i18n Multi-Tenant
This gem is a small utility that provides the basic configuration to perform tenant-specific translations in multi-tenant apps.
Read more about it in the blog announcement.
Setting the locale 🌎
You can set a locale globally using:
I18nMultitenant.set(locale: :en, tenant: 'Tenant Name')
It's usually preferable to set a locale locally by scoping the change to a block:
I18nMultitenant.with_locale(locale: :en, tenant: 'Tenant Name') do
# perform translations
end
For example, using an around_action
in Rails:
around_action do
I18nMultitenant.with_locale(locale: :en, tenant: 'Tenant Name') { yield }
end
Locale files 📝
The library leverages the use of fallbacks, using the tenant name as a locale variant.
You can organize the files in nested folders as you find suitable, the only requirement is that the root of a translation file uses the following convention:
lang-TENANT_NAME:
...
For a few different examples, check out the locale files used in tests, but here are few valid roots:
en:
en-US:
en-US-TENANT_NAME:
Any name can be passed through the :tenant
option, and it will be normalized
to be uppercase and not contain any hyphens, dots, or spaces.
If you need to use names that are not be valid yml keys even after this process,
you will need to sanitize the names yourself before handing them over to set
.
Installation 💿
Add this line to your application's Gemfile and run bundle install
:
gem 'i18n_multitenant'
Or install it yourself running:
gem install i18n_multitenant
Configuration ⚙️
In Rails everything should be configured out of the box, but you can perform the configuration yourself in other applications by calling:
I18nMultitenant.configure(I18n) # or pass I18n.config
Front-end Translations
If you also need to perform translations in the front-end, you can use a library
like i18n-js
. You can easily configure
i18n-js
to support multi-tenant translations by leveraging i18n
itself:
I18n.locale = <%= I18n.locale.to_json.html_safe %>;
I18n.locales[I18n.locale] = <%= I18n.fallbacks[I18n.locale].to_json.html_safe %>