Mind Dump, Tech And Life Blog
written by Ivan Alenko
published under license Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)copy! share!
posted at 20. May '20
last updated at 21. May '20

Ruby on Rails Internationalization (I18n) Notes

My Locale Changes Randomly In Tests

Only tests ran through puma won’t affect locale of next test in line. Reset it after tests.

RSpec.configure do |config|
  config.after(:each) { I18n.locale = I18n.default_locale }

Run tests with the seed and debug where is fails:

RSpec.configure do |config|
  config.before(:each) do |example|
    puts "#{I18n.locale} #{example.metadata[:example_group][:file_path]} #{example.description}"
bin/rspec --seed 53982

Required Settings

# config/application.rb

config.i18n.default_locale = ENV['DEFAULT_LOCALE'] || :en
config.i18n.available_locales = [:en, :sk]

Fragment Caching

Add locale to be part of the key:

- cache [I18n.locale, @article] do

Last Help

Sometimes deploy is just fucked up. Redeploy or restart containers.

My Fucking I18n Locale Leaks Across Requests

The locale isn’t reset in the same process or thread. So specific puma thread or unicorn process return the previous locale instead of expected default one.

Always set locale in before_action like:

# ApplicationController
before_action :set_locale

def set_locale
  if params[:locale]
    I18n.locale = params[:locale]
    I18n.locale = I18n.default_locale

Or use around_action like in Rails guides https://guides.rubyonrails.org/i18n.html#configure-the-i18n-module

# ApplucationController
around_action :switch_locale
def switch_locale(&action)
  locale = params[:locale] || I18n.default_locale
  I18n.with_locale(locale, &action)

If locale is invalid, it sets default one, so no need to validate against available locales.

Add Comment