2017-04-07 03:40:26 -07:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Localized
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
2019-07-21 09:08:02 -07:00
|
|
|
around_action :set_locale
|
2017-04-07 03:40:26 -07:00
|
|
|
end
|
|
|
|
|
2022-02-07 17:34:56 -08:00
|
|
|
def set_locale(&block)
|
|
|
|
I18n.with_locale(requested_locale || I18n.default_locale, &block)
|
2017-04-07 03:40:26 -07:00
|
|
|
end
|
|
|
|
|
2020-06-20 04:30:13 -07:00
|
|
|
private
|
|
|
|
|
2022-02-07 17:34:56 -08:00
|
|
|
def requested_locale
|
2022-02-18 18:12:28 -08:00
|
|
|
requested_locale_name = available_locale_or_nil(params[:lang])
|
2022-02-07 17:34:56 -08:00
|
|
|
requested_locale_name ||= available_locale_or_nil(current_user.locale) if respond_to?(:user_signed_in?) && user_signed_in?
|
|
|
|
requested_locale_name ||= http_accept_language if ENV['DEFAULT_LOCALE'].blank?
|
|
|
|
requested_locale_name
|
|
|
|
end
|
|
|
|
|
|
|
|
def http_accept_language
|
|
|
|
HttpAcceptLanguage::Parser.new(request.headers.fetch('Accept-Language')).language_region_compatible_from(I18n.available_locales) if request.headers.key?('Accept-Language')
|
2017-06-10 00:44:02 -07:00
|
|
|
end
|
|
|
|
|
2022-02-07 17:34:56 -08:00
|
|
|
def available_locale_or_nil(locale_name)
|
|
|
|
locale_name.to_sym if locale_name.present? && I18n.available_locales.include?(locale_name.to_sym)
|
2017-04-14 16:12:39 -07:00
|
|
|
end
|
2022-02-24 15:34:14 -08:00
|
|
|
|
|
|
|
def content_locale
|
|
|
|
@content_locale ||= I18n.locale.to_s.split(/[_-]/).first
|
|
|
|
end
|
2017-04-07 03:40:26 -07:00
|
|
|
end
|