Multiple Language Support for an Ecommerce Application
If you're building an ecommerce application that will do business in more than one country, you will probably need to support multiple languages. Indeed, you might face this problem even if you're doing business in just one state in the US, such as Florida or Texas. This four-part article series will show you how to add support for multiple languages to a Ruby-on-Rails ecomerce application. It is excerpted from chapter 10 of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Multiple Language Support for an Ecommerce Application - Localizing with Globalize (Page 3 of 4 )
Globalize uses the term base language for the language from which you are translating. So, if you write the text in your views and database in English, this means your base language is English. Globalize uses the base language as the key for other translations. For example, a view containing the following text inserts a record into the globalize_translations table, where the text Picture is stored in the tr_key column:
<%= 'Picture'.t %>
When translating into Swedish, for example, a new row is inserted, where the tr_key contains the text Picture and the text column contains the translated text Bild .
Using Globalize, you can translate the base language to other languages, by telling Globalize that the text should be translatable. You tell Globalize that text stored in a view should be translatable by appending .t ( translate ) to the string, as follows:
In this example, the base language is English. The first line, Locale.set('sv') , sets the locale to Swedish, and the second line prints out Tuesday in Swedish (Tisdag). The fourth line sets the locale to Finnish, and the fifth line prints out Wednesday in Finnish (keskiviikko). This example doesn’t require you to translate the weekdays to Swedish and Finnish, because Globalize already contains these translations. However, if you want to add translations, use Locale.set_translation and Locale.set_pluralized_translation , as explained in the Globalize API documentation ( http://globalize.rubyforge.org/ ).
All the work is done behind the scenes by Globalize. The translated text is pulled out of the database with a query similar to this one:
SELECT * FROM globalize_translations WHERE ? (tr_key = 'Tuesday' AND language_id = 6024 AND pluralization_index = 1) ? AND ( (globalize_translations.`type` = 'ViewTranslation' ) ) LIMIT 1
Globalize caches the view translations in memory to avoid unnecessary database hits.