Module: I18n::Tasks::PluralKeys

Included in:
BaseTask, Data::Tree::Siblings
Defined in:
lib/i18n/tasks/plural_keys.rb

Constant Summary collapse

CLDR_CATEGORY_KEYS =
%w[zero one two few many other].freeze
PLURAL_KEY_SUFFIXES =
Set.new CLDR_CATEGORY_KEYS
PLURAL_KEY_RE =
/\.(?:#{CLDR_CATEGORY_KEYS * "|"})$/
EXPLICIT_0_1 =
%w[0 1].freeze

Instance Method Summary collapse

Instance Method Details

#collapse_plural_nodes!(tree) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/i18n/tasks/plural_keys.rb', line 12

def collapse_plural_nodes!(tree)
  tree.leaves.map(&:parent).compact.uniq.each do |node|
    children = node.children
    next unless plural_forms?(children)

    node.value = children.to_hash
    node.children = nil
    node.data.merge! children.first.data
  end
  tree
end

#depluralize_key(key, locale = base_locale) ⇒ String

Returns the base form if the key is a specific plural form (e.g. apple for apple.many), the key otherwise.

Parameters:

  • key (String)

    i18n key

  • locale (String) (defaults to: base_locale)

    to pull key data from

Returns:

  • (String)

    the base form if the key is a specific plural form (e.g. apple for apple.many), the key otherwise.



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/i18n/tasks/plural_keys.rb', line 27

def depluralize_key(key, locale = base_locale)
  return key if key !~ PLURAL_KEY_RE

  key_name = last_key_part(key)
  parent_key = key[0..- (key_name.length + 2)]
  nodes = tree("#{locale}.#{parent_key}").presence || (locale != base_locale && tree("#{base_locale}.#{parent_key}"))
  if nodes && plural_forms?(nodes)
    parent_key
  else
    key
  end
end

#plural_forms?(s) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/i18n/tasks/plural_keys.rb', line 56

def plural_forms?(s)
  s.present? && s.all? { |node| node.leaf? && plural_suffix?(node.key) }
end

#plural_nodes(tree) {|node| ... } ⇒ Object

Parameters:

Yield Parameters:



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/i18n/tasks/plural_keys.rb', line 42

def plural_nodes(tree)
  return to_enum(:plural_nodes, tree) unless block_given?

  visited = Set.new
  tree.leaves do |node|
    parent = node.parent
    next if !parent || visited.include?(parent)

    yield parent if plural_forms?(parent.children)
    visited.add(parent)
  end
  self
end

#plural_suffix?(key) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/i18n/tasks/plural_keys.rb', line 60

def plural_suffix?(key)
  PLURAL_KEY_SUFFIXES.include?(key) || EXPLICIT_0_1.include?(key)
end