Class | I18n::MessageResources |
In: |
message_resources.rb
|
Parent: | Object |
General purpose class for retrieving messages to support i18n. Designed similar to i18n support available in java web frameworks.
The locale specific files are identified using a simple naming convention. The language and country code are appended to the end of the filename before the extension. You can make up your own codes but it is better to use standard codes. Valid ISO language codes can be found here: www.ics.uci.edu/pub/ietf/http/related/iso639.txt . Also you can find a list of ISO country codes here: www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html.
Example filenames: (Note that all files have extention ‘translation’)
messages.translation (The default. It has no languagecode-countrycode) messages_en-us.translation messages_fr-fr.translation
The translation files are simple yaml files with entries of the following format:
key: value range_error: Value not within range {0} to {1}
Applications are coded to the ‘key’. So when translating, translate only the ‘value’.
$KCODE = 'u' require 'jcode'
before_filter :set_content_type def set_content_type @response.headers["Content-Type"] = "text/html; charset=UTF-8" end
require 'message_resources' I18n::MessageResources.basename="#{RAILS_ROOT}/config/i18n/messages"
messages.translation messages_fr-fr.translation
I18n::MessageResources.instance.message(key)
returns the value corresponding to key from messages.translation (the default file)
I18n::MessageResources.instance.message(key, "fr-fr")
returns the value corresponding to key from messages_fr-fr.translation. The idea is to match the locale string (‘fr-fr’ in this case) to the languagecode-countrycode file name.
Assumming entry in messages.translation file of:
range_error: Value not within range {0} to {1} I18n::MessageResources.instance.message("range_error", nil, ["15", "20"])
returns ‘Value not within range 15 to 20’. The {0} and {1} .. are replaced by values in the array argument. Supports any number of replaceable parameters.
To pickup the locale per request in the application_helper.rb file add the following:
def m(key, args=nil) I18n::MessageResources.instance.message(key, request.env['HTTP_ACCEPT_LANGUAGE'],args) end
In the case where the users locale is stored in the session for example in session[:locale] (probably set when the user logged in):
def m(key, args=nil) I18n::MessageResources.instance.message(key, session[:locale], args) end
<%= m 'user_id' %> <%= m ('range_error', ['15', '20']) %>
Author: Antony Joseph