From 830ce05fe64fd310d26d7da87ea6e4076696b7c8 Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 30 Mar 2015 16:31:36 +1100 Subject: [PATCH] PERF: simplify and shrink the translation cache FIX: leaking objects into the translation cache causing sidekiq to grow --- .../post_action_type_serializer.rb | 5 ++-- app/serializers/topic_flag_type_serializer.rb | 5 ++-- lib/freedom_patches/translate_accelerator.rb | 27 +++++++------------ 3 files changed, 15 insertions(+), 22 deletions(-) diff --git a/app/serializers/post_action_type_serializer.rb b/app/serializers/post_action_type_serializer.rb index 763bc3886..d32bdf1ea 100644 --- a/app/serializers/post_action_type_serializer.rb +++ b/app/serializers/post_action_type_serializer.rb @@ -25,8 +25,9 @@ class PostActionTypeSerializer < ApplicationSerializer protected - def i18n(field, vars={}) - I18n.t("post_action_types.#{object.name_key}.#{field}", vars) + def i18n(field, vars=nil) + key = "post_action_types.#{object.name_key}.#{field}" + vars ? I18n.t(key, vars) : I18n.t(key) end end diff --git a/app/serializers/topic_flag_type_serializer.rb b/app/serializers/topic_flag_type_serializer.rb index f95cf6a8d..a764d1a82 100644 --- a/app/serializers/topic_flag_type_serializer.rb +++ b/app/serializers/topic_flag_type_serializer.rb @@ -2,8 +2,9 @@ class TopicFlagTypeSerializer < PostActionTypeSerializer protected - def i18n(field, vars={}) - I18n.t("topic_flag_types.#{object.name_key}.#{field}", vars) + def i18n(field, vars=nil) + key = "topic_flag_types.#{object.name_key}.#{field}" + vars ? I18n.t(key,vars) : I18n.t(key) end end diff --git a/lib/freedom_patches/translate_accelerator.rb b/lib/freedom_patches/translate_accelerator.rb index af237e9b6..95f9f9d0b 100644 --- a/lib/freedom_patches/translate_accelerator.rb +++ b/lib/freedom_patches/translate_accelerator.rb @@ -34,7 +34,7 @@ module I18n class << self alias_method :translate_no_cache, :translate alias_method :reload_no_cache!, :reload! - LRU_CACHE_SIZE = 2000 + LRU_CACHE_SIZE = 300 def reload! @loaded_locales = [] @@ -59,25 +59,16 @@ module I18n end end - def translate(*args) + def translate(key, *args) + load_locale(config.locale) unless @loaded_locales.include?(config.locale) + return translate_no_cache(key, *args) if args.length > 0 + @cache ||= LruRedux::ThreadSafeCache.new(LRU_CACHE_SIZE) - found = true - k = [args, config.locale, config.backend.object_id] - t = @cache.fetch(k) { found = false } - unless found - load_locale(config.locale) unless @loaded_locales.include?(config.locale) - begin - t = translate_no_cache(*args) - rescue MissingInterpolationArgument - options = args.last.is_a?(Hash) ? args.pop.dup : {} - options.merge!(locale: config.default_locale) - key = args.shift - t = translate_no_cache(key, options) - ensure - t = @cache[k] = t.freeze - end + k = "#{key}#{config.locale}#{config.backend.object_id}" + + @cache.getset(k) do + translate_no_cache(key).freeze end - t end alias_method :t, :translate