Framework Rails Internationalization (i18n) zapewnia lokalizację ciągów znaków, liczb, walut i dat za pomocą standardowych słowników YAML.
Podstawowe pomocniki tłumaczeń i dat
<!-- Tłumaczenie klucza -->
<%= t('welcome.title') %>
<!-- Wyszukiwanie z leniwym zakresem wg bieżącego kontrolera/akcji -->
<!-- W app/views/articles/index.html.erb: szuka articles.index.heading -->
<%= t('.heading') %>
<!-- Lokalizowanie dat i godzin -->
<%= l(Time.now, format: :short) %>
<%= l(Date.today, format: :long) %>
Interpolacja zmiennych i liczba mnoga
# 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."
W szablonie:
<%= t('greetings.hello', name: current_user.name) %>
<%= t('inbox.unread_messages', count: @unread_count) %>
Ustawianie bieżącego języka (Locale)
W 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
Tłumaczenia modeli Active Record
en:
activerecord:
models:
user: "Customer"
attributes:
user:
email: "Email Address"
role: "Account Role"
W widokach:
<%= User.model_name.human %>
<!-- => "Customer" -->
<%= User.human_attribute_name(:email) %>
<!-- => "Email Address" -->