Module: Chef::Validation::HashExt

Defined in:
lib/chef/validation/ext/hash.rb

Class Method Summary collapse

Class Method Details

.dig(hash, path, separator = "/") ⇒ Object?

Return the value of the nested hash key from the given dotted path

Examples:


nested_hash = {
  "deep" => {
    "nested" => {
      "hash" => :my_value
    }
  }
}

HashExt.dig(hash, "deep/nested/hash") => :my_value


23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/chef/validation/ext/hash.rb', line 23

def dig(hash, path, separator = "/")
  return nil unless !path.nil? && !path.empty?
  return nil unless hash.respond_to?(:has_key?)
  return hash unless hash.respond_to?(:[])

  key, rest = path.split(separator, 2)
  match     = hash[key.to_s].nil? ? hash[key.to_sym] : hash[key.to_s]
  if rest.nil? or match.nil?
    match
  else
    dig(match, rest, separator)
  end
end