v7.0.8
Veja mais em rubyonrails.org: Mais Ruby on Rails

API de Internacionalização do Rails (I18n)

Ruby I18n (abreviação de internacionalização) é uma gem fornecida com o Ruby on Rails (a partir do Rails 2.2) que fornece uma estrutura extensível e fácil de usar para traduzir sua aplicação para um único idioma personalizado que não seja o inglês ou para fornecer suporte em multilinguagens em sua aplicação.

O processo de "internacionalização" geralmente significa abstrair todas as strings e outros bits específicos do código do idioma (como formatos de data ou moeda) de sua aplicação. O processo de "localização" significa fornecer traduções e formatos locais para esses bits.1

Portanto, no processo de internacionalização de sua aplicação Rails, você deve:

No processo de "localização" de sua aplicação, você provavelmente fará os três passos abaixo:

Este documento o guiará pela API I18n e contém um tutorial sobre como internacionalizar uma aplicação Rails desde o início.

O framework Ruby I18n fornece todas os meios necessários para internacionalização/localização da sua aplicação Rails. Você também pode usar várias gems disponíveis para adicionar funcionalidades ou recursos adicionais. Veja rails-i18n gem para mais informações.

1 Como o I18n funciona no Ruby on Rails

A internacionalização é um problema complexo. As línguas diferem de muitas maneiras (por exemplo, nas regras de pluralização), sendo difícil fornecer ferramentas para resolver todos os problemas de uma vez. Por esse motivo, a API I18n do Rails concentra-se em:

  • fornecer suporte para o inglês e línguas similares por padrão
  • facilitar a personalização e extensão de tudo para outras línguas

Como parte dessa solução, cada string estática no framework Rails - por exemplo, mensagens de validação do Active Record, formatos de data e hora - foi internacionalizada. Localização de uma aplicação Rails significa definir valores traduzidos para essas strings nos idiomas desejados.

Para localizar, armazenar e atualizar conteúdo em sua aplicação (por exemplo, traduzir postagens de blog), consulte a seção Traduzindo Conteúdo do Model.

1.1 A Arquitetura Geral da Biblioteca

Assim, a gem Ruby I18n é dividida em duas partes:

  • A API pública do framework i18n - um módulo Ruby com métodos públicos que definem como a biblioteca funciona
  • Um backend padrão (intencionalmente chamado de backend Simple) que implementa esses métodos

Como usuário, você deve sempre acessar apenas os métodos públicos no módulo I18n, mas é útil conhecer as capacidades do backend.

É possível substituir o backend Simple fornecido por um mais poderoso, que armazenaria dados de tradução em um banco de dados relacional, dicionário GetText, ou similar. Consulte a seção Usando Backends Diferentes abaixo.

1.2 A API Pública I18n

Os métodos mais importantes da API I18n são:

translate # Pesquisar traduções de texto
localize  # Localizar objetos de Data e Hora nos formatos locais

Eles têm os aliases #t e #l, para que você possa usá-los assim:

I18n.t 'store.title'
I18n.l Time.now

Também há métodos de leitura e escrita para os seguintes atributos:

load_path                 # Anuncie seus arquivos de tradução personalizados
locale                    # Obtenha e defina o idioma atual
default_locale            # Obtenha e defina o idioma padrão
available_locales         # Locais permitidos disponíveis para a aplicação
enforce_available_locales # Reforce a permissão de idioma (true ou false)
exception_handler         # Use um manipulador de exceção diferente
backend                   # Use um backend diferente

Então, vamos internacionalizar uma aplicação Rails simples do zero nos próximos capítulos!

2 Configurando a Aplicação Rails para Internacionalização

Há alguns passos para começar a usar o suporte à internacionalização (I18n) em uma aplicação Rails.

2.1 Configurando o Módulo I18n

Seguindo a filosofia de convenção sobre configuração, o Rails I18n fornece algumas strings com tradução padrão. Quando são necessárias strings com tradução diferentes, elas podem ser sobrescritas.

O Rails adiciona todos os arquivos .rb e .yml do diretório config/locales ao caminho de carregamento de traduções automaticamente.

O arquivo padrão en.yml neste diretório inclui um par de exemplos de strings para tradução:

en:
  hello: "Hello world"

Isso significa que, na localidade :en, a chave hello será mapeada para a string Hello world. Cada string dentro do Rails é internacionalizada dessa maneira. Consulte, por exemplo, as mensagens de validação do Active Model no arquivo activemodel/lib/active_model/locale/en.yml ou os formatos de hora e data no arquivo activesupport/lib/active_support/locale/en.yml. Você pode usar YAML ou hashes Ruby padrão para armazenar traduções no backend (Simple) padrão.

