In this second part of a four-part article series on adding support for multiple languages to a Ruby-on-Rails ecomerce application, you will learn how to use Globalize to add this important capability. This article is excerpted from chapter 10 of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
The first line in the sample output prints out the current date, which is localized according to the rules for the base language by calling the localize method. The third line demonstrates how to localize a number in the same way. As you can see, Globalize converts the number 12345.45 to the localized string "12,345.45" .
Currencies are formatted automatically according to the current locale by adding the following to the model:
class Item < ActiveRecord::Base composed_of :price_localized, :class_name => "Globalize::Currency", :mapping => [ %w(price cents) ] end
By calling composed_of , you are telling ActiveRecord that the new price_localized field is of type Globalize::Currency , and that the value for it is taken from the price field, which is specified in cents, since the Globalize::Currency constructor expects this. Creating a book where the price field has the value 100000 and the locale was set to en-US prints out the string $1,000.00 .
Note The price_localized field is not editable because of a limitation in Globalize that might be fixed in the future. This is why we canít use it in a form and need to create a separate field for it.
UPDATING THE BASE LANGUAGE
Be careful when updating the base language, which is used in the views and database, because this breaks the link between the base language and the translations. For instance, suppose that you have a view containing the base language text "Next page" and that you have translated it to Swedish. Now, if you change the base language text to "Show next page," you will need to translate the text again to Swedish, and you will still have the old translation in the database. This is a problem in most applications where you want to be able to update the base language text and still keep the translations.
One way of avoiding this problem is not to change the base language after you have translated it to other languages. A better option is to use a base language that is not one of languages that you want to support (Swahili maybe?), and then never show it to your users by setting the default locale (in the config/environment.rb file) to one of the languages that you want to support. Just use the base language as the key for your translations. So, instead of writing the full text in the view, just write a summary, such as "help_page_text," and translate the text as usual to the target languages. But remember that the users should never see the base language text, because youíve set the default locale to another language.