skip to content

Per-Request Locale Choice

Each request picks its locale from params, a path scope, a subdomain or Accept-Language and wraps the action in I18n.with_locale. Interviewers probe why assigning I18n.locale leaks across requests.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In a Rails controller, how do you set each request's locale from params[:locale] or a (:locale) route scope, and why use I18n.with_locale in an around_action?

level: middleimportance: must knowfreq 62%

answer

  1. one concern in ApplicationController
  2. around_action :switch_locale
  3. params[:locale] from query or path
  4. check with I18n.locale_available?
  5. with_locale restores in an ensure

basics

~10 s

Add around_action :switch_locale to ApplicationController, take params[:locale] (filled by ?locale= or a (:locale) path scope) when I18n.locale_available? accepts it, else default_locale, and run I18n.with_locale(locale, &action), which restores the previous locale afterwards.

solid answer

~40 s

The idiom is a concern included in `ApplicationController` that declares `around_action :switch_locale`. The method reads `params[:locale]`, which Rails fills from a query string (`/tours?locale=fr`) or from an optional path segment declared with `scope "(:locale)", locale: /en|fr|de/` in `config/routes.rb`; checks it with `I18n.locale_available?`; falls back to `I18n.default_locale`; and runs the action with `I18n.with_locale(locale, &action)`. `with_locale` sets the locale, yields, and restores the previous value in an `ensure`, so the action, its rendering and its redirect all see one locale and nothing is left on the thread, even when the action raises. Assigning `I18n.locale =` in a `before_action` sets state that outlives the request on that server thread. Generated links keep the locale through `default_url_options`.

code

ruby · 14 lines
ruby
class ApplicationController < ActionController::Base
  around_action :switch_locale

  private
    def switch_locale(&action)
      locale = params[:locale]
      locale = I18n.default_locale unless I18n.locale_available?(locale)
      I18n.with_locale(locale, &action)
    end

    def default_url_options
      { locale: I18n.locale }
    end
end

go deeper

for a junior

Recall the around_action that wraps the action in I18n.with_locale and the params[:locale] source.

for a middle

Explain why with_locale restores state, why the locale must be validated against available_locales, and how a (:locale) scope fills params.

for a senior

Show how you cover error pages, language switchers and handed-off work, and how you order URL, preference and header sources.

for a principal

Weigh path, subdomain and preference strategies for discoverability, caching and shared links across the product's locales.

