localized.rb 932 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # frozen_string_literal: true
  2. module Localized
  3. extend ActiveSupport::Concern
  4. included do
  5. around_action :set_locale
  6. end
  7. private
  8. def set_locale
  9. locale = current_user.locale if respond_to?(:user_signed_in?) && user_signed_in?
  10. locale ||= session[:locale] ||= default_locale
  11. locale = default_locale unless I18n.available_locales.include?(locale.to_sym)
  12. I18n.with_locale(locale) do
  13. yield
  14. end
  15. end
  16. def default_locale
  17. if ENV['DEFAULT_LOCALE'].present?
  18. I18n.default_locale
  19. else
  20. request_locale || I18n.default_locale
  21. end
  22. end
  23. def request_locale
  24. preferred_locale || compatible_locale
  25. end
  26. def preferred_locale
  27. http_accept_language.preferred_language_from(available_locales)
  28. end
  29. def compatible_locale
  30. http_accept_language.compatible_language_from(available_locales)
  31. end
  32. def available_locales
  33. I18n.available_locales.reverse
  34. end
  35. end