rails 2.2 i18n for the impatients

Posted by kain Thu, 24 Jul 2008 18:16:00 GMT

it’s all very straightforward and you can taste it already, grab a copy of edge rails and do this:

create a directory called "locale" in lib, and place two files, for example en-US.rb and it-IT.rb

Inside write:

# en-US.rb
I18n.store_translations 'en-US',
:yes => "yes",
:no => "no",
:action_show => "show",
:welcome => 'Welcome {{name}}!',
:inbox => ['1 message', '{{count}} messages']

as you can see we now have some symbol with our translation, do the same for it-IT.

it’s worth noticing the last two lines, {{name}} is a placeholder, let’s see how the things works.

open your ApplicationHelper and use this shortcut

  def t(*args)
    translate(*args)
  end

after that open a view and put this:

t(:welcome, :name => "kain") # sorry for the formatting

next: ApplicationController

before_filter :set_locale

  def set_locale
    default_locale = 'en-US'

    locale = params[:locale] || session[:locale] || (this_user.site_language if is_logged_in?) || default_locale
    session[:locale] = locale

    I18n.locale = locale
    I18n.populate do
      require "lib/locale/#{locale}.rb" # << WARNING: this is dangerous, change the method to load libs, maybe initializer
    end
  end

voilà, all done.

thanks to http://almosteffortless.com/2008/07/21/simple-localization-in-rails-22/

Trackbacks

Use the following link to trackback from your own site:
http://www.icoretech.org/trackbacks?article_id=rails-2-2-i18n-for-the-impatients&day=24&month=07&year=2008

Comments

Leave a comment

Comments