## The pattern Rails does not pick a locale per request on its own; every request starts in whatever locale its thread currently holds, normally `I18n.default_locale`. The standard place to choose one is a controller callback that wraps the whole action. ```ruby # app/controllers/concerns/localized.rb module Localized extend ActiveSupport::Concern included do around_action :switch_locale end private def switch_locale(&action) locale = params[:locale] locale = I18n.default_locale unless I18n.locale_available?(locale) I18n.with_locale(locale, &action) end end ``` `include Localized` in `ApplicationController` covers every controller that inherits from it. ## Where `params[:locale]` comes from | Source | Example URL | How it reaches `params` | |---|---|---| | Query string | `/tours?locale=fr` | any route; Rails parses the query | | Optional path scope | `/fr/tours` and `/tours` | `scope "(:locale)", locale: /en\|fr\|de/` around the routes | | Required path scope | `/fr/tours` only | `scope "/:locale"`; a URL without a locale does not match | With the constrained optional scope, `/it/tours` does not match the scoped routes at all, so it ends in a routing error (a 404 page in production) before any controller runs. A query parameter has no such guard: `?locale=it` reaches the controller and must be validated there. To keep the locale in links, the app overrides `default_url_options` to return `{ locale: I18n.locale }`; route helpers then add it to every generated path. The root path needs its own `get "/:locale" => ...` mapping, since `root` ignores the scope. ## Why validate before switching `I18n.enforce_available_locales` is true by default. Passing an unchecked `"it"` or a junk string to `with_locale` raises `I18n::InvalidLocale`, which turns a mistyped or malicious URL into a 500. `I18n.locale_available?` accepts strings and symbols and returns false for `nil` and unknown values, so one check covers missing and invalid input. ## Why `with_locale` in an `around_action` 1. **It wraps everything the action does.** An `around_action` yields to the action, so the locale is set during rendering, redirects, flash messages and anything else in that block, not only in the action body. 2. **It cleans up.** `I18n.with_locale` saves the current locale, assigns the new one, yields, and restores the saved value in an `ensure`. A raised exception still restores it. 3. **It cannot leak.** `I18n.locale` is per-thread state, and Puma serves many requests on each thread. A `before_action` that only assigns `I18n.locale =` leaves the value behind for the next request on that thread whose controller does not set one. 4. **It drives template lookup too.** The controller's lookup context follows `I18n.locale`, so `show.fr.html.erb` is preferred over `show.html.erb` while the block runs. `with_locale(nil)` simply yields without changing anything, which is why the snippet resolves a concrete default instead of passing `params[:locale]` straight through. ## Things that run outside the block - **`rescue_from` handlers** run after the around callback has unwound, so an error page they render uses the restored locale, not the request's. Re-apply the locale inside the handler if error pages must be translated. - **Work handed off** to Active Job keeps the locale because the job records it at enqueue time; plain threads you start yourself do not get that treatment. ## Testing the switch An integration test can check both the chosen language and the cleanup: ```ruby test "French tour page" do get tour_path(tours(:old_town), locale: :fr) assert_select "h1", "Vieille ville" assert_equal :en, I18n.locale # restored after the request end ``` The last assertion only holds because `with_locale` restores the value; with plain assignment the test thread would still hold `:fr`. Rails' own mailer-preview controller uses the same `around_action` with `I18n.with_locale`, which is a useful reference when someone asks whether the pattern is idiomatic. ## Choosing among sources A tourism site usually combines sources in a fixed order: an explicit locale in the URL first, a signed-in visitor's saved preference next, the browser's language for first visits, and `default_locale` last. Whatever the order, it ends in one validated value passed to `with_locale`. Interviewers asking this want the callback type, the validation and the reason `with_locale` beats assignment.

  • Why does an error page rendered by rescue_from come out in the default locale?
    In `ActionController::Base`, `Rescue` wraps the callbacks, so an exception first unwinds the `around_action`; `with_locale`'s `ensure` restores the previous locale, and only then does the `rescue_from` handler render. Re-apply the locale inside the handler, for example by calling `I18n.with_locale(resolved_locale) { render ... }`.
  • What does I18n.with_locale(params[:locale], &action) do when the request has no locale param?
    `with_locale(nil)` just yields without touching the locale, so the action runs in whatever the thread currently holds, normally the default. Resolving an explicit default first, as the concern does, makes the result independent of what an earlier request left behind.
  • How do you build a language switcher that links to the same page in each locale?
    Pass the locale explicitly, for example `url_for(locale: :de)` or `tour_path(@tour, locale: :de)`, instead of changing `I18n.locale` in a loop, because `default_url_options` is evaluated once per request and its result is cached.

  • A before_action that assigns I18n.locale is just as safe as with_locale.
  • Passing params[:locale] straight to I18n.with_locale is fine because unknown locales fall back.
  • Rails sets I18n.locale from params[:locale] automatically when the route has a :locale segment.
  • I18n.with_locale(nil) resets the locale to default_locale.
  • rescue_from handlers always render in the locale the action used.
open as a page

In a Rails app, what do config.i18n.default_locale and config.i18n.available_locales control, and what happens when code asks for an unlisted locale?

level: juniorimportance: should knowfreq 45%

basics

~20 s

default_locale (:en unless configured) is what I18n.locale returns until something sets it; available_locales is the allow list, derived from loaded translation data when unset. Since enforce_available_locales defaults to true, using an unlisted locale raises I18n::InvalidLocale.

open as a page

In a Rails controller, how would you take the locale from a subdomain like fr.visit-lyon.com or from the Accept-Language header, and what goes wrong?

level: middleimportance: should knowfreq 35%

basics

~10 s

Rails parses neither for you: read request.subdomains.first or request.headers['Accept-Language'], map the value onto I18n.available_locales, and fall back to default_locale. Raw values raise I18n::InvalidLocale, and naive header parsing ignores q-values and region tags.

open as a page

In Rails 8.1, what does config.i18n.fallbacks = true in the generated production.rb do, and why can a missing French key look fine in production but not in development?

level: seniorimportance: should knowfreq 38%

basics

~20 s

It includes I18n::Backend::Fallbacks and builds I18n.fallbacks from default_locale, so a key missing in :fr is tried in its parent locales and then :en. Only production.rb sets it, so development shows the missing-key marker while production quietly prints English.

open as a page

When a Rails controller calls perform_later inside I18n.with_locale(:fr), which locale does the Active Job run in, and why?

level: seniorimportance: should knowfreq 32%

basics

~10 s

French. Active Job writes I18n.locale into the job's serialized 'locale' field at enqueue time, and perform_now runs perform inside I18n.with_locale(locale), so the worker translates in fr whatever its own thread's locale is.

open as a page

A Rails city-guide app assigns I18n.locale = params[:locale] in EventsController's before_action; why do visitors to other pages sometimes see German?

level: seniorimportance: should knowfreq 45%

basics

~20 s

I18n.locale is per-thread state and Puma reuses threads across requests. Rails never resets it, so German set during an events request stays on that thread and shows up on the next request whose controller sets no locale.

open as a page