From 6f4821cff88acc6f2c1014b76a98abe83339e692 Mon Sep 17 00:00:00 2001 From: Anton Davydov Date: Fri, 10 Apr 2015 00:26:03 +0300 Subject: [PATCH] Load only required locale files --- lib/sidekiq/web_helpers.rb | 25 ++++++++++++++++++------- test/test_web.rb | 13 +++++++++++++ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/lib/sidekiq/web_helpers.rb b/lib/sidekiq/web_helpers.rb index 694b01d5..f5092260 100644 --- a/lib/sidekiq/web_helpers.rb +++ b/lib/sidekiq/web_helpers.rb @@ -3,19 +3,30 @@ require 'uri' module Sidekiq # This is not a public API module WebHelpers - def strings - @@strings ||= begin + def strings(lang) + @@strings ||= {} + @@strings[lang] ||= begin # Allow sidekiq-web extensions to add locale paths # so extensions can be localized - settings.locales.each_with_object({}) do |path,global| - Dir["#{path}/*.yml"].each_with_object(global) do |file,hash| + settings.locales.each_with_object({}) do |path, global| + find_locale_files(lang).each do |file| strs = YAML.load(File.open(file)) - hash.deep_merge!(strs) + global.deep_merge!(strs[lang]) end end end end + def locale_files + @@locale_files = settings.locales.flat_map do |path| + Dir["#{path}/*.yml"] + end + end + + def find_locale_files(lang) + locale_files.select { |file| file =~ /\/#{lang}\.yml$/ } + end + # This is a hook for a Sidekiq Pro feature. Please don't touch. def filtering(*) end @@ -55,14 +66,14 @@ module Sidekiq 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) + break locale = lang if find_locale_files(lang).any? end locale end end def get_locale - strings[locale] + strings(locale) end def t(msg, options={}) diff --git a/test/test_web.rb b/test/test_web.rb index 8953623b..45045944 100644 --- a/test/test_web.rb +++ b/test/test_web.rb @@ -1,3 +1,4 @@ +# encoding: utf-8 require_relative 'helper' require 'sidekiq' require 'sidekiq/web' @@ -29,6 +30,18 @@ class TestWeb < Sidekiq::Test end end + it 'can show text with any locales' do + rackenv = {'HTTP_ACCEPT_LANGUAGE' => 'ru,en'} + get '/', {}, rackenv + assert_match(/Панель управления/, last_response.body) + rackenv = {'HTTP_ACCEPT_LANGUAGE' => 'es,en'} + get '/', {}, rackenv + assert_match(/Panel de Control/, last_response.body) + rackenv = {'HTTP_ACCEPT_LANGUAGE' => 'en-us'} + get '/', {}, rackenv + assert_match(/Dashboard/, last_response.body) + end + describe 'busy' do it 'can display workers' do