Temporarily Change Locale

Sometimes it can be very useful to temporarily change the current locale to perform an action and then directly switch back to the original locale. For example you need to deliver an email to a user in its own preferred locale.

Rails I18n ships with the I18n.with_locale method and Translation.io is of course fully compatible with it.

Here is a basic example of usage :

I18n.locale #=> :en

I18n.with_locale(:fr) do
  I18n.locale #=> :fr
end

I18n.locale #=> :en

And a real world example in a mailer :

class UserMailer < ActionMailer::Base
  default from: 'noreply@translation.io'

  def invitation(user)
    I18n.with_locale(user.locale) do
      mail({
        :subject => _("You have been invited"),
        :to      => user.email
      })
    end
  end
end