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.txt273
1 files changed, 206 insertions, 67 deletions
diff --git a/railties/doc/guides/source/i18n.txt b/railties/doc/guides/source/i18n.txt
index 2638807761..4465a77289 100644
--- a/railties/doc/guides/source/i18n.txt
+++ b/railties/doc/guides/source/i18n.txt
@@ -1,9 +1,25 @@
The Rails Internationalization (I18n) API
=========================================
-The Ruby I18n (shorthand for _internationalization_) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or providing multi-language support in your application.
+The Ruby I18n (shorthand for _internationalization_) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for *translating your application to a single custom language* other than English or for *providing multi-language support* in your application.
-NOTE: The Ruby I18n framework provides you with all neccessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available. See Rails http://rails-i18n.org/wiki[I18n Wiki] for more information.
+The process of "internationalization" usually means to abstract all strings and other locale specific bits (such as date or currency formats) out of your application. The process of "localization" means to provide translations and localized formats for these bits. <<1>>
+
+So, in the process of _internationalizing_ your Rails application you have to:
+
+* Ensure you have support for i18n
+* Tell Rails where to find locale dictionaries
+* Tell Rails how to set, preserve and switch locale
+
+In the process of _localizing_ your application you'll probably want to do following three things:
+
+* Replace or supplement Rail's default locale -- eg. date and time formats, month names, ActiveRecord model names, etc
+* Abstract texts in your application into keyed dictionaries -- eg. flash messages, static texts in your views, etc
+* Store the resulting dictionaries somewhere
+
+This guide will walk you through the I18n API and contains a tutorial how to internationalize a Rails application from the start.
+
+NOTE: The Ruby I18n framework provides you with all neccessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available, which add additional functionality or features. See Rails http://rails-i18n.org/wiki[I18n Wiki] for more information.
== How I18n in Ruby on Rails works
@@ -78,6 +94,8 @@ This means, that in the +:en+ locale, the key _hello_ will map to _Hello world_
The I18n library will use *English* as a *default locale*, ie. if you don't set a different locale, +:en+ will be used for looking up translations.
+NOTE: The i18n library takes *pragmatic approach* to locale keys (after http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en[some discussion]), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-UK+, which are traditionally used for separating "languages" and "regional setting" or "dialects". (For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-UK+, you would have €. Also, insults would be different in American and British English :) Reason for this pragmatic approach is that most of the time, you usually care about making your application available in different "languages", and working with locales is much simpler this way. However, nothing stops you from separating regional and other settings in the traditional way. In this case, you could eg. inherit from the default +en+ locale and then provide UK specific settings in a +:en-UK+ dictionary.
+
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.
NOTE: 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.
@@ -116,7 +134,7 @@ If you want to translate your Rails application to a *single language other than
However, you would probably like to *provide support for more locales* in your application. In such case, you need to set and pass the locale between requests.
-WARNING: You may be tempted to store choosed locale in a _session_ or a _cookie_. *Do not do so*. The locale should be transparent and a part of the URL. This way you don't break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content. A fancy word for this would be that you're being http://en.wikipedia.org/wiki/Representational_State_Transfer[_RESTful_]. There may be some exceptions to this rule, which are discussed below.
+WARNING: You may be tempted to store choosed locale in a _session_ or a _cookie_. *Do not do so*. The locale should be transparent and a part of the URL. This way you don't break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content. A fancy word for this would be that you're being http://en.wikipedia.org/wiki/Representational_State_Transfer[_RESTful_]. Read more about RESTful approach in http://www.infoq.com/articles/rest-introduction[Stefan Tilkov's articles]. There may be some exceptions to this rule, which are discussed below.
The _setting part_ is easy. You can set locale in a +before_filter+ in the ApplicationController like this:
@@ -125,17 +143,17 @@ The _setting part_ is easy. You can set locale in a +before_filter+ in the Appli
before_filter :set_locale
def set_locale
# if params[:locale] is nil then I18n.default_locale will be used
- I18n.locale = params[:locale]
+ I18n.locale = params[:locale]
end
-------------------------------------------------------
-This requires you to pass the locale as a URL query parameter as in +http://example.com/books?locale=pt+. (This is eg. Google's approach). So +http://localhost:3000?locale=pt+ will load the Portugese localization, whereas +http://localhost:3000?locale=de+ would load the German localization, and so on.
+This requires you to pass the locale as a URL query parameter as in +http://example.com/books?locale=pt+. (This is eg. Google's approach). So +http://localhost:3000?locale=pt+ will load the Portugese localization, whereas +http://localhost:3000?locale=de+ would load the German localization, and so on. You may skip the next section and head over to the *Internationalize your application* section, if you want to try things out by manually placing locale in the URL and reloading the page.
Of course, you probably don't want to manually include locale in every URL all over your application, or want the URLs look differently, eg. the usual +http://example.com/pt/books+ versus +http://example.com/en/books+. Let's discuss the different options you have.
IMPORTANT: Following examples rely on having locales loaded into your application available as an array of strings like +["en", "es", "gr"]+. This is not inclued in current version of Rails 2.2 -- forthcoming Rails version 2.3 will contain easy accesor +available_locales+. (See http://github.com/svenfuchs/i18n/commit/411f8fe7[this commit] and background at http://rails-i18n.org/wiki/pages/i18n-available_locales[Rails I18n Wiki].)
-We have to include support for getting available locales manually in an initializer like this:
+So, for having available locales easily available in Rails 2.2, we have to include this support manually in an initializer, like this:
[source, ruby]
-------------------------------------------------------
@@ -172,7 +190,7 @@ end
=== Setting locale from the domain name
-One option you have is to set the locale from the domain name, where your application runs. For example, we want +www.example.com+ to load English (or default) locale, and +www.example.es+ to load Spanish locale. Thus the _top-level domain name_ is used for locale setting. This has several advantages:
+One option you have is to set the locale from the domain name where your application runs. For example, we want +www.example.com+ to load English (or default) locale, and +www.example.es+ to load Spanish locale. Thus the _top-level domain name_ is used for locale setting. This has several advantages:
* Locale is an _obvious_ part of the URL
* People intuitively grasp in which language the content will be displayed
@@ -213,22 +231,107 @@ def extract_locale_from_subdomain
end
-------------------------------------------------------
+If your application includes a locale switching menu, you would then have something like this in it:
+
+[source, ruby]
+-------------------------------------------------------
+link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['REQUEST_URI']}")
+-------------------------------------------------------
+
+assuming you would set +APP_CONFIG[:deutsch_website_url]+ to some value like +http://www.application.de+.
+
+This solution has aforementioned advantages, however, you may not be able or may not want to provide different localizations ("language versions") on different domains. The most obvious solution would be to include locale code in the URL params (or request path).
+
=== Setting locale from the URL params
-* TODO : Based on *+default_url options+*, http://github.com/karmi/test_default_url_options/blob/master/app/controllers/application.rb#L22-26
+Most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the +I18n.locale = params[:locale]+ _before_filter_ in the first example. We would like to have URLs like +www.example.com/books?locale=ja+ or +www.example.com/ja/books+ in this case.
-* TODO : Discussion of plugins (translate_routes and routing_filter)
+This approach has almost the same set of advantages as setting the locale from domain name: namely that it's RESTful and in accord with rest of the World Wide Web. It does require a little bit more work to implement, though.
+Getting the locale from +params+ and setting it accordingly is not hard; including it in every URL and thus *passing it through the requests* is. To include an explicit option in every URL (eg. +link_to( books_url(:locale => I18n.locale) )+) would be tedious and probably impossible, of course.
-TIP: For setting locale from URL 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] in the Rails i18n Wiki.
+Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its http://api.rubyonrails.org/classes/ActionController/Base.html#M000515[+*ApplicationController#default_url_options*+], which is useful precisely in this scenario: it enables us to set "defaults" for http://api.rubyonrails.org/classes/ActionController/Base.html#M000503[+url_for+] and helper methods dependent on it (by implementing/overriding this method).
-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.
+We can include something like this in our ApplicationController then:
-== Internationalize your application
+[source, ruby]
+-------------------------------------------------------
+# app/controllers/application_controller.rb
+def default_url_options(options={})
+ logger.debug "default_url_options is passed options: #{options.inspect}\n"
+ { :locale => I18n.locale }
+end
+-------------------------------------------------------
+
+Every helper method dependent on +url_for+ (eg. helpers for named routes like +root_path+ or +root_url+, resource routes like +books_path+ or +books_url+, etc.) will now *automatically include the locale in the query string*, like this: +http://localhost:3001/?locale=ja+.
+
+You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of application domain: and URLs should reflect this.
+
+You probably want URLs look like this: +www.example.com/en/books+ (which loads English locale) and +www.example.com/nl/books+ (which loads Netherlands locale). This is achievable with the "over-riding +default_url_options+" strategy from above: you just have to set up your routes with http://api.rubyonrails.org/classes/ActionController/Resources.html#M000354[+path_prefix+] option in this way:
+
+[source, ruby]
+-------------------------------------------------------
+# config/routes.rb
+map.resources :books, :path_prefix => '/:locale'
+-------------------------------------------------------
+
+Now, when you call +books_path+ method you should get +"/en/books"+ (for the default locale). An URL like +http://localhost:3001/nl/books+ should load the Netherlands locale, then, and following calls to +books_path+ should return +"/nl/books"+ (because the locale changed).
-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>>
+Of course, you need to take special care of root URL (usually "homepage" or "dashboard") of your application. An URL like +http://localhost:3001/nl+ will not work automatically, because the +map.root :controller => "dashboard"+ declaration in your +routes.rb+ doesn't take locale into account. (And rightly so. There's only one "root" URL.)
-So, let's internationalize something. You most probably have something like this in one of your applications:
+You would probably need to map URLs like these:
+
+[source, ruby]
+-------------------------------------------------------
+# config/routes.rb
+map.dashboard '/:locale', :controller => "dashboard"
+-------------------------------------------------------
+
+Do take special care about the *order of your routes*, so this route declaration does not "eat" other ones. (You may want to add it directly before the +map.root+ declaration.)
+
+IMPORTANT: This solution has currently one rather big *downside*. Due to the _default_url_options_ implementation, you have to pass the +:id+ option explicitely, like this: +link_to 'Show', book_url(:id => book)+ and not depend on Rails' magic in code like +link_to 'Show', book+. If this should be a problem, have a look on two plugins which simplify working with routes in this way: Sven Fuchs's http://github.com/svenfuchs/routing-filter/tree/master[_routing_filter_] and Raul Murciano's http://github.com/raul/translate_routes/tree/master[_translate_routes_]. See also the page http://rails-i18n.org/wiki/pages/how-to-encode-the-current-locale-in-the-url[How to encode the current locale in the URL] in the Rails i18n Wiki.
+
+=== Setting locale from the client supplied information
+
+In specific cases, it would make sense to set locale from client supplied information, ie. not from URL. This information may come for example from users' preffered language (set in their browser), can be based on users' geographical location inferred from their IP, or users can provide it simply by choosing locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites -- see the box about _sessions_, _cookies_ and RESTful architecture above.
+
+
+==== Using Accept-Language
+
+One source of client supplied information would be an +Accept-Language+ HTTP header. People may http://www.w3.org/International/questions/qa-lang-priorities[set this in their browser] or other clients (such as _curl_).
+
+A trivial implementation of using +Accept-Language+ header would be:
+
+[source, ruby]
+-------------------------------------------------------
+def set_locale
+ logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
+ I18n.locale = extract_locale_from_accept_language_header
+ logger.debug "* Locale set to '#{I18n.locale}'"
+end
+private
+def extract_locale_from_accept_language_header
+ request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
+end
+-------------------------------------------------------
+
+Of course, in production environment you would need much robust code, and could use a plugin such as Iaian Hecker's http://github.com/iain/http_accept_language[http_accept_language].
+
+==== Using GeoIP (or similar) database
+
+Another way of choosing the locale from client's information would be to use a database for mapping client IP to region, such as http://www.maxmind.com/app/geolitecountry[GeoIP Lite Country]. The mechanics of the code would be very similar to the code above -- you would need to query database for user's IP, and lookup your preffered locale for the country/region/city returned.
+
+==== User profile
+
+You can also provide users of your application with means to set (and possibly over-ride) locale in your application interface, as well. Again, mechanics for this approach would be very similar to the code above -- you'd probably let users choose a locale from a dropdown list and save it to their profile in database. Then you'd set the locale to this value.
+
+== Internationalizing your application
+
+OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale should be used and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff.
+
+Let's _internationalize_ our application, ie. abstract every locale-specific parts, and that _localize_ it, ie. provide neccessary translations for these abstracts.
+
+You most probably have something like this in one of your applications:
[source, ruby]
-------------------------------------------------------
@@ -253,7 +356,7 @@ 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:
+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:
[source, ruby]
-------------------------------------------------------
@@ -269,13 +372,13 @@ end
<p><%= flash[:notice] %></p>
-------------------------------------------------------
-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.
+When you now render this view, it will show an error message which tells you that the translations for the keys +:hello_world+ and +:hello_flash+ are missing.
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;.
+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 +<span class="translation_missing">+.
-So let's add the missing translations (i.e. do the "localization" part):
+So let's add the missing translations into the dictionary files (i.e. do the "localization" part):
[source, ruby]
-------------------------------------------------------
@@ -290,19 +393,19 @@ pirate:
hello_flash: Ahoy Flash
-------------------------------------------------------
-There you go. Because you haven't changed the default_locale I18n will use English. 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_en.png[rails i18n demo translated to english]
-And when you change the URL to pass the pirate locale you get:
+And when you change the URL to pass the pirate locale (+http://localhost:3000?locale=pirate+), you'll 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.
+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.
+OK! Now 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]
-------------------------------------------------------
@@ -327,17 +430,53 @@ 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.
+TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected. Of course, there's a great chance that somebody already did all the work by *translating Rails's defaults for your locale*. See the http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[rails-i18n repository at Github] for an archive of various locale files. When you put such file(s) in +config/locale/+ directory, they will automatically ready for use.
+
+=== Organization of locale files
+When you are using the default SimpleStore, shipped with the i18n library, you store dictionaries in plain-text files on the disc. Putting translations for all parts of your application in one file per locale could be hard to manage. You can store these files in a hierarchy which makes sense to you.
+
+For example, your +config/locale+ directory could look like this:
+
+-------------------------------------------------------
+|-defaults
+|---es.rb
+|---en.rb
+|-models
+|---book
+|-----es.rb
+|-----en.rb
+|-views
+|---defaults
+|-----es.rb
+|-----en.rb
+|---books
+|-----es.rb
+|-----en.rb
+|---users
+|-----es.rb
+|-----en.rb
+|---navigation
+|-----es.rb
+|-----en.rb
+-------------------------------------------------------
+
+This way, you can separate model and model attribute names from text inside views, and all of this from the "defaults" (eg. date and time formats).
+
+Other stores for the i18n library could provide different means of such separation.
+
+Do check the http://rails-i18n.org/wiki[Rails i18n Wiki] for list of tools available for managing translations.
== Overview of the I18n API features
-The following purposes are covered:
+You should have good understanding of using the i18n library now, knowing all neccessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth.
+
+Covered are features like these:
-* lookup translations
-* interpolate data into translations
-* pluralize translations
-* localize dates, numbers, currency etc.
+* looking up translations
+* interpolating data into translations
+* pluralizing translations
+* localizing dates, numbers, currency etc.
=== Looking up translations
@@ -351,14 +490,14 @@ I18n.t :message
I18n.t 'message'
-------------------------------------------------------
-translate also takes a :scope option which can contain one or many additional keys that will be used to specify a “namespace” or scope for a translation key:
++translate+ also takes a +:scope+ option which can contain one or many additional keys that will be used to specify a “namespace” or scope for a translation key:
[source, ruby]
-------------------------------------------------------
I18n.t :invalid, :scope => [:active_record, :error_messages]
-------------------------------------------------------
-This looks up the :invalid message in the Active Record error messages.
+This looks up the +:invalid+ message in the Active Record error messages.
Additionally, both the key and scopes can be specified as dot separated keys as in:
@@ -389,7 +528,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]
-------------------------------------------------------
@@ -417,9 +556,9 @@ I18n.t 'active_record.error_messages'
=== Interpolation
-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.
+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:
+All options besides +:default+ and +:scope+ that are passed to +#translate+ will be interpolated to the translation:
[source, ruby]
-------------------------------------------------------
@@ -428,14 +567,14 @@ 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.
+If a translation uses +:default+ or +:scope+ as a interpolation variable an I+18n::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
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:
+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]
-------------------------------------------------------
@@ -447,22 +586,22 @@ I18n.translate :inbox, :count => 2
# => '2 messages'
-------------------------------------------------------
-The algorithm for pluralizations in :en is as simple as:
+The algorithm for pluralizations in +:en+ is as simple as:
[source, ruby]
-------------------------------------------------------
entry[count == 1 ? 0 : 1]
-------------------------------------------------------
-I.e. the translation denoted as :one is regarded as singular, the other is used as plural (including the count being zero).
+I.e. the translation denoted as +:one+ is regarded as singular, the other is used as plural (including the count being zero).
-If the lookup for the key does not return an Hash suitable for pluralization an I18n::InvalidPluralizationData exception is raised.
+If the lookup for the key does not return an Hash suitable for pluralization an +18n::InvalidPluralizationData+ exception is raised.
=== Setting and passing a locale
-The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current like, e.g., Time.zone) or can be passed as an option to #translate and #localize.
+The locale can be either set pseudo-globally to +I18n.locale+ (which uses +Thread.current+ like, e.g., +Time.zone+) or can be passed as an option to +#translate+ and +#localize+.
-If no locale is passed I18n.locale is used:
+If no locale is passed +I18n.locale+ is used:
[source, ruby]
-------------------------------------------------------
@@ -479,7 +618,7 @@ 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]
-------------------------------------------------------
@@ -512,9 +651,9 @@ pt:
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".
+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.yml translations YAML file:
+Here is a "real" example from the ActiveSupport +en.yml+ translations YAML file:
[source, ruby]
-------------------------------------------------------
@@ -526,7 +665,7 @@ en:
long: "%B %d, %Y"
-------------------------------------------------------
-So, all of the following equivalent lookups will return the :short date format "%B %d":
+So, all of the following equivalent lookups will return the +:short+ date format +"%B %d"+:
[source, ruby]
-------------------------------------------------------
@@ -536,11 +675,11 @@ 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
+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 Active Record 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.
+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:
@@ -556,7 +695,7 @@ en:
# will translate User attribute "login" as "Handle"
-------------------------------------------------------
-Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle".
+Then +User.human_name+ will return "Dude" and +User.human_attribute_name(:login)+ will return "Handle".
==== Error message scopes
@@ -564,7 +703,7 @@ Active Record validation error messages can also be translated easily. Active Re
This gives you quite powerful means to flexibly adjust your messages to your application's needs.
-Consider a User model with a validates_presence_of validation for the name attribute like this:
+Consider a User model with a +validates_presence_of+ validation for the name attribute like this:
[source, ruby]
-------------------------------------------------------
@@ -573,7 +712,7 @@ class User < ActiveRecord::Base
end
-------------------------------------------------------
-The key for the error message in this case is :blank. Active Record will lookup this key in the namespaces:
+The key for the error message in this case is +:blank+. Active Record will lookup this key in the namespaces:
[source, ruby]
-------------------------------------------------------
@@ -619,9 +758,9 @@ This way you can provide special translations for various error messages at diff
The translated model name, translated attribute name, and value are always available for interpolation.
-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}}".
+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, where available, can be used for pluralization if present:
++count+, where available, can be used for pluralization if present:
|=====================================================================================================
| validation | with option | message | interpolation
@@ -651,7 +790,7 @@ count, where available, can be used for pluralization if present:
==== Translations for the Active Record error_messages_for helper
-If you are using the Active Record error_messages_for helper you will want to add translations for it.
+If you are using the Active Record +error_messages_for+ helper you will want to add translations for it.
Rails ships with the following translations:
@@ -674,23 +813,23 @@ Rails uses fixed strings and other localizations, such as format strings and oth
==== ActionView helper methods
-* distance_of_time_in_words translates and pluralizes its result and interpolates the number of seconds, minutes, hours and so on. See http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51[datetime.distance_in_words] translations.
+* +distance_of_time_in_words+ translates and pluralizes its result and interpolates the number of seconds, minutes, hours and so on. See http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51[datetime.distance_in_words] translations.
-* datetime_select and select_month use translated month names for populating the resulting select tag. See http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15[date.month_names] for translations. datetime_select also looks up the order option from http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18[date.order] (unless you pass the option explicitely). All date select helpers translate the prompt using the translations in the http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83[datetime.prompts] scope if applicable.
+* +datetime_select+ and +select_month+ use translated month names for populating the resulting select tag. See http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15[date.month_names] for translations. +datetime_select+ also looks up the order option from http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18[date.order] (unless you pass the option explicitely). All date select helpers translate the prompt using the translations in the http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83[datetime.prompts] scope if applicable.
-* The number_to_currency, number_with_precision, number_to_percentage, number_with_delimiter and humber_to_human_size helpers use the number format settings located in the http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2[number] scope.
+* The +number_to_currency+, +number_with_precision+, +number_to_percentage+, +number_with_delimiter+ and +humber_to_human_size+ helpers use the number format settings located in the http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2[number] scope.
==== Active Record methods
-* human_name and human_attribute_name use translations for model names and attribute names if available in the http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L43[activerecord.models] scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
+* +human_name+ and +human_attribute_name+ use translations for model names and attribute names if available in the http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L43[activerecord.models] scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
-* ActiveRecord::Errors#generate_message (which is used by Active Record validations but may also be used manually) uses human_name and human_attribute_name (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".
+* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +human_name+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".
-* ActiveRecord::Errors#full_messages prepends the attribute name to the error message using a separator that will be looked up from http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91[activerecord.errors.format.separator] (and defaults to ' ').
+*+ ActiveRecord::Errors#full_messages+ prepends the attribute name to the error message using a separator that will be looked up from http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91[activerecord.errors.format.separator] (and defaults to +' '+).
==== ActiveSupport methods
-* Array#to_sentence uses format settings as given in the http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30[support.array] scope.
+* +Array#to_sentence+ uses format settings as given in the http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30[support.array] scope.
== Customize your I18n setup
@@ -720,7 +859,7 @@ ReservedInterpolationKey # the translation contains a reserved interpolation
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 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.
@@ -737,11 +876,11 @@ end
I18n.exception_handler = :just_raise_that_exception
-------------------------------------------------------
-This would re-raise all caught exceptions including MissingTranslationData.
+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.
+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:
+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]
-------------------------------------------------------
@@ -762,13 +901,13 @@ I18n support in Ruby on Rails was introduced in the release 2.2 and is still evo
Thus we encourage everybody to experiment with new ideas and features in plugins or other libraries and make them available to the community. (Don't forget to announce your work on our http://groups.google.com/group/rails-i18n[mailinglist]!)
-If you find your own locale (language) missing from our http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[example translations data] repository for Ruby on Rails
+If you find your own locale (language) missing from our http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[example translations data] repository for Ruby on Rails, please http://github.com/guides/fork-a-project-and-submit-your-modifications[_fork_] the repository, add your data and send a http://github.com/guides/pull-requests[pull request].
== Resources
* http://rails-i18n.org[rails-i18n.org] - Homepage of the rails-i18n project. You can find lots of useful resources on the http://rails-i18n.org/wiki[wiki].
-* http://groups.google.com/group/rails-i18n[rails-i18n Google group] - The project's mailinglist.
+* http://groups.google.com/group/rails-i18n[rails-i18n Google group] - The project's mailing list.
* http://github.com/svenfuchs/rails-i18n/tree/master[Github: rails-i18n] - Code repository for the rails-i18n project. Most importantly you can find lots of http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[example translations] for Rails that should work for your application in most cases.
* http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview[Lighthouse: rails-i18n] - Issue tracker for the rails-i18n project.
* http://github.com/svenfuchs/i18n/tree/master[Github: i18n] - Code repository for the i18n gem.
@@ -777,8 +916,8 @@ If you find your own locale (language) missing from our http://github.com/svenfu
== Authors
-* Sven Fuchs[http://www.workingwithrails.com/person/9963-sven-fuchs] (initial author)
-* Karel Minarik[http://www.workingwithrails.com/person/7476-karel-mina-k]
+* http://www.workingwithrails.com/person/9963-sven-fuchs[Sven Fuchs] (initial author)
+* http://www.workingwithrails.com/person/7476-karel-mina-k[Karel Minařík]
If you found this guide useful please consider recommending its authors on http://www.workingwithrails.com[workingwithrails].