A biblioteca I18n usará o inglês como localidade padrão. Ou seja, se uma localidade diferente não estiver configurada, :en será usada para procurar traduções.

A biblioteca I18n adota uma abordagem pragmática para as chaves de localidade (após algumas discussões), incluindo apenas a parte da localidade ("idioma"), como :en, :pl, não a parte da região, como :"en-US" ou :"en-GB", que são tradicionalmente usadas para separar "idiomas" e "configurações regionais" ou "dialetos". Muitas aplicações internacionais usam apenas o elemento "idioma" de uma localidade, como :cs, :th, ou :es (para tcheco, tailandês e espanhol). No entanto, também existem diferenças regionais dentro de diferentes grupos de idiomas que podem ser importantes. Por exemplo, na localidade :"en-US", você teria $ como símbolo de moeda, enquanto na :"en-GB", você teria £. Nada impede você de separar configurações regionais e outras dessa maneira: você só precisa fornecer a localidade completa "Inglês - Reino Unido" em um dicionário :"en-GB".

O *caminho de carregamento de traduções (I18n.load_path) é um array de caminhos para arquivos que serão carregados automaticamente. Configurar este caminho permite a personalização da estrutura do diretório de traduções e do esquema de nomeação de arquivos.

O backend carrega essas traduções de forma preguiçosa (lazy-load) quando uma tradução é consultada pela primeira vez. Esse backend pode ser trocado por outro mesmo depois que as traduções já foram anunciadas.

Você pode alterar a localidade padrão, bem como configurar os caminhos de carregamento de traduções em config/application.rb da seguinte forma:

config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
config.i18n.default_locale = :de

O caminho de carregamento deve ser especificado antes de qualquer consulta de tradução. Para alterar a localidade padrão a partir de um inicializador em vez de config/application.rb:

# config/initializers/locale.rb

# Onde a biblioteca I18n deve procurar arquivos de tradução
I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]

# Localidades permitidas disponíveis para a aplicação
I18n.available_locales = [:en, :pt]

# Definir localidade padrão para algo diferente de :en
I18n.default_locale = :pt

Note que anexar diretamente a I18n.load_path em vez de à configuração i18n da aplicação não substituirá traduções de gems externas.

2.2 Gerenciando a Localidade entre Requisições

Uma aplicação localizada provavelmente precisará oferecer suporte a várias localidades. Para isso, a localidade deve ser definida no início de cada requisição para que todas as strings sejam traduzidas usando a localidade desejada durante a vida útil dessa requisição.

A localidade padrão é usada para todas as traduções, a menos que I18n.locale= ou I18n.with_locale seja usado.

A I18n.locale pode vazar para requisições subsequentes servidas pela mesma thread/processo se não for consistentemente definida em cada controller. Por exemplo, executar I18n.locale = :es em uma requisição POST terá efeitos para todas as requisições posteriores aos controllers que não definem a localidade, mas apenas nessa thread/processo específico. Por esse motivo, em vez de I18n.locale = você pode usar I18n.with_locale, que não tem esse problema de vazamento.

A localidade pode ser definida em um around_action no ApplicationController:

around_action :switch_locale

def switch_locale(&action)
  locale = params[:locale] || I18n.default_locale
  I18n.with_locale(locale, &action)
end

Este exemplo ilustra isso usando um parâmetro de consulta de URL para definir a localidade (por exemplo, http://example.com/books?locale=pt). Com essa abordagem, http://localhost:3000?locale=pt renderiza a localização em português, enquanto http://localhost:3000?locale=de carrega a localização em alemão.

A localidade pode ser definida de várias maneiras diferentes.

2.2.1 Definindo a Localidade a partir do Nome do Domínio

Uma opção que você tem é definir a localidade a partir do nome de domínio onde sua aplicação está em execução. Por exemplo, queremos que www.example.com carregue a localidade em inglês (ou padrão) e www.example.es carregue a localidade em espanhol. Assim, o nome de domínio de nível superior é usado para a definição da localidade. Isso tem várias vantagens:

  • A localidade é uma parte óbvia da URL.
  • As pessoas compreendem intuitivamente em qual idioma o conteúdo será exibido.
  • É muito trivial de implementar no Rails.
  • Os motores de busca parecem gostar de conteúdo em diferentes idiomas em domínios diferentes e interligados.

Você pode implementar isso da seguinte forma no seu ApplicationController:

around_action :switch_locale

def switch_locale(&action)
  locale = extract_locale_from_tld || I18n.default_locale
  I18n.with_locale(locale, &action)
end

# Obtenha o idioma do domínio de nível superior ou retorne +nil+ se esse idioma não estiver disponível
# Você precisa adicionar algo como:
#   127.0.0.1 application.com
#   127.0.0.1 application.it
#   127.0.0.1 application.pl
# no seu arquivo /etc/hosts para testar isso localmente
def extract_locale_from_tld
  parsed_locale = request.host.split('.').last
  I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
end

Também podemos definir o idioma a partir do subdomínio de uma maneira muito semelhante:

# Obtenha o código do idioma do subdomínio da solicitação (como http://it.application.local:3000)
# Você precisa adicionar algo como:
#   127.0.0.1 gr.application.local
# no seu arquivo /etc/hosts para testar isso localmente
def extract_locale_from_subdomain
  parsed_locale = request.subdomains.first
  I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
end

Se sua aplicação incluir um menu de troca de idioma, você terá algo assim:

link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['PATH_INFO']}")

