Module: HashExtensions::InstanceMethods

Defined in:
lib/eventhub/hash_extensions.rb

Instance Method Summary collapse

Instance Method Details

#all_keys_with_path(parent = nil) ⇒ Object

get all keys path, { ‘a’ => ‘value1’, ‘b’ => { ‘c’ => ‘value2’}}.all_keys_with_path => [‘a’,‘b.c’]



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/eventhub/hash_extensions.rb', line 28

def all_keys_with_path(parent=nil)
  a = []
  each do |k,v|
    if v.is_a?(Hash)
      a << v.all_keys_with_path([parent,k].compact.join('.'))
    else
      a << "#{[parent,k].compact.join(".")}"
    end
  end
  a.flatten
end

#get(arg) ⇒ Object

“a” => { “b” => { “c” => { “value”}}}



9
10
11
12
13
14
# File 'lib/eventhub/hash_extensions.rb', line 9

def get(arg)
  path = arg.is_a?(String) ? arg.split('.') : arg
  path.inject(self,:[])
rescue NoMethodError 
  return nil
end

#set(arg, value, overwrite = true) ⇒ Object

set value from provided key path, e.h. hash.set(‘a.b.c’,‘new value’) if overwrite is false, value will be set if it was nil previously



18
19
20
21
22
23
24
25
# File 'lib/eventhub/hash_extensions.rb', line 18

def set(arg,value,overwrite=true)
  *key_path, last = arg.is_a?(String) ? arg.split(".") : arg
  if overwrite
    key_path.inject(self) { |h,key| h.has_key?(key) ? h[key] :  h[key]={}} [last] = value 
  else
    key_path.inject(self) { |h,key| h.has_key?(key) ? h[key] :  h[key]={}} [last] ||= value
  end  
end