From 7bc1ca351523949f6b4ce96018e95e61cbc7719e Mon Sep 17 00:00:00 2001
From: Prem Sichanugrist <%= flash[:notice] %> <%= flash[:notice] %> <%= flash[:notice] %>
Date: Sat, 1 Sep 2012 17:08:06 -0400
Subject: Convert code blocks into GFM style
---
guides/source/i18n.md | 228 +++++++++++++++++++++++++-------------------------
1 file changed, 114 insertions(+), 114 deletions(-)
(limited to 'guides/source/i18n.md')
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index c073a146a8..f4ff52e5e1 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -46,27 +46,27 @@ h4. The Public I18n API
The most important methods of the I18n API are:
-
+```ruby
translate # Lookup text translations
localize # Localize Date and Time objects to local formats
-
+```
These have the aliases #t and #l so you can use them like this:
-
+```ruby
I18n.t 'store.title'
I18n.l Time.now
-
+```
There are also attribute readers and writers for the following attributes:
-
+```ruby
load_path # Announce your custom translation files
locale # Get and set the current locale
default_locale # Get and set the default locale
exception_handler # Use a different exception_handler
backend # Use a different backend
-
+```
So, let's internationalize a simple Rails application from the ground up in the next chapters!
@@ -82,10 +82,10 @@ Rails adds all +.rb+ and +.yml+ files from the +config/locales+ directory to you
The default +en.yml+ locale in this directory contains a sample pair of translation strings:
-
+```ruby
en:
hello: "Hello world"
-
+```
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 Record validation messages in the "+activerecord/lib/active_record/locale/en.yml+":https://github.com/rails/rails/blob/master/activerecord/lib/active_record/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.
@@ -99,11 +99,11 @@ NOTE: The backend will lazy-load these translations when a translation is looked
The default +application.rb+ files 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.
-
+```ruby
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
-
+```
h4. Optional: Custom I18n Configuration Setup
@@ -111,7 +111,7 @@ For the sake of completeness, let's mention that if you do not want to use the +
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:
-
+```ruby
# in config/initializers/locale.rb
# tell the I18n library where to find your translations
@@ -119,7 +119,7 @@ I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
# set default locale to something other than :en
I18n.default_locale = :pt
-
+```
h4. Setting and Passing the Locale
@@ -131,13 +131,13 @@ WARNING: You may be tempted to store the chosen locale in a _session_ or a c
The _setting part_ is easy. You can set the locale in a +before_filter+ in the +ApplicationController+ like this:
-
+```ruby
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_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.
@@ -154,7 +154,7 @@ One option you have is to set the locale from the domain name where your applica
You can implement it like this in your +ApplicationController+:
-
+```ruby
before_filter :set_locale
def set_locale
@@ -171,11 +171,11 @@ def extract_locale_from_tld
parsed_locale = request.host.split('.').last
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
end
-
+```
We can also set the locale from the _subdomain_ in a very similar way:
-
+```ruby
# Get locale code from request subdomain (like http://it.application.local:3000)
# You have to put something like:
# 127.0.0.1 gr.application.local
@@ -184,13 +184,13 @@ def extract_locale_from_subdomain
parsed_locale = request.subdomains.first
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
end
-
+```
If your application includes a locale switching menu, you would then have something like this in it:
-
+```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+.
@@ -208,13 +208,13 @@ Rails contains infrastructure for "centralizing dynamic decisions about the URLs
We can include something like this in our +ApplicationController+ then:
-
+```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+ (e.g. 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+.
@@ -222,23 +222,23 @@ You may be satisfied with this. It does impact the readability of URLs, though,
You probably want URLs to look like this: +www.example.com/en/books+ (which loads the English locale) and +www.example.com/nl/books+ (which loads the Dutch locale). This is achievable with the "over-riding +default_url_options+" strategy from above: you just have to set up your routes with "+scoping+":http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html option in this way:
-
+```ruby
# config/routes.rb
scope "/:locale" do
resources :books
end
-
+```
Now, when you call the +books_path+ method you should get +"/en/books"+ (for the default locale). An URL like +http://localhost:3001/nl/books+ should load the Dutch locale, then, and following calls to +books_path+ should return +"/nl/books"+ (because the locale changed).
If you don't want to force the use of a locale in your routes you can use an optional path scope (denoted by the parentheses) like so:
-
+```ruby
# config/routes.rb
scope "(:locale)", :locale => /en|nl/ do
resources :books
end
-
+```
With this approach you will not get a +Routing Error+ when accessing your resources such as +http://localhost:3001/books+ without a locale. This is useful for when you want to use the default locale when one is not specified.
@@ -246,10 +246,10 @@ Of course, you need to take special care of the root URL (usually "homepage" or
You would probably need to map URLs like these:
-
+```ruby
# config/routes.rb
match '/:locale' => 'dashboard#index'
-
+```
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 +root :to+ declaration.)
@@ -266,7 +266,7 @@ One source of client supplied information would be an +Accept-Language+ HTTP hea
A trivial implementation of using an +Accept-Language+ header would be:
-
+```ruby
def set_locale
logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
I18n.locale = extract_locale_from_accept_language_header
@@ -276,7 +276,7 @@ private
def extract_locale_from_accept_language_header
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
-
+```
Of course, in a production environment you would need much more robust code, and could use a plugin 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.
@@ -296,7 +296,7 @@ Let's _internationalize_ our application, i.e. abstract every locale-specific pa
You most probably have something like this in one of your applications:
-
+```ruby
# config/routes.rb
Yourapp::Application.routes.draw do
root :to => "home#index"
@@ -312,7 +312,7 @@ end
# app/views/home/index.html.erb
Hello World
<%=t :hello_world %>
<%=t :hello_world %>
+``` |-defaults |---es.rb |---en.rb @@ -442,17 +442,17 @@ For example, your +config/locales+ directory could look like this: |---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" (e.g. date and time formats). Other stores for the i18n library could provide different means of such separation. NOTE: The default locale loading mechanism in Rails does not load locale files in nested dictionaries, like we have here. So, for this to work, we must explicitly tell Rails to look further: - +```ruby # config/application.rb config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')] - +``` Do check the "Rails i18n Wiki":http://rails-i18n.org/wiki for list of tools available for managing translations. @@ -474,84 +474,84 @@ h5. Basic Lookup, Scopes and Nested Keys Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent: - +```ruby I18n.t :message I18n.t 'message' - +``` The +translate+ method also takes a +:scope+ option which can contain one or more additional keys that will be used to specify a “namespace” or scope for a translation key: - +```ruby I18n.t :record_invalid, :scope => [:activerecord, :errors, :messages] - +``` This looks up the +:record_invalid+ message in the Active Record error messages. Additionally, both the key and scopes can be specified as dot-separated keys as in: - +```ruby I18n.translate "activerecord.errors.messages.record_invalid" - +``` Thus the following calls are equivalent: - +```ruby I18n.t 'activerecord.errors.messages.record_invalid' I18n.t 'errors.messages.record_invalid', :scope => :active_record I18n.t :record_invalid, :scope => 'activerecord.errors.messages' I18n.t :record_invalid, :scope => [:activerecord, :errors, :messages] - +``` h5. Defaults When a +:default+ option is given, its value will be returned if the translation is missing: - +```ruby I18n.t :missing, :default => 'Not here' # => '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: - +```ruby I18n.t :missing, :default => [:also_missing, 'Not here'] # => 'Not here' - +``` h5. Bulk and Namespace Lookup To look up multiple translations at once, an array of keys can be passed: - +```ruby I18n.t [:odd, :even], :scope => 'errors.messages' # => ["must be odd", "must be even"] - +``` Also, a key can translate to a (potentially nested) hash of grouped translations. E.g., one can receive _all_ Active Record error messages as a Hash with: - +```ruby I18n.t 'activerecord.errors.messages' # => { :inclusion => "is not included in the list", :exclusion => ... } - +``` h5. "Lazy" Lookup Rails implements a convenient way to look up the locale inside _views_. When you have the following dictionary: -