What's New In Rails Edge: i18n 1

Posted by luca
on Friday, July 18

Ruby on Rails has just integrated a basic support for i18n.

ActiveSupport

ActiveSupport now includes the i18n gem which provides the API and the settings for the default locale: en-US.
The gem abstracts the repository where the translations are stored, so all the plugin authors could write their own mechanism. The bundled repository is called Simple and stores all the settings in memory.

Declaring a locale is quite easy:

I18n.backend.store_translations :'it-IT', {
  :support => {
    :array => {
      :sentence_connector => 'e'
    }
  },
  :date => {
    :formats => {
      :default => "%d/%m/%Y",
      :short => "%d %b",
      :long => "%d %B %Y",
    },
    :day_names => %w(Lunedì Martedì Mercoledì Giovedì Venerdì Sabato Domenica),
    :abbr_day_names => %w(Lun Mar Mer Gio Ven Sab Dom),
    :month_names => %w(Gennaio Febbraio Marzo Aprile Maggio Giugno Luglio Agosto Settembre Ottobre Novembre Dicembre).unshift(nil),
    :abbr_month_names => %w(Gen Feb Mar Apr Mag Giu Lug Ago Set Ott Nov Dic).unshift(nil),
    :order => [:day, :month, :year]
  },
  :time => {
    :formats => {
      :default => "%a, %d %b %Y %H:%M:%S %z",
      :short => "%d %b %H:%M",
      :long => "%B %d, %Y %H:%M",
    },
    :am => 'am',
    :pm => 'pm'
  }
}

How can I translate or localize?

I18n.locale = 'it-IT'
I18n.t :hello   # => Ciao
I18n.l Time.now # => "Ven, 18 Lug 2008 10:58:14 +0200"

I18n#t is also useful to fetch locale defaults:
I18n.t :'time.formats.short' # => %d %b %H:%M

ActiveRecord

ActiveRecord now returns localized error messages for validations.

You may wish to declare your messages:

I18n.backend.store_translations :'it-IT', {
  :active_record => {
    :error_messages => {
      :inclusion => "non è incluso nella lista"
      # ...
    }
  }
}

ActionPack

ActionView now supports translations and localization for time and currency helpers (i.e. distance_of_time_in_words, number_to_currency).


UPDATE 2008-07-19: Sven Fuchs wrote a i18n Rails manifesto and a technical post about the i18n API.