Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/plant/hash_pathify.rb

Overview

Monkey patch hash to provide pathify method

Instance Method Summary collapse

Instance Method Details

#pathify(sep = '/', paths = [], path = '') ⇒ Object

Returns a flat hash that show the full path to the value, so we don’t have to recursively traverse a nested hash Examples:

> ‘ff’.pathify

=> {foo: 'ff'}

> {bar: ‘gg’, boo: ‘hh’}.pathify

=> {'foo/bar': 'gg', 'foo/boo': 'hh'}

Optionally, Specify a seperator as first argument (defaults to ‘/’)



11
12
13
14
15
16
17
18
19
20
# File 'lib/plant/hash_pathify.rb', line 11

def pathify(sep = '/', paths = [], path = '')
  each do |key, value|
    if value.is_a? Hash
      value.pathify(sep, paths, "#{path}#{sep}#{key}")
    else
      paths << Hash["#{path}#{sep}#{key}".sub(/^#{sep}/, ''), value]
    end
  end
  paths.reduce({}, :merge)
end