supondo que você defina APP_CONFIG[:deutsch_website_url] para algum valor como http://www.application.de.

Esta solução tem as vantagens mencionadas anteriormente, no entanto, você pode não conseguir ou não querer fornecer diferentes localizações ("versões de idioma") em domínios diferentes. A solução mais óbvia seria incluir o código do idioma nos parâmetros da URL (ou caminho da solicitação).

2.2.2 Definindo o Idioma a partir de Parâmetros da URL

A maneira mais comum de definir (e passar) o idioma seria incluí-lo nos parâmetros da URL, como fizemos no I18n.with_locale(params[:locale], &action) around_action no primeiro exemplo. Gostaríamos de ter URLs como www.example.com/books?locale=ja ou www.example.com/ja/books neste caso.

Essa abordagem compartilha quase o mesmo conjunto de vantagens de definir o idioma a partir do nome do domínio, principalmente por ser RESTful e estar em conformidade com o restante da World Wide Web. No entanto, demanda um pouco mais de esforço para ser implementada.

Obter o idioma de params e defini-lo de acordo não é difícil; incluí-lo em cada URL e assim passá-lo por meio da requisição é. Incluir uma opção explícita em cada URL, por exemplo, link_to(books_url(locale: I18n.locale)), seria tedioso e provavelmente impossível, é claro.

O Rails contém infraestrutura para "centralizar decisões dinâmicas sobre os URLs" em seu ApplicationController#default_url_options, que é útil precisamente nesse cenário: ele nos permite definir "padrões" para url_for e métodos auxiliares dependentes dele (implementando/substituindo default_url_options).

Podemos incluir algo assim no nosso ApplicationController então:

# app/controllers/application_controller.rb
def default_url_options
  { locale: I18n.locale }
end

Todo método auxiliar dependente de url_for (por exemplo, auxiliares para rotas nomeadas como root_path ou root_url, rotas de recursos como books_path ou books_url, etc.) agora incluirá automaticamente o idioma na string de consulta, como isto: http://localhost:3001/?locale=ja.

Você pode estar satisfeito com isso. No entanto, impacta a legibilidade das URLs, quando o idioma "pendura" no final de cada URL na sua aplicação. Além disso, do ponto de vista arquitetônico, o idioma geralmente está hierarquicamente acima das outras partes do domínio da aplicação: e as URLs devem refletir isso.

Provavelmente, você quer que as URLs se pareçam com isso: http://www.example.com/en/books (que carrega o idioma inglês) e http://www.example.com/nl/books (que carrega o idioma holandês). Isso é possível com a estratégia de "sobrepor default_url_options" mencionada acima: você só precisa configurar suas rotas com scope:

# config/routes.rb
scope "/:locale" do
  resources :books
end

Agora, quando você chama o método books_path, você deve obter "/en/books" (para o idioma padrão). Uma URL como http://localhost:3001/nl/books deve carregar o idioma holandês e chamadas subsequentes para books_path devem retornar "/nl/books" (porque o idioma mudou).

Como o valor de retorno de default_url_options é armazenado em cache por solicitação, as URLs em um seletor de idioma não podem ser geradas chamando auxiliares em um loop que define o I18n.locale correspondente em cada iteração. Em vez disso, deixe I18n.locale intocado e passe uma opção explícita :locale para o auxiliar, ou edite request.original_fullpath.

Se você não deseja forçar o uso de um idioma nas suas rotas, pode usar um escopo de caminho opcional (indicado pelos parênteses) assim:

# config/routes.rb
scope "(:locale)", locale: /en|nl/ do
  resources :books
end

Com essa abordagem, você não receberá um Routing Error ao acessar seus recursos, como http://localhost:3001/books sem um idioma. Isso é útil quando você deseja usar o idioma padrão quando não especificado.

Claro, você precisa ter um cuidado especial com a URL raiz (geralmente "homepage" ou "dashboard") da sua aplicação. Uma URL como http://localhost:3001/nl não funcionará automaticamente, porque a declaração root to: "dashboard#index" no seu routes.rb não leva em consideração o idioma. (E com razão: há apenas uma URL "root").

