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

Fix issue with disabled subtrees and pluralization for KeyValue backend #402

Merged
merged 1 commit into from Jan 18, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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?