I18nをファイル分割して管理する
アプリケーションをI18n対応する際、1つのyamlファイル(ja.yml)に内容を追加していくと管理が大変になるので、 ファイル分割する方法について調べてみた。
複数のロケールファイルを読み込むには次のコードをconfig/application.rb
に追加すれば良い。
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
追加後のapplication.rb
がこちら
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Media class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 config.i18n.default_locale = :ja config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s] # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. end end
これでいつも通りI18n.t('hoge.foo.bar')
でI18nが使えます。