Rails 3.1 - Translating routes

October 26, 2011


This post was originally published in the Rambling Labs Blog on October 26, 2011.


Today, I was wondering if there would be a way to add translated routes automatically in Ruby on Rails. This is for a project I’m currently working on, whose users speak mostly spanish, so I want to make them happy with urls like “/contacto”, “/quienes-somos” and “/trabajos/1” instead of “/contact”, “/about-us”, and “jobs/1”.

So, I googled and there it was: the i18n_routing gem.

This reminded me one more time how awesome is the Ruby community, which is definitely one of the main reasons why I’m loving Ruby and Rails so much.

So back on topic, the gem is easy to install, and only depends on the i18n gem. Run gem install i18n_routing and you should be good to go. It supports rails 2.x as well as 3.x.

Now, for adding the translated routes, you have to wrap your routes in this:

localized(I18n.available_locales) do
  # Your routes here
  # This are just test routes
  resources :users, :jobs

  resource :contact

  match 'home' => 'jobs#index'
end

Then, and this is the most pleasing aspect of the gem, just add your translations to the locale file that you need! In my case, it’s gonna be the config/locales/es.yml. Like this:

es:
  resources:
    users: 'usuarios'
  resource:
    contact: 'contacto'
  named_routes:
    about-us: 'quienes-somos'
  routes:
    jobs:
      as: 'trabajos'
      path_names:
        new: 'nuevo'
        edit: 'editar'

Beautiful!

Note the correspondence between the routes methods and the routes translation tree. The resources and the resource correspond to the resources and resource methods used when defining the routes. Similarly, the named_routes corresponds to the match match. And finally, the routes is a subtree, containing the resource and it’s path names.

That is all… Nice, right?!

You might find more info about it in their wiki.

Oh, I almost forgot. For debugging, you can add a second parameter verbose: true to the localized method. The routes configuration will be printed out when starting the rails console, the application, and even when running the migrations.