Set Current Locale in your Rails App
You are probably used to having a
before_action somewhere in your controller
hierarchy to set the current locale (
I18n.locale) based on a value from the
URL, the session, a cookie, etc.
But, if you need a custom behaviour, you can of course continue to use your own method by redefining it. For instance:
before_action :set_locale def set_locale I18n.locale = # custom logic to get the locale code end
Another common use case is to let registered users set their preferred locale in their profile (saved in the database).
Here is what it might look like in such a case:
before_action :set_locale def set_locale if current_user I18n.locale = current_user.locale || I18n.default_locale else super end end