From 649d435f3fb240de6ae3d5c06d5c0c57cbb5de75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=B4mulo=20A=2E=20Ceccon?= Date: Sat, 11 Mar 2017 11:41:46 -0300 Subject: [PATCH] Initialize global hash during module load The idiom for lazy initialization with operator `||=` is not thread safe. Method `I18n#normalized_key_cache` was converted into a class variable initialized during module load to avoid a race condition. --- lib/i18n.rb | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/lib/i18n.rb b/lib/i18n.rb index 52a19635..9a259446 100644 --- a/lib/i18n.rb +++ b/lib/i18n.rb @@ -323,8 +323,10 @@ def handle_exception(handling, exception, locale, key, options) end end + @@normalized_key_cache = Concurrent::Hash.new { |h, k| h[k] = Concurrent::Hash.new } + def normalize_key(key, separator) - normalized_key_cache[separator][key] ||= + @@normalized_key_cache[separator][key] ||= case key when Array key.map { |k| normalize_key(k, separator) }.flatten @@ -335,10 +337,6 @@ def normalize_key(key, separator) keys end end - - def normalized_key_cache - @normalized_key_cache ||= Concurrent::Hash.new { |h,k| h[k] = Concurrent::Hash.new } - end end extend Base