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-Language →
default → I18n.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
-
#resolved_locale ⇒ Object
The locale chosen for this request — always one I18n can switch to.
-
#switch_locale ⇒ Object
Public so subclasses can override; runs the action under the resolved locale.
Instance Method Details
#resolved_locale ⇒ Object
The locale chosen for this request — always one I18n can switch to.
49 50 51 52 53 54 55 |
# File 'lib/concerns_on_rails/controllers/localizable.rb', line 49 def resolved_locale opts = self.class. 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 |
#switch_locale ⇒ Object
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 |