Skip to content

Commit a230cb4

Browse files
authored
Merge pull request #129 from prograils/fix/fallback_keys_firing_unnecessary_queries
Fix/fallback keys firing unnecessary queries
2 parents 20403f6 + 9074543 commit a230cb4

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

lib/lit/i18n_backend.rb

+2-1
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ def lookup(locale, key, scope = [], options = {})
7272
# check in cache or in simple backend
7373
content = @cache[key_with_locale] || super
7474
return content if parts.size <= 1
75+
7576
if content.nil? && should_cache?(key_with_locale, options)
7677
new_content = @cache.init_key_with_value(key_with_locale, content)
7778
content = new_content if content.nil? # Content can change when Lit.humanize is true for example
@@ -181,7 +182,7 @@ def is_ignored_key(key_without_locale)
181182

182183
def should_cache?(key_with_locale, options)
183184
if @cache.has_key?(key_with_locale)
184-
return false unless options[:default]
185+
return false unless options[:default] && !options[:default].is_a?(Array)
185186
end
186187

187188
_, key_without_locale = ::Lit::Cache.split_key(key_with_locale)

test/test_helper.rb

+7
Original file line numberDiff line numberDiff line change
@@ -128,3 +128,10 @@ def new_controller_test_format?
128128
end
129129

130130
MinitestVcr::Spec.configure!
131+
132+
def assert_no_database_queries
133+
ActiveRecord::Base.connection.stubs(:execute).
134+
raises(Minitest::Assertion, 'The block should not make any database calls')
135+
yield
136+
ActiveRecord::Base.connection.unstub(:execute)
137+
end

test/unit/i18n_backend_test.rb

+19
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,23 @@ def teardown
5353
l = lk.localizations.where(locale: locale).first
5454
assert_nil l.default_value
5555
end
56+
57+
test 'will not call additional queries when nil values in a fallback key chain have been cached' do
58+
Lit.humanize_key = false
59+
I18n.locale = :en
60+
61+
test_key = :'test.key'
62+
fallback_key = :'test.fallback'
63+
64+
# first, when these keys don't exist in the DB yet, they should be created:
65+
loc_key_count = -> { Lit::LocalizationKey.where(localization_key: [test_key, fallback_key]).count }
66+
assert_equal 0, loc_key_count.call
67+
assert_equal 'foobar', I18n.t(test_key, default: [fallback_key, 'foobar'])
68+
assert_equal 2, loc_key_count.call
69+
70+
# on subsequent translation calls, they should not be fetched from DB
71+
assert_no_database_queries do
72+
assert_equal 'foobar', I18n.t(test_key, default: [fallback_key, 'foobar'])
73+
end
74+
end
5675
end

0 commit comments

Comments
 (0)