2 min. read

Set Current Locale in your Rails App

Michaël Hoste

Michaël Hoste

Founder & CEO

Who is Michaël?

Michaël is the founder of Translation.io. He is always interested in hearing your feedback on the product.

Feel free to get in touch: michael@translation.io

Illustrative image for the blog post 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.

The translation gem ships with a generic implementation that can be called directly in your ApplicationController:

before_action :set_locale

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
Published on April 23, 2015
Ready to give it a try? Start your free 7-days trial