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

(Tuis.) #1

266 | Chapter 8: i18n and L10n


TheLOCALEShash is a list mapping two-letter language codes to the actual locale
namesthat Globalize uses. The next step is to set up an application-wide filter that
will set the user’s locale so that Globalize knows which translation to look for.


app/controllers/application.rb
class ApplicationController < ActionController::Base
helper :all


before_filter :set_locale

protected

def set_locale
# params overrides session, but en-US is only used if both
# params and session are absent
session[:locale] = LOCALES[params[:locale]] ||
session[:locale] ||
'en-US'
Locale.set session[:locale]
end
end

Theset_localefilter will notice anytime a page is requested with a locale in the
query string (for example,http://localhost:3000/people?locale=es). It will set the locale
so the views are translated into the correct language, and then it will store the cho-
sen locale in the session so that the locale will be used again, even if the next request
has no locale parameter. The locale defaults to en-US if none can be found in the ses-
sion orparams. An application that required user registration would most likely store
the user’s locale preference in the user account, but the session will suffice for our
needs.


One very nice thing that Globalize does for us is to collect a list of text that needs to
be translated. As soon as theString#tmethod is called, if the appropriate transla-
tion is not in place, it is stored away to be translated. We can use Ruby to strip out a
list of needed translations and send them to a translator. Alternatively, we could
build an administrative interface with Rails that allows our translators to log in, see
any text that needs to be translated, and input translations that are used immedi-
ately. For now, we will stick with the simple approach.


Before we can enter the translations, we need to generate the list of needed transla-
tions. Browse to/people?locale=esand click around until you have visited all of the
pages. (As ActionView doesn’t render templates until they are needed, theString#t
methods will not be called until the page is actually needed.) This will populate the
list of required translations, which we can easily extract at the Rails console. All we
need to do is tell Globalize that we are translating into Mexican Spanish, and then
find the translations that have no corresponding Spanish text:

Free download pdf