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

(Tuis.) #1

256 | Chapter 8: i18n and L10n


Locale-Specific Settings


Beyond simple translation, there are plenty more locale-specific issues. Different
locales, even within the same language, can have vastly different conventions for rep-
resenting dates, times, currency, and numbers.


Luckily, this is more of a data problem than a programming problem. Globalize pro-
vides data to help with all of these issues. The date formatting helpers,Time#localize
andDate#localize, serve as a replacement forTime#strftimethat translates day and
month names (both full and abbreviated):


>> Time.now.strftime("%A, %d %B %Y")
=> "Saturday, 02 June 2007"

>> Locale.set 'en-US'
>> Time.now.localize("%A, %d %B %Y")
=> "Saturday, 02 June 2007"

>> Locale.set 'pl-PL'
>> Time.now.localize("%A, %d %B %Y")
=> "Sobota, 02 Czerwiec 2007"

Thelocalizemethod is also available on Integers and Floats, and provides numbers
localized to the current locale:


>> Locale.set 'en-US'
>> 123456.789.localize
=> "123,456.789"

>> Locale.set 'de-DE'
>> 123456.789.localize
=> "123.456,789"

Globalize also provides aCurrencyclass to handle money. It acts like Tobias Lütke’s
Moneyclass, in that it stores prices as integers in the database. But it is more flexible
in handling multiple currencies. Refer to the API documentation for the full story,
but here is a sample usage:


# app/models/product.rb
class Product < ActiveRecord::Base
composed_of :price, :class_name => 'Globalize::Currency',
:mapping => [%w(price cents)]
end

Then we can create a product:


@product = Product.new :price => Currency.new(1000_00)
puts @product.price.to_s
# >> 1,000.00

TheCurrency#formatmethod formats the currency according to the specifications of
the current locale (which, as usual, is set with theLocale.set method):


Locale.set 'de-DE'
puts @product.price.format(:code => true)
# >> 1.000,00 EUR
Free download pdf