Фреймворк интернационализации Rails (i18n) обеспечивает локализацию строк, чисел, валют и дат через стандартные YAML-словари.
Базовые хелперы перевода и дат
<!-- Перевод ключа -->
<%= t('welcome.title') %>
<!-- Относительный перевод с учетом текущего контроллера/действия -->
<!-- В app/views/articles/index.html.erb: ищет articles.index.heading -->
<%= t('.heading') %>
<!-- Локализация даты и времени -->
<%= l(Time.now, format: :short) %>
<%= l(Date.today, format: :long) %>
Интерполяция переменных и множественные числа
# config/locales/en.yml
en:
greetings:
hello: "Hello, %{name}!"
inbox:
unread_messages:
one: "You have 1 unread message."
other: "You have %{count} unread messages."
zero: "You have no unread messages."
В шаблоне:
<%= t('greetings.hello', name: current_user.name) %>
<%= t('inbox.unread_messages', count: @unread_count) %>
Установка текущей локали (Locale)
В ApplicationController:
class ApplicationController < ActionController::Base
before_action :set_locale
private
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options
{ locale: I18n.locale }
end
end
Переводы моделей Active Record
en:
activerecord:
models:
user: "Customer"
attributes:
user:
email: "Email Address"
role: "Account Role"
Во view-шаблонах:
<%= User.model_name.human %>
<!-- => "Customer" -->
<%= User.human_attribute_name(:email) %>
<!-- => "Email Address" -->