Você provavelmente precisaria mapear URLs como estas:

# config/routes.rb
get '/:locale' => 'dashboard#index'

Tenha um cuidado especial com a ordem das suas rotas, para que essa declaração de rota não "anule" outras. (Você pode querer adicioná-la diretamente antes da declaração root :to.)

Dê uma olhada em várias gems que simplificam o trabalho com rotas: routing_filter, route_translator.

2.2.3 Definindo o Idioma a partir das Preferências do Usuário

Uma aplicação com usuários autenticados pode permitir que os usuários definam uma preferência de idioma por meio da interface da aplicação. Com essa abordagem, a preferência de idioma selecionada pelo usuário é persistida no banco de dados e usada para definir o idioma para solicitações autenticadas por esse usuário.

around_action :switch_locale

def switch_locale(&action)
  locale = current_user.try(:locale) || I18n.default_locale
  I18n.with_locale(locale, &action)
end
2.2.4 Escolhendo um Idioma Implícito

Quando um idioma explícito não foi definido para uma solicitação (por exemplo, por meio de um dos métodos acima), a aplicação deve tentar inferir o idioma desejado.

2.2.4.1 Inferindo o Idioma do Cabeçalho de Idioma

O cabeçalho HTTP Accept-Language indica o idioma preferido para a resposta da solicitação. Navegadores configuram esse valor de cabeçalho com base nas configurações de preferência de idioma do usuário, tornando-o uma boa escolha inicial ao inferir um idioma.

Uma implementação trivial usando um cabeçalho Accept-Language ser

def switch_locale(&action)
  logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
  locale = extract_locale_from_accept_language_header
  logger.debug "* Locale set to '#{locale}'"
  I18n.with_locale(locale, &action)
end

private
  def extract_locale_from_accept_language_header
    request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
  end

Na prática, é necessário um código mais robusto para fazer isso de forma confiável. A biblioteca http_accept_language de Iain Hecker ou o middleware Rack locale de Ryan Tomayko oferecem soluções para esse problema.

2.2.4.2 Inferindo o Idioma a partir da Geolocalização por IP

O endereço IP do cliente que faz a solicitação pode ser usado para inferir a região do cliente e, portanto, seu idioma. Serviços como GeoLite2 Country ou gems como geocoder podem ser usados para implementar essa abordagem.

Em geral, essa abordagem é muito menos confiável do que usar o cabeçalho de idioma e não é recomendada para a maioria das aplicações web.

2.2.5 Armazenando o Idioma a partir da Sessão ou Cookies

Você pode ser tentado a armazenar o idioma escolhido em uma sessão ou em um cookie. No entanto, não faça isso. O idioma deve ser transparente e fazer parte da URL. Dessa forma, você não quebrará as suposições básicas das pessoas sobre a web: se você enviar uma URL a um amigo, eles deveriam ver a mesma página e conteúdo que você. Um termo sofisticado para isso seria que você está sendo RESTful. Leia mais sobre a abordagem RESTful nos artigos de Stefan Tilkov. Às vezes, há exceções a essa regra, e essas são discutidas abaixo.

3 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.

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.

Given the following example:

# config/routes.rb
Rails.application.routes.draw do
  root to: "home#index"
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base

  around_action :switch_locale

  def switch_locale(&action)
    locale = params[:locale] || I18n.default_locale
    I18n.with_locale(locale, &action)
  end
end
# app/controllers/home_controller.rb
class HomeController < ApplicationController
  def index
    flash[:notice] = "Hello Flash"
  end
end
<!-- app/views/home/index.html.erb -->
<h1>Hello World</h1>
<p><%= flash[:notice] %></p>

rails i18n demo untranslated

3.1 Abstracting Localized Code

In our code, there are two strings written in English that will be rendered in our response ("Hello Flash" and "Hello World"). To internationalize this code, these strings need to be replaced by calls to Rails' #t helper with an appropriate key for each string:

# app/controllers/home_controller.rb
class HomeController < ApplicationController
  def index
    flash[:notice] = t(:hello_flash)
  end
end
<!-- app/views/home/index.html.erb -->
<h1><%= t :hello_world %></h1>
<p><%= flash[:notice] %></p>

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

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">.

3.2 Providing Translations for Internationalized Strings

Add the missing translations into the translation dictionary files:

# config/locales/en.yml
en:
  hello_world: Hello world!
  hello_flash: Hello flash!
# config/locales/pirate.yml
pirate:
  hello_world: Ahoy World
  hello_flash: Ahoy Flash

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

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

You need to restart the server when you add new locale files.

