【Ruby on Rails】簡単なメモアプリの作成|rails-i18nによる日本語化対応の実装

作成日: 更新日:

開発環境

  • Ruby:version 3.1.2
  • Ruby on Rails:version 7.0.4
  • Visual Studio Code:version 1.73.0
  • OS:Windows10

Ruby on Railsでi18nによる日本語化対応の実装手順

Ruby on Railsの日本語化対応はja.ymlという辞書データを作成していく流れになります。 今回はメモアプリの作成で使用したコードを用いて解説していきます。

rails-i18nのgemファイルをインストールする

まずはrails-i18nのgemファイルをインストールするためにGemファイルに下記を記述します。

1# memo_app\Gemfile
2
3group :test do
4  # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
5  gem "capybara"
6  gem "selenium-webdriver"
7  gem "webdrivers"
8end
9
10+ gem 'rails-i18n'

続いて以下のコマンドを打ち、gemファイルをインストールします。

1bundle install

デフォルトの言語を日本語に設定する

続いてデフォルトの言語を日本語に設定するための設定をしていきます。

1# memo_app\config\application.rb
2
3module MemoApp
4  class Application < Rails::Application
5    # Initialize configuration defaults for originally generated Rails version.
6    config.load_defaults 7.0
7
8    # Configuration for the application, engines, and railties goes here.
9    #
10    # These settings can be overridden in specific environments using the files
11    # in config/environments, which are processed later.
12    #
13    # config.time_zone = "Central Time (US & Canada)"
14    # config.eager_load_paths << Rails.root.join("extras")
15+   config.i18n.default_locale = :ja
16+   config.i18n.load_path += Dir[Rails.root.join('config/locales/**/*.yml').to_s]
17  end
18end

21行目の「config.i18n.default_locale = :ja」は、デフォルトの言語を日本語に設定するという設定になります。 22行目の「config.i18n.load_path += Dir[Rails.root.join('config/locales/**/*.yml').to_s]」は、複数のロケールファイルが読み込まれるようpathを通す設定になります。

翻訳ファイルを作成する

続いて「app\config\locales」フォルダ内に「ja.yml」というファイルを作成します。 その後、「ja.yml」に「rails-i18n」のGitHubの日本語の辞書データを記述します。 GitHubの日本語の辞書データ:https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/ja.yml

