Skip to content
Snippets Groups Projects
Unverified Commit 710fdbb3 authored by Sébastien Gaya's avatar Sébastien Gaya
Browse files

switch locale + rack::locale

parent ae203983
No related branches found
No related tags found
No related merge requests found
......@@ -30,6 +30,7 @@ gem 'kaminari'
gem 'octokit'
gem 'front_matter_parser'
gem 'two_factor_authentication', git: 'https://github.com/lespoupeesrusses/two_factor_authentication.git'
gem 'rack-contrib'
# Front
gem 'jquery-rails'
......
......@@ -240,6 +240,8 @@ GEM
nio4r (~> 2.0)
racc (1.5.2)
rack (2.2.3)
rack-contrib (2.3.0)
rack (~> 2.0)
rack-mini-profiler (2.3.3)
rack (>= 1.2.0)
rack-protection (2.1.0)
......@@ -386,6 +388,7 @@ DEPENDENCIES
octokit
pg (~> 1.1)
puma
rack-contrib
rack-mini-profiler (~> 2.0)
rails
rails-i18n
......
......@@ -2,7 +2,7 @@ class Admin::ApplicationController < ApplicationController
layout 'admin/layouts/application'
before_action :authenticate_user!
before_action :set_locale
around_action :switch_locale
protected
......@@ -22,9 +22,8 @@ class Admin::ApplicationController < ApplicationController
: add_breadcrumb('Créer')
end
def set_locale
return unless current_user
return unless current_user.language
I18n.locale = current_user.language.iso_code
def switch_locale(&action)
locale = LocaleService.locale(current_user, request.env['HTTP_ACCEPT_LANGUAGE'])
I18n.with_locale(locale, &action)
end
end
class LocaleService
## Get best locale for a user
def self.locale(user, accept_language_header)
user&.language.nil? ? self.preferred_language(accept_language_header) : user.language.iso_code.to_sym
end
def self.preferred_language(brand_languages, accept_language_header)
# browser_language > french
browser_languages = accept_language_header&.scan(/\*|([a-z]{1,8}(?:-[A-Z0-9]{1,8})*)/i)&.flatten&.compact&.reject { |v| v == "q" }
browser_languages&.each do |code|
symbol = self.get_symbol(code)
return symbol unless symbol.nil?
end
I18n.default_locale
end
def self.get_symbol(code)
if Language.where(iso_code: code).any?
symbol = code.to_sym
elsif code.include?('-')
# safari returns only "fr-fr", so if we only have "fr" active it fallbacks to english
root_code = code.split('-').first
symbol = root_code.to_sym if Language.where(iso_code: root_code).any?
end
symbol
end
end
......@@ -23,6 +23,8 @@ module Osuny
class Application < Rails::Application
config.load_defaults 6.1
config.middleware.insert_before Warden::Manager, Rack::Locale
config.time_zone = 'Europe/Paris'
config.active_job.queue_adapter = :delayed_job
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment