From 3288aee6c356cf7af3729fd2a99dc378dbeb1f9d Mon Sep 17 00:00:00 2001 From: Mike Perham Date: Thu, 9 Apr 2015 11:14:05 -0700 Subject: [PATCH] Update web locale determination, fixes #2243 The code worked with "fr,en" but did not work with "fr-FR,fr,en" --- Changes.md | 1 + lib/sidekiq/web_helpers.rb | 15 +++++++++++-- test/test_web_helpers.rb | 46 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 test/test_web_helpers.rb diff --git a/Changes.md b/Changes.md index f76046dc..ef58aaa8 100644 --- a/Changes.md +++ b/Changes.md @@ -8,6 +8,7 @@ HEAD - Web UI polling now uses Ajax to avoid page reload [#2266, davydovanton] - Several Web UI styling improvements [davydovanton] - Add Tamil, Hindi translations for Web UI [ferdinandrosario, tejasbubane] +- Fix Web UI to work with country-specific locales [#2243] - Handle circular error causes [#2285, eugenk] 3.3.3 diff --git a/lib/sidekiq/web_helpers.rb b/lib/sidekiq/web_helpers.rb index e88d5114..694b01d5 100644 --- a/lib/sidekiq/web_helpers.rb +++ b/lib/sidekiq/web_helpers.rb @@ -45,9 +45,20 @@ module Sidekiq eval('', block.binding) end + # Given a browser request Accept-Language header like + # "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,ru;q=0.2", this function + # will return "fr" since that's the first code with a matching + # locale in web/locales def locale - lang = (request.env["HTTP_ACCEPT_LANGUAGE"] || 'en').split(',')[0].downcase - strings[lang] ? lang : 'en' + @locale ||= begin + locale = 'en'.freeze + languages = request.env['HTTP_ACCEPT_LANGUAGE'.freeze] || 'en'.freeze + languages.downcase.split(','.freeze).each do |lang| + lang = lang.split(';'.freeze)[0] + break locale = lang if strings.has_key?(lang) + end + locale + end end def get_locale diff --git a/test/test_web_helpers.rb b/test/test_web_helpers.rb new file mode 100644 index 00000000..0dadaa3a --- /dev/null +++ b/test/test_web_helpers.rb @@ -0,0 +1,46 @@ +require_relative 'helper' +require 'sidekiq' +require 'sidekiq/web_helpers' + +class TestWebHelpers < Sidekiq::Test + + class Helpers + include Sidekiq::WebHelpers + + def initialize(params={}) + @thehash = default.merge(params) + end + + def request + self + end + + def settings + self + end + + def locales + ['web/locales'] + end + + def env + @thehash + end + + def default + { + } + end + end + + def test_locale_determination + obj = Helpers.new + assert_equal 'en', obj.locale + + obj = Helpers.new('HTTP_ACCEPT_LANGUAGE' => 'fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,ru;q=0.2') + assert_equal 'fr', obj.locale + + obj = Helpers.new('HTTP_ACCEPT_LANGUAGE' => 'zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4,ru;q=0.2') + assert_equal 'zh-cn', obj.locale + end +end