258 | Chapter 8: i18n and L10n
Locale.set(params[:locale] || Locale.base_language.code)
end
end
After this filter is set up, you can specify the locale for any action within the applica-
tion by adding the appropriate parameter to the URL (http://example.com/posts/
show/34?locale=zh-CN). Alternatively, you can specify the locale parameter with a
custom route:
map.cms_page ':locale/*path_info', :controller => 'pages', :action => 'show'
This route would support a multilingual content-management system, where the
localeparameter determines the language and the*path_infosegment looks up
the page in the database:http://example.com/en-US/about-us/contact-us.
- Declare that the ActiveRecord class in question contains translated data:
class Page < ActiveRecord::Base
translates :title, :body
end - Find an object that needs translation; set the locale, set the text, and save the
object.
Locale.set 'es-MX'
@page.reload
@page.update_attributes! :body => "¡Hola, mundo!" - The ActiveRecord accessors for the attributes specified by the translates
method now automatically check the current locale and look for the proper
translation:
<%= @page.body %>>> "¡Hola, mundo!"
Globalize Example: An Address Book
To illustrate the use of Globalize for view translation all the way through an applica-
tion, we will construct a simple database that functions like an address book. First
we will develop the address book as an English-only application; later, we will see
what is involved in integrating Globalize and adding translations.
We will use a simple SQLite3 database file for storage:
config/database.yml
development:
adapter: sqlite3
database: db/globalize.sqlite3
encoding: utf8
First, we create the model and migration for the Personmodeland its corresponding
people table: