Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/inspec/utils/hash.rb

Instance Method Summary collapse

Instance Method Details

#contains(contains) ⇒ Object

deep check if all values are contained



28
29
30
31
32
33
34
35
36
# File 'lib/inspec/utils/hash.rb', line 28

def contains(contains)
  hash = smash
  contains = contains.smash

  contains.each do |key, val|
    return false if hash[key] != val
  end
  true
end

#deep_merge(second) ⇒ Object



3
4
5
6
7
8
# File 'lib/inspec/utils/hash.rb', line 3

def deep_merge(second)
  merger = proc { |_key, v1, v2|
    v1.is_a?(Hash) && v2.is_a?(Hash) ? v1.merge(v2, &merger) : v2
  }
  merge(second, &merger)
end

#smash(prefix = nil) ⇒ Object

converts a deep hash into a flat hash hash =

'a' => 1,
'b' => {'c' => 2,

} hash.smash # => {“a”=>1, “b-c”=>2}



16
17
18
19
20
21
22
23
24
25
# File 'lib/inspec/utils/hash.rb', line 16

def smash(prefix = nil)
  inject({}) do |acc, (key, value)|
    index = prefix.to_s + key.to_s
    if value.is_a?(Hash)
      acc.merge(value.smash(index + "-"))
    else
      acc.merge(index => value)
    end
  end
end