Class: Accord::NestedKeyHash

Inherits:
Object
  • Object
show all
Defined in:
lib/accord/nested_key_hash.rb

Instance Method Summary collapse

Instance Method Details

#[](keys) ⇒ Object



3
4
5
6
7
8
9
10
11
# File 'lib/accord/nested_key_hash.rb', line 3

def [](keys)
  keys = keys.dup
  last_key = keys.pop
  last_hash = keys.inject(hash) do |partial, key|
    return nil unless partial.has_key?(key)
    partial[key]
  end
  last_hash[last_key]
end

#[]=(keys, value) ⇒ Object



13
14
15
16
17
18
# File 'lib/accord/nested_key_hash.rb', line 13

def []=(keys, value)
  keys = keys.dup
  last_key = keys.pop
  last_hash = keys.inject(hash) { |partial, key| partial[key] ||= {} }
  last_hash[last_key] = value
end

#delete(keys) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/accord/nested_key_hash.rb', line 20

def delete(keys)
  keys = keys.dup
  last_hash = {}
  result = nil
  while last_hash.size == 0 && keys.any?
    last_key = keys.pop
    last_hash = keys.inject(hash) { |partial, key| partial[key] || {} }
    partial_result = last_hash.delete(last_key)
    result ||= partial_result
  end
  result
end

#detect_expansion(keys) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/accord/nested_key_hash.rb', line 33

def detect_expansion(keys)
  keys.inject(hash) do |partial, part|
    expansion = yield(part)
    valid_key = expansion.detect { |key| partial.has_key?(key) }
    return unless valid_key
    partial[valid_key]
  end
end

#select_expansions(keys, partial = hash, results = [], &block) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/accord/nested_key_hash.rb', line 42

def select_expansions(keys, partial=hash, results=[], &block)
  if keys.size == 1
    expansion = block.call(keys.first)
    valid_expansions = expansion.select { |key| partial.has_key?(key) }
    valid_expansions.each { |key| results << partial[key] }
    return results
  end
  keys = keys.dup
  first_key = keys.shift
  expansion = block.call(first_key)
  valid_expansions = expansion.select { |key| partial.has_key?(key) }
  return results unless valid_expansions.any?
  valid_expansions.each do |key|
    select_expansions(keys, partial[key], results, &block)
  end
  results
end