The Rails Internationalization (i18n) framework provides localization for strings, numbers, currencies, and dates through standard YAML dictionary catalogs.
Basic Translation & Date Helpers
<!-- Translating a key -->
<%= t('welcome.title') %>
<!-- Lazy scoped translation based on current controller/action -->
<!-- In app/views/articles/index.html.erb: looks up articles.index.heading -->
<%= t('.heading') %>
<!-- Localizing dates and times -->
<%= l(Time.now, format: :short) %>
<%= l(Date.today, format: :long) %>
Variable Interpolation & Pluralization
# 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."
In template:
<%= t('greetings.hello', name: current_user.name) %>
<%= t('inbox.unread_messages', count: @unread_count) %>
Setting the Current Locale
In 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 Model Translations
en:
activerecord:
models:
user: "Customer"
attributes:
user:
email: "Email Address"
role: "Account Role"
In views:
<%= User.model_name.human %>
<!-- => "Customer" -->
<%= User.human_attribute_name(:email) %>
<!-- => "Email Address" -->