1# memo_app\config\locales\ja.yml
2ja:
3  activerecord:
4    errors:
5      messages:
6        record_invalid: 'バリデーションに失敗しました: %{errors}'
7        restrict_dependent_destroy:
8          has_one: "%{record}が存在しているので削除できません"
9          has_many: "%{record}が存在しているので削除できません"
10  date:
11    abbr_day_names:
12    -13    -14    -15    -16    -17    -18    -19    abbr_month_names:
20    - 
21    - 1月
22    - 2月
23    - 3月
24    - 4月
25    - 5月
26    - 6月
27    - 7月
28    - 8月
29    - 9月
30    - 10月
31    - 11月
32    - 12月
33    day_names:
34    - 日曜日
35    - 月曜日
36    - 火曜日
37    - 水曜日
38    - 木曜日
39    - 金曜日
40    - 土曜日
41    formats:
42      default: "%Y/%m/%d"
43      long: "%Y年%m月%d日(%a)"
44      short: "%m/%d"
45    month_names:
46    - 
47    - 1月
48    - 2月
49    - 3月
50    - 4月
51    - 5月
52    - 6月
53    - 7月
54    - 8月
55    - 9月
56    - 10月
57    - 11月
58    - 12月
59    order:
60    - :year
61    - :month
62    - :day
63  datetime:
64    distance_in_words:
65      about_x_hours: 約%{count}時間
66      about_x_months: 約%{count}ヶ月
67      about_x_years: 約%{count}68      almost_x_years: "%{count}年弱"
69      half_a_minute: 30秒前後
70      less_than_x_seconds: "%{count}秒未満"
71      less_than_x_minutes: "%{count}分未満"
72      over_x_years: "%{count}年以上"
73      x_seconds: "%{count}秒"
74      x_minutes: "%{count}分"
75      x_days: "%{count}日"
76      x_months: "%{count}ヶ月"
77      x_years: "%{count}年"
78    prompts:
79      second:80      minute:81      hour:82      day:83      month:84      year:85  errors:
86    format: "%{attribute}%{message}"
87    messages:
88      accepted: を受諾してください
89      blank: を入力してください
90      confirmation: と%{attribute}の入力が一致しません
91      empty: を入力してください
92      equal_to: は%{count}にしてください
93      even: は偶数にしてください
94      exclusion: は予約されています
95      greater_than: は%{count}より大きい値にしてください
96      greater_than_or_equal_to: は%{count}以上の値にしてください
97      inclusion: は一覧にありません
98      invalid: は不正な値です
99      less_than: は%{count}より小さい値にしてください
100      less_than_or_equal_to: は%{count}以下の値にしてください
101      model_invalid: 'バリデーションに失敗しました: %{errors}'
102      not_a_number: は数値で入力してください
103      not_an_integer: は整数で入力してください
104      odd: は奇数にしてください
105      other_than: は%{count}以外の値にしてください
106      present: は入力しないでください
107      required: を入力してください
108      taken: はすでに存在します
109      too_long: は%{count}文字以内で入力してください
110      too_short: は%{count}文字以上で入力してください
111      wrong_length: は%{count}文字で入力してください
112    template:
113      body: 次の項目を確認してください
114      header: "%{model}に%{count}個のエラーが発生しました"
115  helpers:
116    select:
117      prompt: 選択してください
118    submit:
119      create: 登録する
120      submit: 保存する
121      update: 更新する
122  number:
123    currency:
124      format:
125        delimiter: ","
126        format: "%n%u"
127        precision: 0
128        separator: "."
129        significant: false
130        strip_insignificant_zeros: false
131        unit:132    format:
133      delimiter: ","
134      precision: 3
135      separator: "."
136      significant: false
137      strip_insignificant_zeros: false
138    human:
139      decimal_units:
140        format: "%n %u"
141        units:
142          billion: 十億
143          million: 百万
144          quadrillion: 千兆
145          thousand:146          trillion:147          unit: ''
148      format:
149        delimiter: ''
150        precision: 3
151        significant: true
152        strip_insignificant_zeros: true
153      storage_units:
154        format: "%n%u"
155        units:
156          byte: バイト
157          eb: EB
158          gb: GB
159          kb: KB
160          mb: MB
161          pb: PB
162          tb: TB
163    percentage:
164      format:
165        delimiter: ''
166        format: "%n%"
167    precision:
168      format:
169        delimiter: ''
170  support:
171    array:
172      last_word_connector: "、"
173      two_words_connector: "、"
174      words_connector: "、"
175  time:
176    am: 午前
177    formats:
178      default: "%Y年%m月%d日(%a) %H時%M分%S秒 %z"
179      long: "%Y/%m/%d %H:%M"
180      short: "%m/%d %H:%M"
181    pm: 午後

モデルとカラムに関する日本語辞書データを作成する

続いて「activerecord」内にモデルとカラムに関連付けて日本語辞書データを作成します。 今回は、メモアプリの作成で使用したコードをサンプルとして記載しておきます。

1# memo_app\config\locales\ja.yml
2ja:
3  activerecord:
4+     modes:
5+       memo: メモ
6+     attributes:
7+       memo:
8+         title: タイトル
9+         description: 本文
10    errors:
11      messages:
12        record_invalid: 'バリデーションに失敗しました: %{errors}'
13        restrict_dependent_destroy:
14          has_one: "%{record}が存在しているので削除できません"
15          has_many: "%{record}が存在しているので削除できません"

おわりに

Ruby on Railsでrails-i18nによる日本語化対応について解説してきましたが、いかがだったでしょうか。 Webサービスではユーザーが使いやすいようにするために複数言語対応などは当たり前に実装されているため、是非、日本語化対応に挑戦してみてください。

【Ruby on Rails】簡単なメモアプリの作成|rails-i18nによる日本語化対応の実装 | いっしー@Webエンジニア