Rocking your application with Rails 2.2 i18n support

Ruby on Rails — Tags: , — admin @ 2:21 pm

I know Sven Fuchs wrote about the Rails i18n core API back in July (when Rails 2.2 was not yet released), but since then, the i18n API has changed a little and now that Rails 2.2 is out I’ll write the steps you need to rock your application with this new excellent support.

1. Configure the I18n module

You need to select the translations files the module will load and the default locale in case the user don’t specify one. As you need to do this only once, you can put the next code in the config/environment.rb file:

I18n.default_locale = "pt-BR"
I18n.load_path += Dir.glob("config/locales/*.yml")

Update: We should add elements to the load_path instead of assigning a new array to not overwrite Rails 2.2 provided paths.

2. Set the locale in each request

You need to tell the I18n module which locale it should use in the current process. This can be done in a filter, before the controller executes the action. A good place to do the filter should be the application controller:

before_filter :set_locale
 
def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

3. Internationalize

From now on the only thing you need to do is translate and localize, so from any place in your application you can call the translate and localize methods (t and l are alias) , for example:

I18n.t 'store.title'
I18n.l Time.now

Now that we know how to get our applications internationalized, I’ll talk about the process.

How does the Rails 2.2 i18n work?

The I18n module stores a backend that implements the localize and translate methods. Every time we call I18n.translate or I18n.localize, the I18n module delegates this calls to the configured backend. Rails 2.2 comes with a default backend called Simple Backend.

The first time the Simple Backend internationalizes something it loads the internationalizations files defined in I18n.load_path .

The internationalizations files

The internationalizations files can be a Ruby Hash or a YAML script:

Ruby Hash

{
  :'pt-BR' => {
    :foo => {
      :bar => "baz"
    }
  }
}

YAML

pt-BR:
  foo:
    bar: baz

Reloading internationalizations files

If for any reason you are using the Simple Backend and you want to load/reload an internationalization file after the first internationalization has been done you can call the load_translations(*file_names) method:

I18n.backend.load_translations("config/locales/es-PE.yml", "config/locales/en-US.yml")

Update: This is considered a hack because no methods in the backend should be called directly and should only be used for testing purpose, when working with script/console for example.

Update2: Since this post there have been created a new method in the I18n module that reloads the translations:

I18n.reload!

This method is not considered a hack! :)

More information

If you want to know about interpolation, pluralization, default values and scopes you should read the corresponded sections in the post from Sven Fuchs. I’m not talking about this features here because nothing has changed and because Sven Fuchs did a great thing explaining them in a simple way.

14 Comments »

  1. Hey, thanks for the awesome writeup!

    Two minor things:

    It probably should be:

    I18n.load_path += Dir.glob(”config/locales/*.yml”)

    so that existing paths (such as those provided by Rails) aren’t overwritten. This is what Karel does in his demo app:

    I18n.load_path += Dir[ File.join(RAILS_ROOT, ‘lib’, ‘locale’, ‘*.{rb,yml}’) ]

    Also, you might want to add a note that any direct access to the backend should rather be considered a hack :) Public I18n methods are always on the I18n module itself, backend implementations might change at any time

    Comment by Sven — November 1, 2008 @ 12:05 pm
  2. Hi Sven, thanks for the corrections, will update the post right now :)

    Comment by dc.rec1 — November 1, 2008 @ 12:09 pm
  3. Eu sai do edge esses dias por uns probs estranhos, voltarei no 2.2.
    Bom saber. Anotado…

    Valeu denovo! Ah… offtpic here, aquela nossa discussion sobre o autosepc… parece que fix na versao 1.1.11 (25/10)

    Comment by nofxx — November 1, 2008 @ 12:13 pm
  4. Hahaha bom saber Marcos. Nem teve tempo de fazer o teste, mas ainda bem parece que temos um problema a menos

    O Rails 2.2 RC1 tem se mostrado bem estavel para mim, ate agora tudo andou bem (:

    Comment by Diego Carrion — November 1, 2008 @ 12:14 pm
  5. A simple question, Who would provide all the country specific locale ? It seems Rails 2.2 doesn’t. Right ?

    Comment by Sanjay — February 2, 2009 @ 9:13 pm
  6. Are you talking about the locale files Sanjay? In that case, you have to populate them manually.

    Comment by Diego Carrion — February 3, 2009 @ 8:29 am
  7. I’m trying to build a system that allows users to submit user-generated translations. If I store those user-generated translations in the database, any thoughts on how I do a “merge” the user-generated translations and my default yml file in the load_path?

    Comment by George Lee — March 24, 2009 @ 3:36 pm
  8. Hey there! I’ve been reading your site for a while now and finally got the bravery to go ahead and give you a shout out from Porter Tx! Just wanted to tell you keep up the good work!

    Comment by Felecia Danza — August 26, 2011 @ 11:57 pm
  9. Thanks for this great information! I really appreciate this. I actually let my husband have a look and he posted it on his blog.

    Comment by HCG diet plan — August 31, 2011 @ 1:40 am
  10. hideshaventspokento you fora whilei think you are spot onwith going for the steel shed instead of using timberit will be much stronger and should last longersiteis excelent,im on here regularand findsome posters are realy helpfull and poster jjay is helping me with my site

    Comment by industrial roofing — September 24, 2011 @ 8:56 am
  11. Hi-Ya! I loves your marvelous website thanks and pls keep on it

    Comment by Free iPhone 4 — October 3, 2011 @ 5:00 pm
  12. Hi-Ya! our family loves your lovely website thanks and pls don’t stop!

    Comment by Free iPhone 4 — October 3, 2011 @ 5:21 pm
  13. This really answered the problem, thank you!

    Comment by military electronics — November 10, 2011 @ 7:13 pm
  14. Thanks for spending the time to discuss this, I feel strongly about it and love reading more on this topic.

    Comment by blister packaging — November 10, 2011 @ 7:13 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2012 Diego Carrion | powered by WordPress with Barecity