skip to content

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%

answer

  1. Rails parses neither for you
  2. request.subdomains.first
  3. tld_length decides what counts as subdomain
  4. q-values and region subtags
  5. match against available_locales, else default

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.

solid answer

~40 s

For a subdomain, `request.subdomains` splits the host using `config.action_dispatch.tld_length` (1 by default), so `fr.visit-lyon.com` gives `["fr"]`; take the first entry and accept it only if `I18n.locale_available?`. On a two-part suffix such as `.co.uk` the bare domain reports a spurious subdomain unless `tld_length` is 2, which validation absorbs. For the browser's preference, `request.headers["Accept-Language"]` is a raw string like `"fr-CA,fr;q=0.9,en;q=0.8"`: split it into tags, order them by `q`, try each tag and then its base language (`fr-CA` to `fr`) against `I18n.available_locales`, and fall back to `default_locale`. The guide's one-liner `scan(/^[a-z]{2}/)` reads only the first two letters. Use the header as a first-visit default; an explicit URL or saved choice should win, and pages that vary by header need care with shared caches.

code

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

  private
    def switch_locale(&action)
      locale = locale_from_subdomain || locale_from_accept_language || I18n.default_locale
      I18n.with_locale(locale, &action)
    end

    def locale_from_subdomain
      candidate = request.subdomains.first
      candidate if I18n.locale_available?(candidate)
    end
end

go deeper

for a junior

Recall request.subdomains and request.headers['Accept-Language'], and that the value must be checked against available locales.

for a middle

Explain tld_length, q-value ordering and base-language matching, and why raw values raise InvalidLocale.

for a senior

Show how you order URL, preference and header sources, and handle caches and crawlers for header-chosen pages.

for a principal

Weigh subdomains, paths and negotiation for SEO, caching and operational cost when adding a language to the product.

## Rails gives you the raw inputs only Rails does not negotiate a locale. It exposes the request's host and headers, and your `around_action` turns them into one validated value for `I18n.with_locale`. Both sources below are common on a city-tourism site: a subdomain per language for marketing pages, and the browser's language for a visitor's first request. ## Subdomains `request.subdomains` returns an Array, `request.subdomain` the same parts joined with dots. Both depend on **`config.action_dispatch.tld_length`**, the number of labels Rails treats as the public suffix (1 by default): | Host | `tld_length` | `request.subdomains` | |---|---|---| | `fr.visit-lyon.com` | 1 | `["fr"]` | | `visit-lyon.com` | 1 | `[]` | | `fr.visit-lyon.co.uk` | 2 | `["fr"]` | | `visit-lyon.co.uk` | 1 | `["visit-lyon"]` (suffix miscounted) | ```ruby def locale_from_subdomain candidate = request.subdomains.first candidate if I18n.locale_available?(candidate) end ``` Points to watch: - **Validate** the label; `www`, `api` or a miscounted domain name must not reach `with_locale`. - **Set `tld_length`** for two-part suffixes so `request.subdomain` means what you think. - **Development hosts**: Rails' host authorization allows `.localhost` and `.test` names by default in development, so a name such as `fr.visit-lyon.localhost` can exercise the code locally. - **Links between languages** are full URLs to another host, so the locale switcher builds them from the host, not from a path segment. ## The Accept-Language header Browsers send the visitor's language list with quality weights: ```http Accept-Language: fr-CA,fr;q=0.9,en;q=0.8,de;q=0.5 ``` `request.headers["Accept-Language"]` (or `request.env["HTTP_ACCEPT_LANGUAGE"]`) returns that string unparsed. A sound extraction: 1. Split on commas; for each entry read the tag and its `q` (default 1.0). 2. Sort by `q`, highest first, and drop entries with `q=0`. 3. For each tag, try the full tag (`fr-CA`) and then its base language (`fr`) against `I18n.available_locales`. 4. Return the first match, or `nil` so the caller falls back to `I18n.default_locale`. ```ruby def locale_from_accept_language header = request.headers["Accept-Language"].to_s tags = header.split(",").filter_map do |part| tag, q = part.strip.split(";q=") [tag, (q || 1).to_f] unless tag.blank? || q.to_s == "0" end tags.sort_by { |_, q| -q }.each do |tag, _| [tag, tag.split("-").first].each { |c| return c if I18n.locale_available?(c) } end nil end ``` The rails guide shows `request.env["HTTP_ACCEPT_LANGUAGE"]&.scan(/^[a-z]{2}/)&.first` and calls it intentionally simple: it reads only the first two lowercase letters of the header, so it ignores weights, later tags and region subtags. Libraries exist for robust parsing; the logic above is what they do. ## What goes wrong - **Unvalidated values** become `I18n::InvalidLocale` and a 500. - **Exact-match only** sends a `fr-CA` browser to English when only `:fr` is available. - **The header overrides the user.** A visitor who picked German from the switcher should not be bounced back to French by their browser; treat the header as the last source before the default. - **Caching.** A page whose language depends on a header but whose URL does not can be stored once by a shared cache and served to everyone in that language; varying the cache on the header or putting the locale in the URL avoids that. ## Remembering and testing the choice A header or subdomain guess is best confirmed once and then made explicit: redirect a first-time visitor to the path for the detected locale, or store the choice (a cookie or the signed-in visitor's record) so later requests no longer depend on the guess. Both sources are easy to test in an integration test: ```ruby get root_path, headers: { "Accept-Language" => "fr-CA,fr;q=0.9,en;q=0.8" } assert_select "h1", "Bienvenue à Lyon" host! "de.visit-lyon.com" get root_path assert_select "h1", "Willkommen in Lyon" ``` `host!` sets the host for subsequent requests in the test session, so `request.subdomains` sees `de`. ## Putting it together A typical `switch_locale` tries `params[:locale]`, then the subdomain, then a saved preference, then the header, then `I18n.default_locale`, and wraps the action in `I18n.with_locale`. The interview signal is knowing Rails hands you only raw strings, and that matching, weighting and validation are the application's job.

  • Why does a fr-CA browser get English when available_locales is [:en, :fr]?
    Because the code compares the full tag only. `fr-CA` is not on the list, so the lookup falls through to the default. Trying the base language after the full tag (`fr-CA`, then `fr`) fixes it; alternatively add `:"fr-CA"` to the list with a fallback to `:fr`.
  • Where should the Accept-Language header sit among the locale sources?
    Last before the default. An explicit locale in the URL or subdomain, and a choice the visitor saved, express intent; the header only reflects browser settings. Using it first would override a visitor who deliberately switched language.

  • Rails sets I18n.locale from Accept-Language automatically.
  • request.subdomain returns an Array of labels.
  • The first two letters of Accept-Language are always the preferred language.
  • A fr-CA tag will match :fr in available_locales without extra code.
  • The header should override a language the visitor picked in the switcher.