Class: Lit::I18nBackend

Inherits:
Object
  • Object
show all
Includes:
I18n::Backend::Pluralization, I18n::Backend::Simple::Implementation
Defined in:
lib/lit/i18n_backend.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache) ⇒ I18nBackend

Returns a new instance of I18nBackend.



11
12
13
14
15
16
17
18
# File 'lib/lit/i18n_backend.rb', line 11

def initialize(cache)
  @cache = cache
  @available_locales_cache = nil
  @translations = {}
  reserved_keys = I18n.const_get(:RESERVED_KEYS) + %i[lit_default_copy]
  I18n.send(:remove_const, :RESERVED_KEYS)
  I18n.const_set(:RESERVED_KEYS, reserved_keys.freeze)
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



9
10
11
# File 'lib/lit/i18n_backend.rb', line 9

def cache
  @cache
end

Instance Method Details

#available_localesObject



43
44
45
46
47
48
49
50
51
52
# File 'lib/lit/i18n_backend.rb', line 43

def available_locales
  return @available_locales_cache unless @available_locales_cache.nil?
  @locales ||= ::Rails.configuration.i18n.available_locales
  if @locales && !@locales.empty?
    @available_locales_cache = @locales.map(&:to_sym)
  else
    @available_locales_cache = Lit::Locale.ordered.visible.map { |l| l.locale.to_sym }
  end
  @available_locales_cache
end

#reset_available_locales_cacheObject



54
55
56
# File 'lib/lit/i18n_backend.rb', line 54

def reset_available_locales_cache
  @available_locales_cache = nil
end

#store_translations(locale, data, options = {}) ⇒ Object

Stores the given translations.

Parameters:

  • locale (String)

    the locale (ie “en”) to store translations for

  • data (Hash)

    nested key-value pairs to be added as blurbs



62
63
64
65
66
67
# File 'lib/lit/i18n_backend.rb', line 62

def store_translations(locale, data, options = {})
  super
  ActiveRecord::Base.transaction do
    store_item(locale, data)
  end if store_items? && valid_locale?(locale)
end

#translate(locale, key, options = {}) ⇒ Object

DOC Translation flow starts with Rails-provided ActionView::Helpers::TranslationHelper ‘translate` method In that method any calls to `I18n.translate` are catched by this method below (because Lit acts as I18 backend) Any calls in Lit to `super` go straight to I18n



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/lit/i18n_backend.rb', line 24

def translate(locale, key, options = {})
  options[:lit_default_copy] = options[:default].dup if can_dup_default(options)
  content = super(locale, key, options)

  if on_rails_6_1_or_higher?
    @untranslated_key = key if key.present? && options[:default].instance_of?(Object)

    if key.nil? && options[:lit_default_copy].present?
      update_default_localization(locale, options)
    end
  end

  if Lit.all_translations_are_html_safe && content.respond_to?(:html_safe)
    content.html_safe
  else
    content
  end
end