Module: I18nInterpolationSpec::Checker

Defined in:
lib/i18n_interpolation_spec/checker.rb

Class Method Summary collapse

Class Method Details

.check(t1, t2, except, &checker) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/i18n_interpolation_spec/checker.rb', line 9

def check(t1, t2, except, &checker)
  i1, i2 = interpolations(t1), interpolations(t2)

  missing_keys = {}

  (i1.keys & i2.keys).each do |key|
    a1, a2 = i1[key], i2[key]
    diff = (a1 - a2) | (a2 - a1)
    next if except? except, key
    missing_keys[key] = diff if checker[key, a1, a2, diff]
  end

  missing_keys
end

.except?(patterns, key) ⇒ Boolean

Returns:

  • (Boolean)


5
6
7
# File 'lib/i18n_interpolation_spec/checker.rb', line 5

def except?(patterns, key)
  patterns.any? { |pattern|  pattern === key }
end

.extract_args(translation) ⇒ Object



59
60
61
# File 'lib/i18n_interpolation_spec/checker.rb', line 59

def extract_args(translation)
  translation.to_s.scan(/(?<!%)%\{([^\}]+)\}/).flatten
end

.interpolations(t) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/i18n_interpolation_spec/checker.rb', line 36

def interpolations(t)
  result = {}

  rec = ->(t, scopes) do
    if t.is_a? Hash
      t.each do |(k, v)|
        rec.call v, [*scopes, k]
      end
    elsif t.is_a? Array
      t.each_with_index do |v, i|
        rec.call v, [*scopes, i]
      end
    else
      args = extract_args t
      result[scopes.join('.')] = args
    end
  end

  rec.call t, []

  result
end

.loose_check(t1, t2, except: []) ⇒ Object



30
31
32
33
34
# File 'lib/i18n_interpolation_spec/checker.rb', line 30

def loose_check(t1, t2, except: [])
  check t1, t2, except do |key, a1, a2, diff|
    a1.any? && a2.any? && (diff == a1 | a2)
  end
end

.strict_check(t1, t2, except: []) ⇒ Object



24
25
26
27
28
# File 'lib/i18n_interpolation_spec/checker.rb', line 24

def strict_check(t1, t2, except: [])
  check t1, t2, except do |key, a1, a2, diff|
    diff.any?
  end
end