LoginSignup
3
3

More than 1 year has passed since last update.

【Rails】localeを使いこなして国際化向けのアプリと化そう!

Last updated at Posted at 2021-06-05

localeとは

デフォルトではエラーメッセージ等は英語で表示されるがconfig/locales/配下に多言語化用の言語ファイルを配置することで、指定した言語や文言に変換することが出来ます。
また、住所や時間の形式なども管理することが出来ます。

使い方

1.config/application.rbに以下のような記述をする。

config/application.rb
.
.
.
module SampleApp
  class Application < Rails::Application
    config.load_defaults 6.0

    # config/locales以下のファイルを読み込む
    config.i18n.load_path += Dir[Rails.root.join("config", "locales", "**", "*.{rb,yml}").to_s]
    # デフォルトの言語を日本語にする
    config.i18n.default_locale = :ja
  end
end

2.Gemfileに以下を記載してbundle installを実行する。
※このgemをインストールすることで、よく使う言葉のlocaleファイルをダウンロードしなくても使用可能になります。

gem 'rails-i18n'

3.locales以下にファイルを作成し好きなように変換する。

config/locales/greet.ja.yml
ja:
  word:
    greeting:
      hello: "こんにちは"

4.使用する際はi18n.t('〇〇.△△.□□')と言ったように階層を「.」で繋ぐ。

I18n.t("word.greeting.hello")
#=> "こんにちは"

注意点

  • config/以下のファイルの内容を変更した場合は、変更を反映させる為にサーバーを再起動させる。

  • 日本語にする際は、ファイル名を〇〇.ja.ymlとする。

  • 対象となるモデルオブジェクトが狭義のモデル(ActiveRecord::Baseを継承するモデルクラス)のインスタンスである場合はactiverecordを使用する。

ja:
  activerecord:
    attributes:
      ...
  • 対象となるモデルオブジェクトが広義のモデル(ActiveRecord::Baseを継承しないモデルクラス)のインスタンスである場合はactivemodelを使用する。
ja:
  activemodel:
    attributes:
      ...
  • modelsやviewsなど、まとまりごとに管理すると分かりやすい。
config
└── locales
    ├── models # models関連のファイルはここで管理する
        ├── staff
            ├── staff.ja.yml
    └── views # views関連のファイルはここで管理する
       ├── staff
          └── index.ja.yml
    └── enums # enums関連のファイルはここで管理する
        ├── staff
            └── staff.ja.yml

使用例

models

config/locales/models/staff/staff.ja.yml
ja:
  activerecord:
    models:
      staff: スタッフ
    attributes:
      staff:
        id:                ID
        name:              名前
        email:             メールアドレス
        created_at:        登録日
        updated_at:        更新日

views

config/locales/views/staff/staff.ja.yml
ja:
  staffs:
    index:
      title: 'スタッフ一覧'
    show:
      title: '%{name}さんの詳細情報'
    edit:
      title: '%{name}さんの情報を編集'

time

※時間のフォーマットを管理するファイル。

config/locales/time.ja.yml
ja:
  date:
    formats:
      japanese: "%Y年%m月%d日"
      japanese_without_zero: "%Y年%_m月%_d日"
      japanese_without_zero_and_blank: "%Y年%-m月%-d日"
      japanese_with_week: "%Y年%m月%d日(%a)"
      japanese_with_week_without_zero_and_blank: "%Y年%-m月%-d日 (%a)"
      japanese_kana: "%Jf"
      japanese_kana_year: "%Jy"
      japanese_kana_month: "%Jm"
      date: "%Y/%m/%d"
      hyphen: "%Y-%m-%d"
  time:
    formats:
      japanese_without_zero_until_minitue: "%Y年%_m月%_d日 %H:%M"
      japanese_without_zero_with_week_include_time: "%Y年%_m月%_d日(%a) %H:%M"
      japanese_without_zero_and_blank: "%Y年%-m月%-d日"
      japanese_with_week_include_time: "%Y年%m月%d日(%a) %H:%M"
      japanese_until_minitue: "%Y年%m月%d日 %H:%M"
      japanese_date: "%Y年%m月%d日"
      japanese_date_without_zero_and_blank: "%Y年%-m月%-d日"
      japanese_without_year_with_week_until_minitue: "%m月%d日(%a) %H:%M"
      japanese_date_with_week: "%m月%d日(%a)"
      japanese_date_with_week_without_zero: "%_m月%_d日(%a)"
      japanese_date_without_year: "%m月%d日"
      week: "%a"
      date: "%Y/%m/%d"
      slash: "%Y/%m/%d %H:%M:%S"
      slash_until_minitue: "%Y/%m/%d %H:%M"
      hyphen: "%Y-%m-%d %H:%M:%S"
      hyphen_until_minitue: "%Y-%m-%d %H:%M"
      number_only: "%Y%m%d%H%M%S"
      date_digital: "%Y%m%d"
      progressed_date: "%m/%d(%a)"
      time: '%H:%M'
      time_digital: '%-H%M'
      time_kanji: "%_H時%M分"
      time_kanji_with_zero: "%H時%M分"

kaminari

※kaminari導入時のlocaleファイル。

config/locales/kaminari.ja.yml
ja:
  helpers:
    page_entries_info:
      more_pages:
        display_entries: '<div class="list-count">[<span class="list-count__all">%{total}</span>件中 %{first}〜%{last}件表示]</div>'
      one_page:
        display_entries:
          one: '<div class="list-count">[<span class="list-count__all">%{count}</span>件中 1〜%{count}件表示]</div>'
          other: '<div class="list-count">[<span class="list-count__all">%{count}</span>件中 1〜%{count}件表示]</div>'
          zero: '<span class="text-notice">該当するデータが1件もありません。</span>'
  views:
    pagination:
      first: "&lt;&lt; 最初のページ"
      last: "最後のページ &gt;&gt;"
      next: "次のページ &gt;"
      previous: "&lt; 前のページ"
      truncate: "&hellip;"

device

※device導入時のlocaleファイル。

config/locales/device.ja.yml
ja:
  devise:
    failure:
      staff:
        already_authenticated: すでにログインしています。
        invalid: "%{authentication_keys}、もしくはパスワードが違います。"
        not_found_in_database: "%{authentication_keys}、もしくはパスワードが違います。"
        timeout: セッションがタイムアウトしました。もう一度ログインしてください。
        unauthenticated: ログインしてください。
        inactive: メールアドレス、もしくはパスワードが違います。
    sessions:
      already_signed_out: 既にログアウト済みです。
      new:
        sign_in: ログイン
      signed_in: ログインしました。
      signed_out: ログアウトしました。

flash

※falshメッセージのlocaleファイル。

config/locales/flash.ja.yml
ja:
  flash:
    new: 作成しました
    updated: 更新しました
    failed: 失敗しました
    destroy: 削除しました
    login: ログインしました
    logout: ログアウトしました

参考

[初学者]Railsのi18nによる日本語化対応

Rails 国際化 (i18n) API

【Rails】 I18n入門書

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3