Skip to content

Commit

Permalink
Fix issue with disabled subtrees and pluralization for KeyValue backend
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Jan 17, 2018
1 parent 405b672 commit ef2bc12
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 6 deletions.
10 changes: 5 additions & 5 deletions lib/i18n/backend/base.rb
Expand Up @@ -34,17 +34,17 @@ def translate(locale, key, options = {})
entry = resolve(locale, key, entry, options)
end

entry = entry.dup if entry.is_a?(String)

count = options[:count]
entry = pluralize(locale, entry, count) if count

if entry.nil?
if (options.key?(:default) && !options[:default].nil?) || !options.key?(:default)
throw(:exception, I18n::MissingTranslation.new(locale, key, options))
end
end

entry = entry.dup if entry.is_a?(String)

count = options[:count]
entry = pluralize(locale, entry, count) if count

deep_interpolation = options[:deep_interpolation]
values = options.except(*RESERVED_KEYS)
if values
Expand Down
46 changes: 45 additions & 1 deletion lib/i18n/backend/key_value.rb
Expand Up @@ -107,7 +107,51 @@ def lookup(locale, key, scope = [], options = {})
key = normalize_flat_keys(locale, key, scope, options[:separator])
value = @store["#{locale}.#{key}"]
value = JSON.decode(value) if value
value.is_a?(Hash) ? value.deep_symbolize_keys : value

if value.is_a?(Hash)
value.deep_symbolize_keys
elsif !value.nil?
value
elsif !@subtrees
SubtreeProxy.new("#{locale}.#{key}", @store)
end
end
end

class SubtreeProxy
def initialize(master_key, store)
@master_key = master_key
@store = store
@subtree = nil
end

def has_key?(key)
@subtree && @subtree.has_key?(key) || self[key]
end

def [](key)
unless @subtree && value = @subtree[key]
value = @store["#{@master_key}.#{key}"]
(@subtree ||= {})[key] = JSON.decode(value) if value
end
value
end

def is_a?(klass)
Hash == klass || super
end
alias :kind_of? :is_a?

def instance_of?(klass)
Hash == klass || super
end

def nil?
@subtree.nil?
end

def inspect
@subtree.inspect
end
end

Expand Down
6 changes: 6 additions & 0 deletions test/backend/key_value_test.rb
Expand Up @@ -40,4 +40,10 @@ def assert_flattens(expected, nested, escape=true, subtree=true)
I18n.t("foo", :raise => true)
end
end

test "translate handles subtrees for pluralization" do
setup_backend!(false)
store_translations(:en, :bar => { :one => "One" })
assert_equal("One", I18n.t("bar", :count => 1))
end
end if I18n::TestCase.key_value?

0 comments on commit ef2bc12

Please sign in to comment.