localized.rb 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. # frozen_string_literal: true
  2. module Localized
  3. extend ActiveSupport::Concern
  4. included do
  5. around_action :set_locale
  6. end
  7. def set_locale(&block)
  8. I18n.with_locale(requested_locale || I18n.default_locale, &block)
  9. end
  10. private
  11. def requested_locale
  12. requested_locale_name = available_locale_or_nil(params[:lang])
  13. requested_locale_name ||= available_locale_or_nil(current_user.locale) if respond_to?(:user_signed_in?) && user_signed_in?
  14. requested_locale_name ||= http_accept_language if ENV['DEFAULT_LOCALE'].blank?
  15. requested_locale_name
  16. end
  17. def http_accept_language
  18. HttpAcceptLanguage::Parser.new(request.headers.fetch('Accept-Language')).language_region_compatible_from(I18n.available_locales) if request.headers.key?('Accept-Language')
  19. end
  20. def available_locale_or_nil(locale_name)
  21. locale_name.to_sym if locale_name.present? && I18n.available_locales.include?(locale_name.to_sym)
  22. end
  23. def content_locale
  24. @content_locale ||= I18n.locale.to_s.split(/[_-]/).first
  25. end
  26. end