You may use YAML (.yml) or plain Ruby (.rb) files for storing your translations in SimpleStore. YAML is the preferred option among Rails developers. However, it has one big disadvantage. YAML is very sensitive to whitespace and special characters, so the application may not load your dictionary properly. Ruby files will crash your application on first request, so you may easily find what's wrong. (If you encounter any "weird issues" with YAML dictionaries, try putting the relevant portion of your dictionary into a Ruby file.)

If your translations are stored in YAML files, certain keys must be escaped. They are:

  • true, on, yes
  • false, off, no

Examples:

# config/locales/en.yml
en:
  success:
    'true':  'True!'
    'on':    'On!'
    'false': 'False!'
  failure:
    true:    'True!'
    off:     'Off!'
    false:   'False!'
I18n.t 'success.true'  # => 'True!'
I18n.t 'success.on'    # => 'On!'
I18n.t 'success.false' # => 'False!'
I18n.t 'failure.false' # => Translation Missing
I18n.t 'failure.off'   # => Translation Missing
I18n.t 'failure.true'  # => Translation Missing

3.3 Passing Variables to Translations

One key consideration for successfully internationalizing an application is to avoid making incorrect assumptions about grammar rules when abstracting localized code. Grammar rules that seem fundamental in one locale may not hold true in another one.

Improper abstraction is shown in the following example, where assumptions are made about the ordering of the different parts of the translation. Note that Rails provides a number_to_currency helper to handle the following case.

<!-- app/views/products/show.html.erb -->
<%= "#{t('currency')}#{@product.price}" %>
# config/locales/en.yml
en:
  currency: "$"
# config/locales/es.yml
es:
  currency: "€"

If the product's price is 10 then the proper translation for Spanish is "10 €" instead of "€10" but the abstraction cannot give it.

To create proper abstraction, the I18n gem ships with a feature called variable interpolation that allows you to use variables in translation definitions and pass the values for these variables to the translation method.

Proper abstraction is shown in the following example:

<!-- app/views/products/show.html.erb -->
<%= t('product_price', price: @product.price) %>
# config/locales/en.yml
en:
  product_price: "$%{price}"
# config/locales/es.yml
es:
  product_price: "%{price} €"

All grammatical and punctuation decisions are made in the definition itself, so the abstraction can give a proper translation.

The default and scope keywords are reserved and can't be used as variable names. If used, an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable, but this has not been passed to #translate, an I18n::MissingInterpolationArgument exception is raised.

3.4 Adding Date/Time Formats

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.

<!-- 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):

# config/locales/pirate.yml
pirate:
  time:
    formats:
      short: "arrrround %H'ish"

So that would give you:

rails i18n demo localized time to pirate

Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by translating Rails' defaults for your locale. See the rails-i18n repository at GitHub for an archive of various locale files. When you put such file(s) in config/locales/ directory, they will automatically be ready for use.

3.5 Inflection Rules for Other Locales

Rails allows you to define inflection rules (such as rules for singularization and pluralization) for locales other than English. In config/initializers/inflections.rb, you can define these rules for multiple locales. The initializer contains a default example for specifying additional rules for English; follow that format for other locales as you see fit.

3.6 Localized Views

Let's say you have a BooksController in your application. Your index action renders content in app/views/books/index.html.erb template. When you put a localized variant of this template: index.es.html.erb in the same directory, Rails will render content in this template, when the locale is set to :es. When the locale is set to the default locale, the generic index.html.erb view will be used. (Future Rails versions may well bring this automagic localization to assets in public, etc.)

You can make use of this feature, e.g. when working with a large amount of static content, which would be clumsy to put inside YAML or Ruby dictionaries. Bear in mind, though, that any change you would like to do later to the template must be propagated to all of them.

3.7 Organization of Locale Files

When you are using the default SimpleStore shipped with the i18n library, dictionaries are stored in plain-text files on the disk. 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/locales directory could look like this:

|-defaults
|---es.yml
|---en.yml
|-models
|---book
|-----es.yml
|-----en.yml
|-views
|---defaults
|-----es.yml
|-----en.yml
|---books
|-----es.yml
|-----en.yml
|---users
|-----es.yml
|-----en.yml
|---navigation
|-----es.yml
|-----en.yml

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.

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:

# config/application.rb
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]

4 Overview of the I18n API Features

You should have a good understanding of using the i18n library now and know how to internationalize a basic Rails application. In the following chapters, we'll cover its features in more depth.

These chapters will show examples using both the I18n.translate method as well as the translate view helper method (noting the additional features provided by the view helper method).

Covered are features like these:

  • looking up translations
  • interpolating data into translations
  • pluralizing translations
  • using safe HTML translations (view helper method only)
  • localizing dates, numbers, currency, etc.

4.1 Looking up Translations

4.1.1 Basic Lookup, Scopes, and Nested Keys

Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:

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:

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:

