254 | Chapter 8: i18n and L10n
Alternatively, the second argument toString#[]can be a hash. The keys correspond
to the names of the interpolation variables, while the values provide the text to be
inserted. The following code is equivalent, but more descriptive and more resilient to
change in the translated text:
puts "Date of birth: {dob} ({age} years old)"[:dob, {:dob => u.dob, :age => u.age}]
# >> Date of birth: 1/1/95 (12 years old)
This example highlights one common problem with localization: it is never straight
translation of text. In most nontrivial situations, the translated text has some level of
dependence on the data that is more complicated than simple string interpolation
(“{age} years”). Later in this chapter, we will see how the Globalize Rails plugin han-
dles these situations.
Gibberish provides good Rails integration. You can automatically set a user’s lan-
guage from a session variable with a simple around filter:
class ApplicationController < ActionController::Base
around_filter :set_language
private
def set_language
Gibberish.use_language(session[:language]) { yield }
end
end
Despite its simplicity, Gibberish has one more trick up its sleeve. If you omit the
string key, one will be generated for you:
lang/es.yml
hello_world: ¡Hola, mundo!
hello.rb
Gibberish.use_language :es
puts "Hello, world!"[:hello_world]
# >> ¡Hola, mundo!
puts "Hello, world!"[]
# >> ¡Hola, mundo!
This method is resilient to small changes (capitalization, punctuation, and anything
else that is removed when folding the string into a symbol), but if this feature is over-
used, you will run into the same fragility problems that gettext presents.
Globalize
For those with heavy localization needs, the Globalize plugin (http://www.globalize-
rails.org/) is the best thing since sliced bread. We will first examine the features of