Skip to content

Commit

Permalink
Add #translations, #init_translations and #intialized? (#97)
Browse files Browse the repository at this point in the history
For compatibility with i18n-js, these methods are required to
build a complete representation of all translations in the
backend.
  • Loading branch information
vipera authored Feb 27, 2020
1 parent 1740246 commit 752ad19
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/i18n/backend/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,24 @@ def store_translations(locale, data, options = {})
end
end

def reload!
@translations = nil
self
end

def initialized?
!@translations.nil?
end

def init_translations
@translations = Translation.to_hash
end

def translations(do_init: false)
init_translations if do_init || !initialized?
@translations ||= {}
end

protected

def lookup(locale, key, scope = [], options = {})
Expand Down
12 changes: 12 additions & 0 deletions lib/i18n/backend/active_record/translation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ def lookup(keys, *separator)
def available_locales
Translation.select('DISTINCT locale').to_a.map { |t| t.locale.to_sym }
end

def to_hash
Translation.all.each.with_object({}) do |t, memo|
locale_hash = (memo[t.locale.to_sym] ||= {})
keys = t.key.split('.')
keys.each.with_index.inject(locale_hash) do |iterator, (key_part, index)|
key = key_part.to_sym
iterator[key] = keys[index + 1] ? (iterator[key] || {}) : t.value
iterator[key]
end
end
end
end

def interpolates?(key)
Expand Down
24 changes: 24 additions & 0 deletions test/active_record_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,28 @@ def teardown

assert_equal "translation missing: en.no key", I18n.t('.')
end

test "intially unitinitialized" do
refute I18n.backend.initialized?
I18n.backend.init_translations
assert I18n.backend.initialized?
I18n.backend.reload!
refute I18n.backend.initialized?
I18n.backend.init_translations
assert I18n.backend.initialized?
end

test "translations returns all translations" do
expected_hash = { :en => { :foo => { :bar => 'bar', :baz => 'baz' } } }
I18n.backend.init_translations
assert_equal expected_hash, I18n.backend.send(:translations)
assert I18n.backend.initialized?
end

test "translations initialized with do_init argument" do
expected_hash = { :en => { :foo => { :bar => 'bar', :baz => 'baz' } } }
refute I18n.backend.initialized?
assert_equal expected_hash, I18n.backend.send(:translations, { do_init: true })
assert I18n.backend.initialized?
end
end

0 comments on commit 752ad19

Please sign in to comment.