I18n.translate "activerecord.errors.messages.record_invalid"

Thus the following calls are equivalent:

I18n.t 'activerecord.errors.messages.record_invalid'
I18n.t 'errors.messages.record_invalid', scope: :activerecord
I18n.t :record_invalid, scope: 'activerecord.errors.messages'
I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
4.1.2 Defaults

When a :default option is given, its value will be returned if the translation is missing:

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:

I18n.t :missing, default: [:also_missing, 'Not here']
# => 'Not here'
4.1.3 Bulk and Namespace Lookup

To look up multiple translations at once, an array of keys can be passed:

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:

I18n.t 'errors.messages'
# => {:inclusion=>"is not included in the list", :exclusion=> ... }

If you want to perform interpolation on a bulk hash of translations, you need to pass deep_interpolation: true as a parameter. When you have the following dictionary:

en:
  welcome:
    title: "Welcome!"
    content: "Welcome to the %{app_name}"

then the nested interpolation will be ignored without the setting:

I18n.t 'welcome', app_name: 'book store'
# => {:title=>"Welcome!", :content=>"Welcome to the %{app_name}"}

I18n.t 'welcome', deep_interpolation: true, app_name: 'book store'
# => {:title=>"Welcome!", :content=>"Welcome to the book store"}
4.1.4 "Lazy" Lookup

Rails implements a convenient way to look up the locale inside views. When you have the following dictionary:

es:
  books:
    index:
      title: "Título"

you can look up the books.index.title value inside app/views/books/index.html.erb template like this (note the dot):

<%= t '.title' %>

Automatic translation scoping by partial is only available from the translate view helper method.

"Lazy" lookup can also be used in controllers:

en:
  books:
    create:
      success: Book created!

This is useful for setting flash messages for instance:

class BooksController < ApplicationController
  def create
    # ...
    redirect_to books_url, notice: t('.success')
  end
end

4.2 Pluralization

In many languages — including English — there are only two forms, a singular and a plural, for a given string, e.g. "1 message" and "2 messages". Other languages (Arabic, Japanese, Russian and many more) have different grammars that have additional or fewer 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 in the pluralization backend. By default, only the English pluralization rules are applied.

I18n.backend.store_translations :en, inbox: {
  zero: 'no messages', # optional
  one: 'one message',
  other: '%{count} messages'
}
I18n.translate :inbox, count: 2
# => '2 messages'

I18n.translate :inbox, count: 1
# => 'one message'

I18n.translate :inbox, count: 0
# => 'no messages'

The algorithm for pluralizations in :en is as simple as:

lookup_key = :zero if count == 0 && entry.has_key?(:zero)
lookup_key ||= count == 1 ? :one : :other
entry[lookup_key]

The translation denoted as :one is regarded as singular, and the :other is used as plural. If the count is zero, and a :zero entry is present, then it will be used instead of :other.

If the lookup for the key does not return a Hash suitable for pluralization, an I18n::InvalidPluralizationData exception is raised.

4.2.1 Locale-specific Rules

The I18n gem provides a Pluralization backend that can be used to enable locale-specific rules. Include it to the Simple backend, then add the localized pluralization algorithms to translation store, as i18n.plural.rule.

I18n::Backend::Simple.include(I18n::Backend::Pluralization)
I18n.backend.store_translations :pt, i18n: { plural: { rule: lambda { |n| [0, 1].include?(n) ? :one : :other } } }
I18n.backend.store_translations :pt, apples: { one: 'one or none', other: 'more than one' }

I18n.t :apples, count: 0, locale: :pt
# => 'one or none'

Alternatively, the separate gem rails-i18n can be used to provide a fuller set of locale-specific pluralization rules.

4.3 Setting and Passing a Locale

The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current in the same way as, for example, Time.zone) or can be passed as an option to #translate and #localize.

If no locale is passed, I18n.locale is used:

I18n.locale = :de
I18n.t :foo
I18n.l Time.now

Explicitly passing a locale:

I18n.t :foo, locale: :de
I18n.l Time.now, locale: :de

The I18n.locale defaults to I18n.default_locale which defaults to :en. The default locale can be set like this:

I18n.default_locale = :de

4.4 Using Safe HTML Translations

Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. When you use them in views the HTML will not be escaped.

# config/locales/en.yml
en:
  welcome: <b>welcome!</b>
  hello_html: <b>hello!</b>
  title:
    html: <b>title!</b>
<!-- app/views/home/index.html.erb -->
<div><%= t('welcome') %></div>
<div><%= raw t('welcome') %></div>
<div><%= t('hello_html') %></div>
<div><%= t('title.html') %></div>

Interpolation escapes as needed though. For example, given:

en:
  welcome_html: "<b>Welcome %{username}!</b>"

