Module: I18n::Tasks::SplitKey

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

Class Method Summary collapse

Class Method Details

.last_key_part(key) ⇒ Object



50
51
52
# File 'lib/i18n/tasks/split_key.rb', line 50

def last_key_part(key)
  split_key(key).last
end

.split_key(key, max = Float::INFINITY) ⇒ Object

split a key by dots (.) dots inside braces or parenthesis are not split on

split_key ‘a.b’ # => [‘a’, ‘b’] split_key ‘a.#bb.c’ # => [‘a’, ‘#bb.c’] split_key ‘a.b.c’, 2 # => [‘a’, ‘b.c’]



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
48
# File 'lib/i18n/tasks/split_key.rb', line 19

def split_key(key, max = Float::INFINITY)
  return [key] if max == 1

  parts = []
  current_parenthesis_end_char = nil
  part = ''
  key.each_char.with_index do |char, index|
    if current_parenthesis_end_char
      part += char
      current_parenthesis_end_char = nil if char == current_parenthesis_end_char
    elsif START_KEYS.include?(char)
      part += char
      current_parenthesis_end_char = END_KEYS[char]
    elsif char == '.'
      parts << part
      if parts.size + 1 == max
        remaining = key[(index + 1)..]
        parts << remaining unless remaining.empty?
        return parts
      end
      part = ''
    else
      part += char
    end
  end

  return parts if part.empty?

  current_parenthesis_end_char ? parts.concat(part.split('.')) : parts << part
end