Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Rails L10n | 253

users to change their locale and dialect) yourself. But there are good examples on
that page, and it is a good start. Also seehttp://jonathan.tron.name/articles/2007/03/
30/gettext-and-rails for a few miscellaneous concerns if you decide on this approach.


Gibberish


Gettext has a few disadvantages, the primary one being that translated strings are
keyed by the original string. Under gettext, even changing"Hello, world!"to"Hello
world!"would require updating that entry in every.pofile and recompiling every-
thing. Even if only the English version changed, every file would require modifica-
tion, as the strings are keyed on the exact source text.


Gibberish,*by Chris Wanstrath, is a very lightweight Rails localization plugin. Like
gettext, it is based on replacing individual strings from a language-dependent
resource file. However, it is much simpler (and, correspondingly, somewhat less flex-
ible) than gettext. It is also tailored toward Ruby’s style and Rails’ needs.


First, install the Rails plugin from Subversion. Itsinit.rbfile will load Gibberish and
any translation files under thelang directory:


$ script/plugin install svn://errtheblog.com/svn/plugins/gibberish

Unlike gettext, which scans your source files to generate translation files, Gibberish
requires you to create translation files yourself. However, they are very easy to create.
A sample Gibberish language file looks like this:


lang/es.yml
welcome: ¡Hola, mundo!


The source syntax is very much like gettext, but with the addition of a symbol tag,
used as a key in place of the string itself. Gibberish overrides theString#[]method
to provide nice syntax for this:


puts "Hello, world!"[:welcome]
# >> Hello, world!

The default language is English, so if no language is selected, that statement will out-
put “Hello, world!”. We can change the default language:


Gibberish.use_language :es

puts "Hello, world!"[:welcome]
# >> ¡Hola, mundo!

Interpolation variables are available, and values for them can be passed as positional
or keyword arguments. IfString#[]is passed non-hash arguments, the second and
subsequent arguments are interpolated into the string, in order:


puts "Date of birth: {dob} ({age} years old)"[:dob, u.dob, u.age]
# >> Date of birth: 1/1/95 (12 years old)

*http://require.errtheblog.com/plugins/browser/gibberish/README

Free download pdf