Module: Homura::SetLocale

Extended by:
ActiveSupport::Concern
Defined in:
lib/homura/set_locale.rb

Instance Method Summary collapse

Instance Method Details

#available_localesObject



9
10
11
# File 'lib/homura/set_locale.rb', line 9

def available_locales
  @available_locales ||= I18n.available_locales.map(&:to_s)
end

#locale_available?(locale) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/homura/set_locale.rb', line 13

def locale_available?(locale)
  available_locales.include?(locale)
end

#set_localeObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/homura/set_locale.rb', line 17

def set_locale
  if (param_locale = params.delete('locale')) && locale_available?(param_locale)
    cookies.permanent['locale'] = param_locale
    I18n.locale = param_locale
    redirect_to params and return
  end

  if (cookie_locale = cookies['locale']) && locale_available?(cookie_locale)
    I18n.locale = cookie_locale and return
  end

  http_accept_language = request.headers['HTTP_ACCEPT_LANGUAGE'] || ''
  preferred_locales = http_accept_language.split(',').map { |l|
    l.split(';').first.downcase.gsub(/-[a-z0-9]+$/i) { |x| x.upcase }
  }
  I18n.locale = preferred_locales.find { |l|
    locale_available?(l)
  }
end