Class: Brut::FrontEnd::RouteHooks::LocaleDetection

Inherits:
Brut::FrontEnd::RouteHook show all
Defined in:
lib/brut/front_end/route_hooks/locale_detection.rb

Overview

Detects the user’s locale from the ‘Accept-Language` header and, if one of the locales has been set up in this app, configured Ruby’s ‘I18n` to use it. This will also store the value in the session via Session#http_accept_language=.

Instance Method Summary collapse

Methods inherited from Brut::FrontEnd::RouteHook

#after, #continue

Methods included from Brut::Framework::Errors

#abstract_method!, #bug!

Methods included from HandlingResults

#http_status, #redirect_to

Instance Method Details

#before(session:, env:) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/brut/front_end/route_hooks/locale_detection.rb', line 6

def before(session:,env:)
  http_accept_language = Brut::I18n::HTTPAcceptLanguage.from_header(env["HTTP_ACCEPT_LANGUAGE"])
  if !session.http_accept_language.known?
    session.http_accept_language = http_accept_language
  end
  best_locale = nil
  session.http_accept_language.weighted_locales.each do |weighted_locale|
    if ::I18n.available_locales.include?(weighted_locale.locale.to_sym)
      best_locale = weighted_locale.locale.to_sym
      break
    elsif ::I18n.available_locales.include?(weighted_locale.primary_only.locale.to_sym)
      best_locale = weighted_locale.primary_only.locale.to_sym
      break
    end
  end
  if best_locale
    Brut.container.instrumentation.add_attributes(prefix: "brut.locale-detection", best_locale:)
    ::I18n.locale = best_locale
  else
    Brut.container.instrumentation.add_attributes(prefix: "brut.locale-detection", best_locale: false)
  end
  continue
end