aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/i18n.md
diff options
context:
space:
mode:
authorEvan Prothro <evan.prothro@gmail.com>2014-09-17 14:43:37 -0500
committerRobin Dupret <robin.dupret@gmail.com>2015-05-04 15:43:08 +0200
commiteaa43785866441db7c699363a91120a3193df25e (patch)
tree41df7e84ea83da1ff266847844cee9be1e80d86d /guides/source/i18n.md
parentbccbaefd7f4fbbbc1e0008cbd8bc4108da9e8fdc (diff)
downloadrails-eaa43785866441db7c699363a91120a3193df25e.tar.gz
rails-eaa43785866441db7c699363a91120a3193df25e.tar.bz2
rails-eaa43785866441db7c699363a91120a3193df25e.zip
Updates various prose to the i18n guide
[ci skip]
Diffstat (limited to 'guides/source/i18n.md')
-rw-r--r--guides/source/i18n.md106
1 files changed, 57 insertions, 49 deletions
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 348c60a9d8..719176513d 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -40,7 +40,7 @@ Internationalization is a complex problem. Natural languages differ in so many w
* providing support for English and similar languages out of the box
* making it easy to customize and extend everything for other languages
-As part of this solution, **every static string in the Rails framework** - e.g. Active Record validation messages, time and date formats - **has been internationalized**, so _localization_ of a Rails application means "over-riding" these defaults.
+As part of this solution, **every static string in the Rails framework** - e.g. Active Record validation messages, time and date formats - **has been internationalized**. _Localization_ of a Rails application means defining translated values for these strings in desired languages.
### The Overall Architecture of the Library
@@ -84,13 +84,13 @@ So, let's internationalize a simple Rails application from the ground up in the
Setup the Rails Application for Internationalization
----------------------------------------------------
-There are just a few simple steps to get up and running with I18n support for your application.
+There are a few steps to get up and running with I18n support for a Rails application.
### Configure the I18n Module
-Following the _convention over configuration_ philosophy, Rails will set up your application with reasonable defaults. If you need different settings, you can overwrite them easily.
+Following the _convention over configuration_ philosophy, Rails I18n provides reasonable default translation strings. When different translation strings are needed, they can be overridden.
-Rails adds all `.rb` and `.yml` files from the `config/locales` directory to your **translations load path**, automatically.
+Rails adds all `.rb` and `.yml` files from the `config/locales` directory to the **translations load path**, automatically.
The default `en.yml` locale in this directory contains a sample pair of translation strings:
@@ -101,15 +101,15 @@ en:
This means, that in the `:en` locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Model validation messages in the [`activemodel/lib/active_model/locale/en.yml`](https://github.com/rails/rails/blob/master/activemodel/lib/active_model/locale/en.yml) file or time and date formats in the [`activesupport/lib/active_support/locale/en.yml`](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml) file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend.
-The I18n library will use **English** as a **default locale**, i.e. if you don't set a different locale, `:en` will be used for looking up translations.
+The I18n library will use **English** as a **default locale**, i.e. if a different locale is not set, `:en` will be used for looking up translations.
NOTE: The i18n library takes a **pragmatic approach** to locale keys (after [some discussion](http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en)), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Few gems such as [Globalize3](https://github.com/globalize/globalize) may help you implement it.
-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.
+The **translations load path** (`I18n.load_path`) is an array of paths to files that will be loaded automatically. Configuring this path allows for customization of translations directory structure and file naming scheme.
-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.
+NOTE: The backend lazy-loads these translations when a translation is looked up for the first time. This backend can be swapped with something else even after translations have already been announced.
-The default `application.rb` file has instructions on how to add locales from another directory and how to set a different default locale. Just uncomment and edit the specific lines.
+The default `application.rb` file has instructions on how to add locales from another directory and how to set a different default locale.
```ruby
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
@@ -117,31 +117,25 @@ The default `application.rb` file has instructions on how to add locales from an
# 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 `application.rb` file 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:
+The load path must be specified before any translations are looked up. To change the default locale from an initializer instead of `application.rb`:
```ruby
-# in config/initializers/locale.rb
+# config/initializers/locale.rb
-# tell the I18n library where to find your translations
+# Where the I18n library should search for translation files
I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
-# set default locale to something other than :en
+# Set default locale to something other than :en
I18n.default_locale = :pt
```
-### Setting and Passing the Locale
+### Managing the Locale across Requests
-If you want to translate your Rails application to a **single language other than English** (the default locale), you can set I18n.default_locale to your locale in `application.rb` or an initializer as shown above, and it will persist through the requests.
+The default locale is used for all translations unless `I18n.locale` is explicitly set.
-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 the chosen locale in a _session_ or a *cookie*. However, **do not do this**. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being [*RESTful*](http://en.wikipedia.org/wiki/Representational_State_Transfer). Read more about the RESTful approach in [Stefan Tilkov's articles](http://www.infoq.com/articles/rest-introduction). Sometimes there are exceptions to this rule and those are discussed below.
+A localized application will likely need to provide support for multiple locales. To accomplish this, the locale should be set at the beginning of each request so that all strings are translated using the desired locale during the lifetime of that request.
-The _setting part_ is easy. You can set the locale in a `before_action` in the `ApplicationController` like this:
+The locale can be set in a `before_action` in the `ApplicationController`:
```ruby
before_action :set_locale
@@ -151,11 +145,11 @@ def set_locale
end
```
-This requires you to pass the locale as a URL query parameter as in `http://example.com/books?locale=pt`. (This is, for example, Google's approach.) So `http://localhost:3000?locale=pt` will load the Portuguese 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 the locale in the URL and reloading the page.
+This example illustrates this using a URL query parameter to set the locale (e.g. `http://example.com/books?locale=pt`). With this approach, `http://localhost:3000?locale=pt` renders the Portuguese localization, while `http://localhost:3000?locale=de` loads a German localization.
-Of course, you probably don't want to manually include the locale in every URL all over your application, or want the URLs look differently, e.g. the usual `http://example.com/pt/books` versus `http://example.com/en/books`. Let's discuss the different options you have.
+The locale can be set using one of many different approaches.
-### Setting the Locale from the Domain Name
+#### Setting the 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 the English (or default) locale, and `www.example.es` to load the Spanish locale. Thus the _top-level domain name_ is used for locale setting. This has several advantages:
@@ -208,7 +202,7 @@ assuming you would set `APP_CONFIG[:deutsch_website_url]` to some value like `ht
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 the Locale from the URL Params
+#### Setting the Locale from URL Params
The 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_action_ 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.
@@ -266,14 +260,23 @@ Do take special care about the **order of your routes**, so this route declarati
NOTE: Have a look at various gems which simplify working with routes: [routing_filter](https://github.com/svenfuchs/routing-filter/tree/master), [rails-translate-routes](https://github.com/francesc/rails-translate-routes), [route_translator](https://github.com/enriclluelles/route_translator).
-### Setting the Locale from the Client Supplied Information
+#### Setting the Locale from User Preferences
+
+An application with authenticated users may allow users to set a locale preference through the application's interface. With this approach, a user's selected locale preference is persisted in the database and used to set the locale for authenticated requests by that user.
+
+```ruby
+def set_locale
+ I18n.locale = current_user.try(:locale) || I18n.default_locale
+end
+```
-In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' preferred language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the 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.
+#### Choosing an Implied Locale
+When an explicit locale has not been set for a request (e.g. via one of the above methods), an application should attempt to infer the desired locale.
-#### Using `Accept-Language`
+##### Inferring Locale from the Language Header
-One source of client supplied information would be an `Accept-Language` HTTP header. People may [set this in their browser](http://www.w3.org/International/questions/qa-lang-priorities) or other clients (such as _curl_).
+The `Accept-Language` HTTP header indicates the preferred language for request's response. Browsers [set this header value based on the user's language preference settings](http://www.w3.org/International/questions/qa-lang-priorities), making it a good first choice when inferring a locale.
A trivial implementation of using an `Accept-Language` header would be:
@@ -290,24 +293,27 @@ private
end
```
-Of course, in a production environment you would need much more robust code, and could use a gem such as Iain Hecker's [http_accept_language](https://github.com/iain/http_accept_language/tree/master) or even Rack middleware such as Ryan Tomayko's [locale](https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb).
-#### Using GeoIP (or Similar) Database
+In practice, more robust code is necessary to do this reliably. Iain Hecker's [http_accept_language](https://github.com/iain/http_accept_language/tree/master) library or Ryan Tomayko's [locale](https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb) Rack middleware provide solutions to this problem.
+
+##### Inferring the Locale from IP Geolocation
-Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as [GeoIP Lite Country](http://www.maxmind.com/app/geolitecountry). The mechanics of the code would be very similar to the code above - you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned.
+The IP address of the client making the request can be used to infer the client's region and thus their locale. Services such as [GeoIP Lite Country](http://www.maxmind.com/app/geolitecountry) or gems like [geocoder](https://github.com/alexreisner/geocoder) can be used to implement this approach.
-#### User Profile
+In general, this approach is far less reliable than using the language header and is not recommended for most web applications.
-You can also provide users of your application with means to set (and possibly over-ride) the 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 the database. Then you'd set the locale to this value.
+#### Storing the Locale from the Session or Cookies
-Internationalizing your Application
+WARNING: You may be tempted to store the chosen locale in a _session_ or a *cookie*. However, **do not do this**. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being [*RESTful*](http://en.wikipedia.org/wiki/Representational_State_Transfer). Read more about the RESTful approach in [Stefan Tilkov's articles](http://www.infoq.com/articles/rest-introduction). Sometimes there are exceptions to this rule and those are discussed below.
+
+Internationalization and Localization
-----------------------------------
-OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale to use and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff.
+OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale to use and how to preserve it between requests.
-Let's _internationalize_ our application, i.e. abstract every locale-specific parts, and then _localize_ it, i.e. provide necessary translations for these abstracts.
+Next we need to _internationalize_ our application by abstracting every locale-specific element. Finally, we need to _localize_ it by providing necessary translations for these abstracts.
-You most probably have something like this in one of your applications:
+Given the following example:
```ruby
# config/routes.rb
@@ -344,9 +350,9 @@ end
![rails i18n demo untranslated](images/i18n/demo_untranslated.png)
-### Adding Translations
+### Abstracting Localized Code
-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:
+There are two strings in our code that are in English and that users will be rendered in our response ("Hello Flash" and "Hello World"). In order to internationalize this code, these strings need to be replaced by calls to Rails' `#t` helper with an appropriate key for each string:
```ruby
# app/controllers/home_controller.rb
@@ -363,13 +369,15 @@ end
<p><%= flash[:notice] %></p>
```
-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.
+Now, when this view is rendered, it will show an error message which tells you that the translations for the keys `:hello_world` and `:hello_flash` are missing.
![rails i18n demo translation missing](images/i18n/demo_translation_missing.png)
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 into the dictionary files (i.e. do the "localization" part):
+### Providing Translations for Internationalized Strings
+
+Add the missing translations into the translation dictionary files:
```yaml
# config/locales/en.yml
@@ -383,11 +391,11 @@ pirate:
hello_flash: Ahoy Flash
```
-There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows:
+Because the `default_locale` hasn't changed, translations use the `:en` locale and the response renders the english strings:
![rails i18n demo translated to English](images/i18n/demo_translated_en.png)
-And when you change the URL to pass the pirate locale (`http://localhost:3000?locale=pirate`), you'll get:
+If the locale is set via the URL to the pirate locale (`http://localhost:3000?locale=pirate`), the response renders the pirate strings:
![rails i18n demo translated to pirate](images/i18n/demo_translated_pirate.png)
@@ -612,13 +620,13 @@ end
### 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.
+Properly internationalized code will use variables in translation definitions to ensure correct translations in multiple languages. See the [Passing Variables to Translations](#passing-variables-to-translations) section for more detail on this consideration.
-All options besides `:default` and `:scope` that are passed to `#translate` will be interpolated to the translation:
+The I18n API provides an interpolation feature to address this need. All options besides `:default` and `:scope` that are passed to `#translate` can be interpolated in the translation:
```ruby
-I18n.backend.store_translations :en, thanks: 'Thanks %{name}!'
-I18n.translate :thanks, name: 'Jeremy'
+I18n.backend.store_translations(:en, thanks: 'Thanks %{name}!')
+I18n.translate(:thanks, name: 'Jeremy')
# => 'Thanks Jeremy!'
```