you can safely pass the username as set by the user:

<%# This is safe, it is going to be escaped if needed. %>
<%= t('welcome_html', username: @current_user.username) %>

Safe strings on the other hand are interpolated verbatim.

Automatic conversion to HTML safe translate text is only available from the translate view helper method.

i18n demo html safe

4.5 Translations for Active Record Models

You can use the methods Model.model_name.human and Model.human_attribute_name(attribute) to transparently look up translations for your model and attribute names.

For example when you add the following translations:

en:
  activerecord:
    models:
      user: Customer
    attributes:
      user:
        login: "Handle"
      # will translate User attribute "login" as "Handle"

Then User.model_name.human will return "Customer" and User.human_attribute_name("login") will return "Handle".

You can also set a plural form for model names, adding as following:

en:
  activerecord:
    models:
      user:
        one: Customer
        other: Customers

Then User.model_name.human(count: 2) will return "Customers". With count: 1 or without params will return "Customer".

In the event you need to access nested attributes within a given model, you should nest these under model/attribute at the model level of your translation file:

en:
  activerecord:
    attributes:
      user/role:
        admin: "Admin"
        contributor: "Contributor"

Then User.human_attribute_name("role.admin") will return "Admin".

If you are using a class which includes ActiveModel and does not inherit from ActiveRecord::Base, replace activerecord with activemodel in the above key paths.

4.5.1 Error Message Scopes

Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes, and/or validations. It also transparently takes single table inheritance into account.

This gives you quite powerful means to flexibly adjust your messages to your application's needs.

Consider a User model with a validation for the name attribute like this:

class User < ApplicationRecord
  validates :name, presence: true
end

The key for the error message in this case is :blank. Active Record will look up this key in the namespaces:

activerecord.errors.models.[model_name].attributes.[attribute_name]
activerecord.errors.models.[model_name]
activerecord.errors.messages
errors.attributes.[attribute_name]
errors.messages

Thus, in our example it will try the following keys in this order and return the first result:

activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
errors.attributes.name.blank
errors.messages.blank

When your models are additionally using inheritance then the messages are looked up in the inheritance chain.

For example, you might have an Admin model inheriting from User:

class Admin < User
  validates :name, presence: true
end

Then Active Record will look for messages in this order:

activerecord.errors.models.admin.attributes.name.blank
activerecord.errors.models.admin.blank
activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
errors.attributes.name.blank
errors.messages.blank

This way you can provide special translations for various error messages at different points in your model's inheritance chain and in the attributes, models, or default scopes.

4.5.2 Error Message Interpolation

The translated model name, translated attribute name, and value are always available for interpolation as model, attribute and value respectively.

So, for example, instead of the default error message "cannot 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:
validation with option message interpolation
confirmation - :confirmation attribute
acceptance - :accepted -
presence - :blank -
absence - :present -
length :within, :in :too_short count
length :within, :in :too_long count
length :is :wrong_length count
length :minimum :too_short count
length :maximum :too_long count
uniqueness - :taken -
format - :invalid -
inclusion - :inclusion -
exclusion - :exclusion -
associated - :invalid -
non-optional association - :required -
numericality - :not_a_number -
numericality :greater_than :greater_than count
numericality :greater_than_or_equal_to :greater_than_or_equal_to count
numericality :equal_to :equal_to count
numericality :less_than :less_than count
numericality :less_than_or_equal_to :less_than_or_equal_to count
numericality :other_than :other_than count
numericality :only_integer :not_an_integer -
numericality :in :in count
numericality :odd :odd -
numericality :even :even -

4.6 Translations for Action Mailer E-Mail Subjects

If you don't pass a subject to the mail method, Action Mailer will try to find it in your translations. The performed lookup will use the pattern <mailer_scope>.<action_name>.subject to construct the key.

# user_mailer.rb
class UserMailer < ActionMailer::Base
  def welcome(user)
    #...
  end
end
en:
  user_mailer:
    welcome:
      subject: "Welcome to Rails Guides!"

To send parameters to interpolation use the default_i18n_subject method on the mailer.

# user_mailer.rb
class UserMailer < ActionMailer::Base
  def welcome(user)
    mail(to: user.email, subject: default_i18n_subject(user: user.name))
  end
end
en:
  user_mailer:
    welcome:
      subject: "%{user}, welcome to Rails Guides!"

4.7 Overview of Other Built-In Methods that Provide I18n Support

Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers. Here's a brief overview.

