aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/source/i18n.txt
diff options
context:
space:
mode:
Diffstat (limited to 'railties/doc/guides/source/i18n.txt')
-rw-r--r--railties/doc/guides/source/i18n.txt260
1 files changed, 175 insertions, 85 deletions
diff --git a/railties/doc/guides/source/i18n.txt b/railties/doc/guides/source/i18n.txt
index 76f081e0bc..ba3cc42a5b 100644
--- a/railties/doc/guides/source/i18n.txt
+++ b/railties/doc/guides/source/i18n.txt
@@ -12,7 +12,7 @@ Internationalization is a complex problem. Natural languages differ in so many w
=== The overall architecture of the library
-To solve this the Ruby I18n gem is split into two parts:
+Thus, the Ruby I18n gem is split into two parts:
* The public API which is just a Ruby module with a bunch of public methods and definitions how the library works.
* A shipped backend (which is intentionally named the Simple backend) that implements these methods.
@@ -29,6 +29,14 @@ translate # lookup translations
localize # localize Date and Time objects to local formats
-------------------------------------------------------
+These have the aliases #t and #l so you can use them like this:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t 'store.title'
+I18n.l Time.now
+-------------------------------------------------------
+
There are also attribute readers and writers for the following attributes:
[source, ruby]
@@ -46,9 +54,30 @@ There are just a few, simple steps to get up and running with a I18n support for
=== Configure the I18n module
-First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English.
+Rails will wire up all required settings for you with sane defaults. If you need different settings you can overwrite them easily.
+
+The I18n library will use English (:en) as a *default locale* by default. I.e if you don't set a different locale, :en will be used for looking up translations. Also, Rails adds all files from config/locales/*.rb,yml to your translations load path.
+
+The *translations load path* (I18n.load_path) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
+
+(Hint: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.)
-You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer:
+The default environment.rb says:
+
+[source, ruby]
+-------------------------------------------------------
+# The internationalization framework can be changed
+# to have another default locale (standard is :en) or more load paths.
+# All files from config/locales/*.rb,yml are added automatically.
+# config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')]
+# config.i18n.default_locale = :de
+-------------------------------------------------------
+
+=== Optional: custom I18n configuration setup
+
+For the sake of completeness let's mention that if you do not want to use the environment for some reason you can always wire up things manually, too.
+
+To tell the I18n library where it can find your custom translation files you can specify the load path anywhere in your application - just make sure it gets run before any translations are actually looked up. You might also want to change the default locale. The simplest thing possible is to put the following into an initializer:
[source, ruby]
-------------------------------------------------------
@@ -58,14 +87,12 @@ You can pick whatever directory and translation file naming scheme makes sense f
I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ]
# you can omit this if you're happy with English as a default locale
-I18n.default_locale = :"pt"
+I18n.default_locale = :pt
-------------------------------------------------------
-I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
-
=== Set the locale in each request
-By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en (English).
+By default the I18n library will use :en (English) as a I18n.default_locale for looking up translations (if you do not specify a locale for a lookup).
If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this:
@@ -78,13 +105,15 @@ def set_locale
end
-------------------------------------------------------
-This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section).
+This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt (which is what Google also does).
+
+TIP: For other URL designs, see http://rails-i18n.org/wiki/pages/how-to-encode-the-current-locale-in-the-url[How to encode the current locale in the URL].
Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff.
-=== Internationalize your application
+== Internationalize your application
-The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits.
+The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application. The process of "localization" means to then provide translations and localized formats for these bits. <<1>>
So, let's internationalize something. You most probably have something like this in one of your applications:
@@ -107,7 +136,9 @@ end
<p><%= flash[:notice] %></p>
-------------------------------------------------------
-TODO screenshot
+image:images/i18n/demo_untranslated.png[rails i18n demo untranslated]
+
+=== Adding Translations
Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:
@@ -125,39 +156,66 @@ end
<p><%= flash[:notice] %></p>
-------------------------------------------------------
-TODO insert note about #t helper compared to I18n.t
-
-TODO insert note/reference about structuring translation keys
-
When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing.
-TODO screenshot
+image:images/i18n/demo_translation_missing.png[rails i18n demo translation missing]
+
+NOTE: Rails adds a +t+ (+translate+) helper method to your views so that you do not need to spell out +I18n.t+ all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a &lt;span class="translation_missing"&gt;.
So let's add the missing translations (i.e. do the "localization" part):
[source, ruby]
-------------------------------------------------------
-# lib/locale/en.yml
-en-US:
+# config/locale/en.yml
+en:
hello_world: Hello World
hello_flash: Hello Flash
-# lib/locale/pirate.yml
+# config/locale/pirate.yml
pirate:
hello_world: Ahoy World
hello_flash: Ahoy Flash
-------------------------------------------------------
-There you go. Your application now shows:
+There you go. Because you haven't changed the default_locale I18n will use English. Your application now shows:
+
+image:images/i18n/demo_translated_english.png[rails i18n demo translated to english]
-TODO screenshot
+And when you change the URL to pass the pirate locale you get:
+
+image:images/i18n/demo_translated_pirate.png[rails i18n demo translated to pirate]
+
+NOTE You need to restart the server when you add new locale files.
+
+=== Adding Date/Time formats
+
+Ok, let's add a timestamp to the view so we can demo the date/time localization feature as well. To localize the time format you pass the Time object to I18n.l or (preferably) use Rails' #l helper. You can pick a format by passing the :format option, by default the :default format is used.
[source, ruby]
-------------------------------------------------------
-I18n.t 'store.title'
-I18n.l Time.now
+# app/views/home/index.html.erb
+<h1><%=t :hello_world %></h1>
+<p><%= flash[:notice] %></p
+<p><%= l Time.now, :format => :short %></p>
+-------------------------------------------------------
+
+And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):
+
+[source, ruby]
+-------------------------------------------------------
+# config/locale/pirate.yml
+pirate:
+ time:
+ formats:
+ short: "arrrround %H'ish"
-------------------------------------------------------
+So that would give you:
+
+image:images/i18n/demo_localized_pirate.png[rails i18n demo localized time to pirate]
+
+NOTE Right now you might need to add some more date/time formats in order to make the I18n backend work as expected. See the http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[rails-i18n repository] for starting points.
+
== Overview of the I18n API features
@@ -218,7 +276,7 @@ I18n.t :missing, :default => 'Not here'
If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.
-E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string ‘Not here’ will be returned:
+E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string "Not here" will be returned:
[source, ruby]
-------------------------------------------------------
@@ -246,28 +304,29 @@ I18n.t 'active_record.error_messages'
=== Interpolation
-TODO explain what this is good for
+In many cases you want to abstract your translations so that variables can be interpolated into the translation. For this reason the I18n API provides an interpolation feature.
All options besides :default and :scope that are passed to #translate will be interpolated to the translation:
[source, ruby]
-------------------------------------------------------
-I18n.backend.store_translations 'en', :thanks => 'Thanks {{name}}!'
+I18n.backend.store_translations :en, :thanks => 'Thanks {{name}}!'
I18n.translate :thanks, :name => 'Jeremy'
# => 'Thanks Jeremy!'
-------------------------------------------------------
If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised.
+
=== Pluralization
-TODO explain what this is good for
+In English there's only a singular and a plural form for a given string, e.g. "1 message" and "2 messages". Other languages (http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ar[Arabic], http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ja[Japanese], http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ru[Russian] and many more) have different grammars that have additional or less http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html[plural forms]. Thus, the I18n API provides a flexible pluralization feature.
The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:
[source, ruby]
-------------------------------------------------------
-I18n.backend.store_translations 'en-US', :inbox => { # TODO change this
+I18n.backend.store_translations :en, :inbox => {
:one => '1 message',
:other => '{{count}} messages'
}
@@ -275,7 +334,7 @@ I18n.translate :inbox, :count => 2
# => '2 messages'
-------------------------------------------------------
-The algorithm for pluralizations in en-US is as simple as:
+The algorithm for pluralizations in :en is as simple as:
[source, ruby]
-------------------------------------------------------
@@ -294,7 +353,7 @@ If no locale is passed I18n.locale is used:
[source, ruby]
-------------------------------------------------------
-I18n.locale = :'de'
+I18n.locale = :de
I18n.t :foo
I18n.l Time.now
-------------------------------------------------------
@@ -303,27 +362,27 @@ Explicitely passing a locale:
[source, ruby]
-------------------------------------------------------
-I18n.t :foo, :locale => :'de'
-I18n.l Time.now, :locale => :'de'
+I18n.t :foo, :locale => :de
+I18n.l Time.now, :locale => :de
-------------------------------------------------------
-I18n.locale defaults to I18n.default_locale which defaults to :'en'. The default locale can be set like this:
+I18n.locale defaults to I18n.default_locale which defaults to :en. The default locale can be set like this:
[source, ruby]
-------------------------------------------------------
-I18n.default_locale = :'de'
+I18n.default_locale = :de
-------------------------------------------------------
== How to store your custom translations
-The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. (2)
+The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. <<2>>
For example a Ruby Hash providing translations can look like this:
[source, ruby]
-------------------------------------------------------
{
- :'pt-BR' => {
+ :pt => {
:foo => {
:bar => "baz"
}
@@ -335,18 +394,18 @@ The equivalent YAML file would look like this:
[source, ruby]
-------------------------------------------------------
-"pt-BR":
+pt:
foo:
bar: baz
-------------------------------------------------------
As you see in both cases the toplevel key is the locale. :foo is a namespace key and :bar is the key for the translation "baz".
-Here is a "real" example from the ActiveSupport en-US translations YAML file:
+Here is a "real" example from the ActiveSupport en.yml translations YAML file:
[source, ruby]
-------------------------------------------------------
-"en":
+en:
date:
formats:
default: "%Y-%m-%d"
@@ -364,12 +423,16 @@ I18n.t :short, :scope => 'date.formats'
I18n.t :short, :scope => [:date, :formats]
-------------------------------------------------------
+Generally we recommend using YAML as a format for storing translations. There are cases though where you want to store Ruby lambdas as part of your locale data, e.g. for special date
+
=== Translations for ActiveRecord models
You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names.
For example when you add the following translations:
+[source, ruby]
+-------------------------------------------------------
en:
activerecord:
models:
@@ -378,6 +441,7 @@ en:
user:
login: "Handle"
# will translate User attribute "login" as "Handle"
+-------------------------------------------------------
Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle".
@@ -396,24 +460,21 @@ class User < ActiveRecord::Base
end
-------------------------------------------------------
-The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with:
+The key for the error message in this case is :blank. ActiveRecord will lookup this key in the namespaces:
[source, ruby]
-------------------------------------------------------
-activerecord.errors.messages.models.user.attributes.name.blank
+activerecord.errors.messages.models.[model_name].attributes.[attribute_name]
+activerecord.errors.messages.models.[model_name]
+activerecord.errors.messages
-------------------------------------------------------
-If it's not there it will try:
+Thus, in our example it will try the following keys in this order and return the first result:
[source, ruby]
-------------------------------------------------------
+activerecord.errors.messages.models.user.attributes.name.blank
activerecord.errors.messages.models.user.blank
--------------------------------------------------------
-
-If this is also not there it will use the default message from:
-
-[source, ruby]
--------------------------------------------------------
activerecord.errors.messages.blank
-------------------------------------------------------
@@ -447,28 +508,27 @@ The translated model name and translated attribute name are always available for
So, for example, instead of the default error message "can not be blank" you could use the attribute name like this: "Please fill in your {{attribute}}".
-Count and/or value are available where applicable. Count can be used for pluralization if present:
-
-[grid="all"]
-`---------------------------`----------------`---------------`----------------
-validation with option message interpolation
-validates_confirmation_of - :confirmation -
-validates_acceptance_of - :accepted -
-validates_presence_of - :blank -
-validates_length_of :within, :in :too_short count
-validates_length_of :within, :in :too_long count
-validates_length_of :is :wrong_length count
-validates_length_of :minimum :too_short count
-validates_length_of :maximum :too_long count
-validates_uniqueness_of - :taken value
-validates_format_of - :invalid value
-validates_inclusion_of - :inclusion value
-validates_exclusion_of - :exclusion value
-validates_associated - :invalid value
-validates_numericality_of - :not_a_number value
-validates_numericality_of :odd :odd value
-validates_numericality_of :even :even value
-------------------------------------------------------------------------------
+count and/or value are available where applicable. Count can be used for pluralization if present:
+
+|==================================================================================
+| validation | with option | message | interpolation
+| validates_confirmation_of | - | :confirmation | -
+| validates_acceptance_of | - | :accepted | -
+| validates_presence_of | - | :blank | -
+| validates_length_of | :within, :in | :too_short | count
+| validates_length_of | :within, :in | :too_long | count
+| validates_length_of | :is | :wrong_length | count
+| validates_length_of | :minimum | :too_short | count
+| validates_length_of | :maximum | :too_long | count
+| validates_uniqueness_of | - | :taken | value
+| validates_format_of | - | :invalid | value
+| validates_inclusion_of | - | :inclusion | value
+| validates_exclusion_of | - | :exclusion | value
+| validates_associated | - | :invalid | value
+| validates_numericality_of | - | :not_a_number | value
+| validates_numericality_of | :odd | :odd | value
+| validates_numericality_of | :even | :even | value
+|==================================================================================
==== Translations for the ActiveRecord error_messages_for helper
@@ -479,14 +539,14 @@ Rails ships with the following translations:
[source, ruby]
-------------------------------------------------------
-"en":
+en:
activerecord:
errors:
template:
header:
one: "1 error prohibited this {{model}} from being saved"
other: "{{count}} errors prohibited this {{model}} from being saved"
- body: "There were problems with the following fields:"
+ body: "There were problems with the following fields:"
-------------------------------------------------------
@@ -496,11 +556,12 @@ Rails uses fixed strings and other localizations, such as format strings and oth
TODO list helpers and available keys
+
== Customize your I18n setup
=== Using different backends
-For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ (1) ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.
+For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ <<3>> ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.
That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:
@@ -509,30 +570,59 @@ That does not mean you're stuck with these limitations though. The Ruby I18n gem
I18n.backend = Globalize::Backend::Static.new
-------------------------------------------------------
-TODO expand this ...? list some backends and their features?
-
=== Using different exception handlers
-TODO
+The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:
-* Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend.
-* Explain the default behaviour.
-* Explain the :raise option
+[source, ruby]
+-------------------------------------------------------
+MissingTranslationData # no translation was found for the requested key
+InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
+InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization
+MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed
+ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default)
+UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path
+-------------------------------------------------------
+
+The I18n API will catch all of these exceptions when they were thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for MissingTranslationData exceptions. When a MissingTranslationData exception has been caught it will return the exception’s error message string containing the missing key/scope.
+
+The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
+
+In other contexts you might want to change this behaviour though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module:
-* Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing"
-* Example 2: for tests you might want a handler that just raises all exceptions all the time
-* Example 3: a handler
+[source, ruby]
+-------------------------------------------------------
+module I18n
+ def just_raise_that_exception(*args)
+ raise args.first
+ end
+end
+
+I18n.exception_handler = :just_raise_that_exception
+-------------------------------------------------------
+
+This would re-raise all caught exceptions including MissingTranslationData.
+
+Another example where the default behaviour is less desirable is the Rails TranslationHelper which provides the method #t (as well as #translate). When a MissingTranslationData exception occurs in this context the helper wraps the message into a span with the css class translation_missing.
+
+To do so the helper forces I18n#translate to raise exceptions no matter what exception handler is defined by setting the :raise option:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t :foo, :raise => true # always re-raises exceptions from the backend
+-------------------------------------------------------
== Resources
-* http://rails-i18n.org
== Footnotes
-(1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.
+[[[1]]] Or, to quote http://en.wikipedia.org/wiki/Internationalization_and_localization[Wikipedia]: _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_
+
+[[[2]]] Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
-(2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
+[[[3]]] One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.
== Credits