Skip to content

Commit 752ad19

Browse files
authored
Add #translations, #init_translations and #intialized? (svenfuchs#97)
For compatibility with i18n-js, these methods are required to build a complete representation of all translations in the backend.
1 parent 1740246 commit 752ad19

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

lib/i18n/backend/active_record.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,24 @@ def store_translations(locale, data, options = {})
4545
end
4646
end
4747

48+
def reload!
49+
@translations = nil
50+
self
51+
end
52+
53+
def initialized?
54+
!@translations.nil?
55+
end
56+
57+
def init_translations
58+
@translations = Translation.to_hash
59+
end
60+
61+
def translations(do_init: false)
62+
init_translations if do_init || !initialized?
63+
@translations ||= {}
64+
end
65+
4866
protected
4967

5068
def lookup(locale, key, scope = [], options = {})

lib/i18n/backend/active_record/translation.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,18 @@ def lookup(keys, *separator)
7575
def available_locales
7676
Translation.select('DISTINCT locale').to_a.map { |t| t.locale.to_sym }
7777
end
78+
79+
def to_hash
80+
Translation.all.each.with_object({}) do |t, memo|
81+
locale_hash = (memo[t.locale.to_sym] ||= {})
82+
keys = t.key.split('.')
83+
keys.each.with_index.inject(locale_hash) do |iterator, (key_part, index)|
84+
key = key_part.to_sym
85+
iterator[key] = keys[index + 1] ? (iterator[key] || {}) : t.value
86+
iterator[key]
87+
end
88+
end
89+
end
7890
end
7991

8092
def interpolates?(key)

test/active_record_test.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,4 +109,28 @@ def teardown
109109

110110
assert_equal "translation missing: en.no key", I18n.t('.')
111111
end
112+
113+
test "intially unitinitialized" do
114+
refute I18n.backend.initialized?
115+
I18n.backend.init_translations
116+
assert I18n.backend.initialized?
117+
I18n.backend.reload!
118+
refute I18n.backend.initialized?
119+
I18n.backend.init_translations
120+
assert I18n.backend.initialized?
121+
end
122+
123+
test "translations returns all translations" do
124+
expected_hash = { :en => { :foo => { :bar => 'bar', :baz => 'baz' } } }
125+
I18n.backend.init_translations
126+
assert_equal expected_hash, I18n.backend.send(:translations)
127+
assert I18n.backend.initialized?
128+
end
129+
130+
test "translations initialized with do_init argument" do
131+
expected_hash = { :en => { :foo => { :bar => 'bar', :baz => 'baz' } } }
132+
refute I18n.backend.initialized?
133+
assert_equal expected_hash, I18n.backend.send(:translations, { do_init: true })
134+
assert I18n.backend.initialized?
135+
end
112136
end

0 commit comments

Comments
 (0)