Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thread Safety Fix #352

Merged
merged 8 commits into from Oct 10, 2017
Merged
2 changes: 2 additions & 0 deletions i18n.gemspec
Expand Up @@ -19,4 +19,6 @@ Gem::Specification.new do |s|
s.rubyforge_project = '[none]'
s.required_rubygems_version = '>= 1.3.5'
s.required_ruby_version = '>= 1.9.3'

s.add_dependency 'concurrent-ruby', '~> 1.0'
end
15 changes: 10 additions & 5 deletions lib/i18n.rb
@@ -1,3 +1,5 @@
require 'concurrent/map'

require 'i18n/version'
require 'i18n/exceptions'
require 'i18n/interpolate/ruby'
Expand All @@ -12,6 +14,11 @@ module I18n
RESERVED_KEYS = [:scope, :default, :separator, :resolve, :object, :fallback, :fallback_in_progress, :format, :cascade, :throw, :raise, :deep_interpolation]
RESERVED_KEYS_PATTERN = /%\{(#{RESERVED_KEYS.join("|")})\}/


def self.new_double_nested_cache # :nodoc:
Concurrent::Map.new { |h,k| h[k] = Concurrent::Map.new }
end

module Base
# Gets I18n configuration object.
def config
Expand Down Expand Up @@ -321,8 +328,10 @@ def handle_exception(handling, exception, locale, key, options)
end
end

@@normalized_key_cache = I18n.new_double_nested_cache

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
Expand All @@ -333,10 +342,6 @@ def normalize_key(key, separator)
keys
end
end

def normalized_key_cache
@normalized_key_cache ||= Hash.new { |h,k| h[k] = {} }
end
end

extend Base
Expand Down
6 changes: 3 additions & 3 deletions lib/i18n/backend/flatten.rb
Expand Up @@ -43,7 +43,7 @@ def normalize_flat_keys(locale, key, scope, separator)

# Store flattened links.
def links
@links ||= Hash.new { |h,k| h[k] = {} }
@links ||= I18n.new_double_nested_cache
end

# Flatten keys for nested Hashes by chaining up keys:
Expand Down Expand Up @@ -99,7 +99,7 @@ def resolve_link(locale, key)
end

def find_link(locale, key) #:nodoc:
links[locale].each do |from, to|
links[locale].each_pair do |from, to|
return [from, to] if key[0, from.length] == from
end && nil
end
Expand All @@ -110,4 +110,4 @@ def escape_default_separator(key) #:nodoc:

end
end
end
end
2 changes: 1 addition & 1 deletion lib/i18n/backend/memoize.rb
Expand Up @@ -34,7 +34,7 @@ def lookup(locale, key, scope = nil, options = {})
end

def memoized_lookup
@memoized_lookup ||= Hash.new { |h, k| h[k] = {} }
@memoized_lookup ||= I18n.new_double_nested_cache
end

def reset_memoizations!(locale=nil)
Expand Down