Class: I18n::Backend::DotLookup

Inherits:
Simple
  • Object
show all
Defined in:
lib/i18n/backend/dot_lookup.rb

Constant Summary collapse

INTERPOLATION_PATTERN =
/%\{(\w+(?:\.\w+)+)\}/.freeze
UNKNOWN_PROPERTY =
Object.new
DOT =
"."

Instance Method Summary collapse

Instance Method Details

#extract_keys(subject) ⇒ Object



58
59
60
# File 'lib/i18n/backend/dot_lookup.rb', line 58

def extract_keys(subject)
  subject.scan(INTERPOLATION_PATTERN).flatten
end

#get_value(object, keys) ⇒ Object



62
63
64
65
66
67
68
69
70
# File 'lib/i18n/backend/dot_lookup.rb', line 62

def get_value(object, keys)
  keys.inject(object) do |target, key|
    unless target&.respond_to?(key)
      throw :unknown_property, UNKNOWN_PROPERTY
    end

    target.public_send(key)
  end
end

#populate_options(subject, options) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/i18n/backend/dot_lookup.rb', line 49

def populate_options(subject, options)
  extract_keys(subject).each_with_object(options) do |key, buffer|
    names = key.split(DOT)
    object = buffer[names.shift.to_sym]
    value = catch(:unknown_property) { get_value(object, names) }
    buffer[key.to_sym] = value if value != UNKNOWN_PROPERTY
  end
end

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

Raises:

  • (InvalidLocale)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/i18n/backend/dot_lookup.rb', line 18

def translate(locale, key, options = {})
  raise InvalidLocale, locale unless locale

  options = options.dup
  entry = key && lookup(locale, key, options[:scope], options)

  if options.empty?
    entry = resolve(locale, key, entry, options)
  else
    count, default = options.values_at(:count, :default)
    values = options.except(*RESERVED_KEYS)

    entry = if entry.nil? && default
              default(locale, key, default, options)
            else
              resolve(locale, key, entry, options)
            end
  end

  if entry.nil?
    throw(:exception, I18n::MissingTranslation.new(locale, key, options))
  end

  entry = entry.dup if entry.is_a?(String)

  populate_options(entry, values) if entry.is_a?(String)
  entry = pluralize(locale, entry, count) if count
  entry = interpolate(locale, entry, values) if values
  entry
end