Archive: October 2008

Internationalization in Rails 2.2

18 October, 2008 01:00

In the darkness of a night, exhausted after long hours of your day-work, you build a new kicking ass web application.

You want to change the world and make your application accessible to all good people out there… that’s why your a new-born baby has to speak several languages!

Now with Rails 2.2 it is easy! All you need to know is two API methods: I18n.transate aka I18n.t and I18n.localize aka I18n.l …and somebody who can help you with translation to exotic languages like Chinese, Thai or Polish.

In this post you will find a quick, step-by-step tutorial how to add internationalization to your Ruby on Rails application. Please be aware it is a very simple example and you have to “live on the edge” to fully benefit from this post… ok… no more fluff and let’s dive into code together!

First of all let’s create Rails app, freeze edge and create resource to test things out.

rails speak2me
cd speak2me
rake rails:freeze:edge
./script/generate resource friend
./script/generate migration AddNameToFriend name:string

Now it is time to create a directory named locales which will contain our translations….

mkdir config/locales

…and create there two translations for English and Polish language

# config/locales/en-US.yml
"en-US":
  main:
    hello: "Hello Darling!"
# config/locales/pl-PL.yml
"pl-PL":
  main:
    hello: 'Witaj Kochanie!'

In the release 2.2 of Ruby on Rails framework there was introduced the I18n module.

In the configuration file we will encapsulate details of what locales are available, where they are kept, and what is to be used as the default. Let’s create i18n.rb file under initializers directory.

# config/initializers/i18n.rb
I18n.load_path += Dir[ File.join(RAILS_ROOT, 'config', 'locales', '*.{rb,yml}') ]
I18n.default_locale = "en-US"

We have just configured I18n module and now it is right time to get use of it in our controller and view files.

First of all let’s add method to set locale. We will create a before_filter in the common base class for all of our controllers.

class ApplicationController < ActionController::Base
  before_filter :set_locale
protected
  def set_locale
    session[:locale] = params[:locale] if params[:locale]
    I18n.locale = session[:locale] || I18n.default_locale
  end
end

Next we will add index.html.erb file with localized version of greeting.

# views/friends/index.html.erb
<%= I18n.t "main.hello" %>

The only thing left is to update route configuration and test things out.

# config/routes.rb
ActionController::Routing::Routes.draw do |map|
  map.resources :friends
  map.root :controller => 'friends'
end

Open your browser and have fun… default locale is en-US but as soon as you change locale param you will get polish version of text.

I have mentioned that in order to localize you Rails 2.2 application you should be aware of two API methods: I18n.transate and I18n.localize.

So far we used only alias to one of the methods - I18n.t. So… what is a function of I18n.localize method?. Well.. this one basically allows you to format Date and Time objects for a certain locale. In order to see it in action we should update our file with polish locale and add one line in view file.

# views/friends/index.html.erb
<%= I18n.t "main.hello" %>
<%= I18n.l Time.now %>
# config/locales/pl-PL.yml
"pl-PL":
    main:
        hello: 'Witaj Kochanie!'

    date:
        formats:
            default: "%d.%m.%Y"
            short: "%e. %b"
            long: "%e. %B %Y"
            only_day: "%e"

        day_names: [Niedziela, Poniedziełek, Wtorek, Środa, Czwartek, Piątek, Sobota]
        abbr_day_names: [N, Pn, Wt, Śr, Cz, Pt, So]
        month_names: [~, Styczeń, Luty, Marzec, Kwiecień, Maj, Czerwiec, Lipiec, Sierpień, Wrzesień, Październik, Listopad, Grudzień]
        abbr_month_names: [~, Sty, Lut, Mar, Kwi, Maj, Cze, Lip, Sie, Wrz, Paz, Lis, Gru]
        order: [ :day, :month, :year ]

    time:
        formats:
            default: "%A, %e. %B %Y, %H:%M"
            time: "%H:%M"
            short: "%e. %B, %H:%M"
            long: "%A, %e. %B %Y, %H:%M"
            only_second: "%S"

        am: "przed południem"
        pm: "po południu"

That’s all folks!

For more details about internationalization in the latest version of Ruby on Rails I strongly recommend to visit Sven Fuchs’s blog. You will get knowledge directly from a source.

Posted in: Software | 3 Comments » tags: