Skip to content

Commit

Permalink
Merge pull request #352 from svenfuchs/pr-51-thread-safety-fix
Browse files Browse the repository at this point in the history
Thread Safety Fix
  • Loading branch information
radar committed Oct 10, 2017
2 parents 4b36936 + 3da644f commit bf58182
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 9 deletions.
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

0 comments on commit bf58182

Please sign in to comment.