class LanguagesController < ApplicationController
|
|
|
|
before_action :set_locale_to_default
|
|
helper_method :accept_language
|
|
|
|
def index
|
|
|
|
|
|
end
|
|
|
|
|
|
def update
|
|
set_locale
|
|
|
|
# Respond with Turbo Stream that updates the content div
|
|
respond_to do |format|
|
|
format.turbo_stream
|
|
end
|
|
end
|
|
|
|
|
|
private
|
|
|
|
def accept_language
|
|
@accept_language ||= first_matching_language
|
|
end
|
|
|
|
|
|
def first_matching_language
|
|
accept_languages = request.env['HTTP_ACCEPT_LANGUAGE'].to_s.split(',').map { |l|
|
|
lang, q_factor = l.split(';q=')
|
|
[lang, (q_factor || '1').to_f]
|
|
}.sort_by { |_, q| -q }.map(&:first)
|
|
|
|
available_languages = I18n.t('languages').keys.map(&:to_s)
|
|
|
|
accept_languages.each do |lang|
|
|
return lang if available_languages.include?(lang)
|
|
|
|
lang_part = lang.split('-').first
|
|
if available_languages.include?(lang_part)
|
|
return lang_part
|
|
else
|
|
wildcard_match = available_languages.find { |l| l.start_with?("#{lang_part}-") }
|
|
return wildcard_match if wildcard_match
|
|
end
|
|
end
|
|
'en'
|
|
end
|
|
|
|
|
|
def set_locale_to_default
|
|
I18n.locale = I18n.default_locale
|
|
end
|
|
|
|
end
|