Class: I18n::PostgresJson::Translation

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/i18n/postgres_json/translation.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.available_localesObject



6
7
8
9
10
# File 'lib/i18n/postgres_json/translation.rb', line 6

def self.available_locales
  (
    distinct.order(locale: :asc).pluck(:locale) + [I18n.default_locale]
  ).map(&:to_sym).uniq
end

.locale(locale) ⇒ Object



20
21
22
# File 'lib/i18n/postgres_json/translation.rb', line 20

def self.locale(locale)
  find_or_initialize_by(locale: locale)
end

.store_translations(locale, data) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/i18n/postgres_json/translation.rb', line 12

def self.store_translations(locale, data)
  record = self.locale(locale)

  record.translations.deep_merge!(data.deep_stringify_keys)

  record.save!
end

Instance Method Details

#dig(*keys) ⇒ Object



24
25
26
27
28
# File 'lib/i18n/postgres_json/translation.rb', line 24

def dig(*keys)
  keys = Array(keys)

  translations.with_indifferent_access.dig(*keys)
end

#lookup(key, scope = [], separator:) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/i18n/postgres_json/translation.rb', line 30

def lookup(key, scope = [], separator:)
  _, *keys = I18n.normalize_keys(locale, key, scope, separator)

  translated = keys.each_with_index.reduce(nil) { |translation, (_, index)|
    if translation.present?
      translation
    else
      leading = keys.take(index)
      trailing = keys.drop(index)

      dig(*([leading.join(separator)] + keys - leading)) ||
        dig(*(keys - trailing + [trailing.join(separator)]))
    end
  }

  if translated.respond_to?(:deep_symbolize_keys)
    translated.deep_symbolize_keys
  else
    translated
  end
end