
はじめに
Rails I18n(Internationalization)は、Ruby on Railsアプリケーションを多言語対応にするための標準ライブラリです。「I18n」は「Internationalization」の略で、「アイ・エイ・ティーン・エヌ」と読みます。
このガイドでは、Rails I18nの基本的な使い方から実践的な実装方法まで、詳しく解説します。
Rails I18nとは
Rails I18nは、アプリケーションのテキストを複数の言語に翻訳するためのフレームワークです。主な特徴は以下の通りです:
- YAML形式の翻訳ファイルを使用
- 動的な翻訳キーの生成
- 複数形対応
- 日時・数値のローカライゼーション
- 翻訳の階層化
基本的な設定
1. 翻訳ファイルの作成
翻訳ファイルは `config/locales/` ディレクトリに配置します。# Rails I18n(国際化)完全ガイド:多言語対応の実装から実践まで
config/locales/ja.yml
ja:
ActiveRecord:
attributes:
user:
status: ステータス
name: 名前
email: メールアドレス
created_at: 作成日時
post:
title: タイトル
content: 内容
published: 公開状態
user:
welcome: ようこそ
profile: プロフィール
settings: 設定
status:
active: アクティブ
inactive: 非アクティブ
pending: 保留中
config/locales/en.yml
en:
ActiveRecord:
attributes:
user:
status: Status
name: Name
email: Email Address
created_at: Created At
post:
title: Title
content: Content
published: Published
user:
welcome: Welcome
profile: Profile
settings: Settings
status:
active: Active
inactive: Inactive
pending: Pending
2. アプリケーションの設定
class Application < Rails::Application
# デフォルトのロケールを設定
config.i18n.default_locale = :ja
# 利用可能なロケールを設定
config.i18n.available_locales = [:ja, :en]
# 翻訳ファイルのパスを設定
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.yml')]
end
基本的な使用方法
1. 翻訳メソッドの使用
# 基本的な翻訳
I18n.t('user.welcome') # => "ようこそ"
# 省略形
t('user.welcome') # => "ようこそ"
# ネストしたキーの指定
I18n.t('ActiveRecord.attributes.user.status') # => "ステータス"
2. 動的な翻訳キー
# 変数を使った翻訳キー
status = 'active'
I18n.t("status.#{status}") # => "アクティブ"
# より実践的な例
def translate_status(status)
I18n.t("status.#{status}").to_s
end
translate_status('active') # => "アクティブ"
translate_status('inactive') # => "非アクティブ"
3. 文字列変換とエンコーディング
# 文字列への明示的な変換
translated_text = I18n.t('user.welcome').to_s
# UTF-8エンコーディングの指定
encoded_text = I18n.t('user.welcome').encode(Encoding::UTF_8)
# 実践的な例
def safe_translate(key)
I18n.t(key).to_s.encode(Encoding::UTF_8)
rescue I18n::MissingTranslationData
key.to_s
end
実践的な実装例
1. モデルの属性翻訳
class User < ApplicationRecord
# ステータス定数
STATUSES = %w[active inactive pending].freeze
# 翻訳されたステータス名を取得
def translated_status
I18n.t("status.#{status}").to_s
end
# 翻訳された属性名を取得
def self.translated_attribute(attribute)
I18n.t("ActiveRecord.attributes.user.#{attribute}").to_s
end
end
2. コントローラーでの使用
class UsersController < ApplicationController
def index
@users = User.all
@status_options = User::STATUSES.map do |status|
[I18n.t("status.#{status}"), status]
end
end
def show
@user = User.find(params[:id])
@translated_status = @user.translated_status
end
end
3. ビューでの使用
<%= form_with model: @user do |form| %>
<div class="field">
<%= form.label :name, User.translated_attribute('name') %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :status, User.translated_attribute('status') %>
<%= form.select :status, @status_options, { prompt: t('common.please_select') } %>
</div>
<div class="actions">
<%= form.submit t('common.save') %>
</div>
<% end %>
高度な機能
1. 変数の埋め込み
ja:
user:
greeting: "こんにちは、%{name}さん"
post_count: "%{count}件の投稿があります"
I18n.t('user.greeting', name: 'タロウ') # => "こんにちは、タロウさん"
I18n.t('user.post_count', count: 5) # => "5件の投稿があります"
2. 複数形対応
ja:
post:
count:
zero: "投稿がありません"
one: "1件の投稿があります"
other: "%{count}件の投稿があります"
I18n.t('post.count', count: 0) # => "投稿がありません"
I18n.t('post.count', count: 1) # => "1件の投稿があります"
I18n.t('post.count', count: 5) # => "5件の投稿があります"
3. 日時のローカライゼーション
# 日時の翻訳
I18n.l(Time.current, format: :long) # => "2024年1月15日 14時30分"
# 日付の翻訳
I18n.l(Date.current, format: :short) # => "2024/01/15"
エラーハンドリング
# 翻訳が見つからない場合の処理
def safe_translate(key, options = {})
I18n.t(key, options)
rescue I18n::MissingTranslationData
"[翻訳が見つかりません: #{key}]"
end
# デフォルト値を指定
I18n.t('unknown.key', default: 'デフォルト値')
パフォーマンス最適化
# 翻訳の事前読み込み
class ApplicationController < ActionController::Base
before_action :load_translations
private
def load_translations
@common_translations = {
save: I18n.t('common.save'),
cancel: I18n.t('common.cancel'),
delete: I18n.t('common.delete')
}
end
end
ベストプラクティス
1. 翻訳キーの命名規則
- 階層化を活用する
- 一貫性のある命名を行う
- 長すぎるキーは避ける
2. 翻訳ファイルの管理
- 機能別にファイルを分割する
- 共通部分は別ファイルに分離する
- 定期的なレビューを行う
3. エラーハンドリング
- 翻訳が見つからない場合の対処を実装
- デフォルト値を適切に設定
- ログ出力で問題を把握
まとめ
Rails I18nを使用することで、効率的に多言語対応のアプリケーションを構築できます。基本的な使用方法から高度な機能まで理解し、適切に実装することで、国際的なユーザーに対応したアプリケーションを開発できます。
翻訳ファイルの管理やエラーハンドリングなど、実践的な側面も考慮しながら、メンテナンスしやすいコードを書くことが重要です。