Module: Buff::Extensions::Hash::DottedPaths

Included in:
Hash
Defined in:
lib/buff/extensions/hash/dotted_paths.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



5
6
7
# File 'lib/buff/extensions/hash/dotted_paths.rb', line 5

def included(base)
  base.send(:extend, ClassMethods)
end

Instance Method Details

#dig(path) ⇒ Object?

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

Examples:


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

nested_hash.dig('deep.nested.hash') => :seed_value

Parameters:

Returns:



87
88
89
90
91
92
93
94
95
96
97
# File 'lib/buff/extensions/hash/dotted_paths.rb', line 87

def dig(path)
  return nil unless path.present?

  parts = path.split('.', 2)
  match = self[parts[0].to_s].nil? ? self[parts[0].to_sym] : self[parts[0].to_s]
  if !parts[1] or match.nil?
    match
  else
    match.dig(parts[1])
  end
end

#dotted_paths(source = self, acc = Array.new, namespace = Array.new) ⇒ Array<String>

Returns an array of dotted paths from the keys, values of this Hash. Values which are nested Hashes will also recurred into and their paths will be added properly.

Parameters:

  • source (Hash) (defaults to: self)
  • acc (Array) (defaults to: Array.new)
  • namespace (Array) (defaults to: Array.new)

Returns:



107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/buff/extensions/hash/dotted_paths.rb', line 107

def dotted_paths(source = self, acc = Array.new, namespace = Array.new)
  if source.is_a?(Hash) && !source.empty?
    source.each do |key, value|
      branch = namespace.dup
      branch << key
      dotted_paths(value, acc, branch)
    end
  else
    acc << namespace.join('.')
  end

  acc
end