i18n_strategy: provides a thin wrapper over Rails i18n API
In i18n section of Rails Guide, there's a description on Rails i18n API. It's comprehensive and has enough information to implement our own locale detection strategy. However, it doesn't provide us some automatic way to handle users' locale.
Now that I have to do with i18n in my project, I want some easier way to handle it. So I hacked up a library named "i18n_strategy" which provides a thin wrapper over Rails i18n API and allows you to detect and set users' locale easily.
Let's get started with i18n_strategy.
At first, add a line below into your Gemfile
:
gem 'i18n_strategy'
Then, set your custom strategy into I18nStrategy.strategy
, which is to detect a locale for a user visiting your application. If no strategy is set, default strategy provided by this library will be used.
Lastly, set available languages in your application via I18nStrategy.available_languages
.
initializers/i18n_strategy
:
# Just for example module MyStrategy def detect_locale if params[:local] && I18nStrategy.available_languages.include?(params[:locale]) params[:locale] else I18n.default_locale end end end I18nStrategy.strategy = MyStrategy I18nStrategy.available_languages = %w[ja en]
Users' locale detected by the strategy is automatically set to I18n.locale
.
That's all. Very much simple. If you got interested, see the GitHub page for more details.
Enjoy!