Module: ConcernsOnRails::Controllers::Localizable

Extended by:
ActiveSupport::Concern
Defined in:
lib/concerns_on_rails/controllers/localizable.rb

Overview

Per-request locale selection from the request params and/or the Accept-Language header, wrapped in an around_action so I18n.locale is set for the action and restored afterwards.

class ApplicationController < ActionController::Base
include ConcernsOnRails::Controllers::Localizable

localizable available: %i[en fr de], default: :en
# localizable param: :lang, header: false   # params[:lang] only
end

Resolution order: params[param] → first match in Accept-LanguagedefaultI18n.default_locale. The chosen locale is always validated against I18n.available_locales before use, so a stray param or a mismatched available: list can never raise I18n::InvalidLocale.

Options: available: (allow-list for param/header matching; defaults to I18n.available_locales), default:, param: (default :locale), header: (default true).

Instance Method Summary collapse

Instance Method Details

#resolved_localeObject

The locale chosen for this request — always one I18n can switch to. Memoized per request (the wrapper plus any helpers may read it several times; parsing the Accept-Language header repeatedly is waste).



51
52
53
54
55
56
57
58
59
# File 'lib/concerns_on_rails/controllers/localizable.rb', line 51

def resolved_locale
  @resolved_locale ||= begin
    opts = self.class.localizable_options
    allowed = opts[:available].presence || I18n.available_locales
    candidate = locale_from_param(opts, allowed) || locale_from_header(opts, allowed) || opts[:default]

    candidate && I18n.available_locales.include?(candidate.to_sym) ? candidate.to_sym : I18n.default_locale
  end
end

#switch_localeObject

Public so subclasses can override; runs the action under the resolved locale.



44
45
46
# File 'lib/concerns_on_rails/controllers/localizable.rb', line 44

def switch_locale(&)
  I18n.with_locale(resolved_locale, &)
end