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) %>
変数展開と複数形対応 (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."
テンプレート内:
<%= t('greetings.hello', name: current_user.name) %>
<%= t('inbox.unread_messages', count: @unread_count) %>
現在のロケール設定
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"
ビュー内:
<%= User.model_name.human %>
<!-- => "Customer" -->
<%= User.human_attribute_name(:email) %>
<!-- => "Email Address" -->