4.7.1 Action View Helper Methods
  • distance_of_time_in_words translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See datetime.distance_in_words translations.

  • datetime_select and select_month use translated month names for populating the resulting select tag. See date.month_names for translations. datetime_select also looks up the order option from date.order (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the datetime.prompts scope if applicable.

  • The number_to_currency, number_with_precision, number_to_percentage, number_with_delimiter, and number_to_human_size helpers use the number format settings located in the number scope.

4.7.2 Active Model Methods
  • model_name.human and human_attribute_name use translations for model names and attribute names if available in the activerecord.models scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".

  • ActiveModel::Errors#generate_message (which is used by Active Model validations but may also be used manually) uses model_name.human 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".

  • ActiveModel::Error#full_message and ActiveModel::Errors#full_messages prepend the attribute name to the error message using a format looked up from errors.format (default: "%{attribute} %{message}"). To customize the default format, override it in the app's locale files. To customize the format per model or per attribute, see config.active_model.i18n_customize_full_message.

4.7.3 Active Support Methods
  • Array#to_sentence uses format settings as given in the support.array scope.

5 How to Store your Custom Translations

The Simple backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format.2

For example a Ruby Hash providing translations can look like this:

{
  pt: {
    foo: {
      bar: "baz"
    }
  }
}

The equivalent YAML file would look like this:

pt:
  foo:
    bar: baz

As you see, in both cases the top level 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 Active Support en.yml translations YAML file:

en:
  date:
    formats:
      default: "%Y-%m-%d"
      short: "%b %d"
      long: "%B %d, %Y"

So, all of the following equivalent lookups will return the :short date format "%b %d":

I18n.t 'date.formats.short'
I18n.t 'formats.short', scope: :date
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 formats.

6 Customize Your I18n Setup

6.1 Using Different Backends

For several reasons the Simple backend shipped with Active Support only does the "simplest thing that could possibly work" for Ruby on Rails3 ... 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 cannot 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, by passing a backend instance to the I18n.backend= setter.

For example, you can replace the Simple backend with the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends.

With the Chain backend, you could use the Active Record backend and fall back to the (default) Simple backend:

I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)

6.2 Using Different Exception Handlers

The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:

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 are 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 behavior, 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 or a class with a call method:

module I18n
  class JustRaiseExceptionHandler < ExceptionHandler
    def call(exception, locale, key, options)
      if exception.is_a?(MissingTranslation)
        raise exception.to_exception
      else
        super
      end
    end
  end
end

I18n.exception_handler = I18n::JustRaiseExceptionHandler.new

This would re-raise only the MissingTranslationData exception, passing all other input to the default exception handler.

However, if you are using I18n::Backend::Pluralization this handler will also raise I18n::MissingTranslationData: translation missing: en.i18n.plural.rule exception that should normally be ignored to fall back to the default pluralization rule for English locale. To avoid this you may use an additional check for the translation key:

if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule'
  raise exception.to_exception
else
  super
end

Another example where the default behavior 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:

I18n.t :foo, raise: true # always re-raises exceptions from the backend

7 Translating Model Content

The I18n API described in this guide is primarily intended for translating interface strings. If you are looking to translate model content (e.g. blog posts), you will need a different solution to help with this.

Several gems can help with this:

  • Mobility: Provides support for storing translations in many formats, including translation tables, json columns (PostgreSQL), etc.
  • Traco: Translatable columns stored in the model table itself

8 Conclusion

At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.

9 Contributing to Rails I18n

I18n support in Ruby on Rails was introduced in the release 2.2 and is still evolving. The project follows the good Ruby on Rails development tradition of evolving solutions in gems and real applications first, and only then cherry-picking the best-of-breed of most widely useful features for inclusion in the core.

Thus we encourage everybody to experiment with new ideas and features in gems or other libraries and make them available to the community. (Don't forget to announce your work on our mailing list!)

If you find your own locale (language) missing from our example translations data repository for Ruby on Rails, please fork the repository, add your data, and send a pull request.

10 Resources

11 Authors

12 Footnotes

1 Or, to quote 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.

3 One of these reasons is that we don't want to imply 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.

Feedback

Você é incentivado a ajudar a melhorar a qualidade deste guia.

Por favor, contribua caso veja quaisquer erros, inclusive erros de digitação. Para começar, você pode ler nossa sessão de contribuindo com a documentação.

Você também pode encontrar conteúdo incompleto ou coisas que não estão atualizadas. Por favor, adicione qualquer documentação em falta na main do Rails. Certifique-se de checar o Edge Guides (en-US) primeiro para verificar se o problema já foi resolvido ou não no branch main. Verifique as Diretrizes do Guia Ruby on Rails para estilo e convenções.

Se, por qualquer motivo, você encontrar algo para consertar, mas não conseguir consertá-lo, por favor abra uma issue no nosso Guia.

E por último, mas não menos importante, qualquer tipo de discussão sobre a documentação do Ruby on Rails é muito bem vinda na forum oficial do Ruby on Rails e nas issues do Guia em português.


dark theme icon