If we want to have multiple languages for our Rails application, I18n will be the standard way to do it.
Rails internationalization (I18n) provides a neat API to ensure creating an application that can be accessible to various parts of the world by providing translations and localizations for languages.
The way to use I18n is by adding locales inside the config/locales
directory.
By default,
we already have en.yml
for all our English translations.
If we want to add Spanish translations,
we could add es.yml
translations inside the config/locales
directory.
Once the application scales,
our translation files become too large and will need to be split into multiple files for better organization.
However,
Rails does not load nested locales in config/locales
by default.
This can be overridden by explicitly loading nested locales in the application.rb
file,
but this is not the Rails way.
We do not want to write configurations as Conventions over Configurations.
This will change in Rails 7 as Rails 7 will allow loading nested locales in engines. These changes will allow us to write multiple translations inside directories for better readability and organization.
Let us assume we have two translation files for English(en.yml
) and Spanish(es.yml
),
and we want to separate our translations into multiple files.
We could organize the translations into the following:
- config/locales/en.yml
- config/locales/es.yml
- config/locales/activerecord/user.en.yml
- config/locales/activerecord/user.es.yml
- config/locales/helper/user.en.yml
- config/locales/helper/user.es.yml
Before
Rails does not autoload the translations due to the nested folders.
We would have to override the load_path in the application.rb
.
After
In Rails 7, the application by default overloads nested locales, so we do not need to override the load_path in the application.rb
This change in I18n further improves the Convention over Configuration motto of Rails by eliminating the need to override any defaults.