Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/hash-graft.rb

Defined Under Namespace

Modules: Graft

Instance Method Summary collapse

Instance Method Details

#get_path(path, delimiter = ?/, data = self) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/hash-graft.rb', line 25

def get_path path, delimiter = ?/, data = self
  path = path.to_s.split(delimiter)if [String, Symbol].include? path.class
  return nil unless path.class == Array

  while key = path.shift
     if data.class == Hash and not data[key].nil?
       data = data[key]
       return data if path.length == 0

     elsif data.class == Hash and not data[key.to_sym].nil?
       data = data[key.to_sym]
       return data if path.length == 0

     elsif data.class == Array and key =~ /^\d*$/ and not data[key.to_i].nil?
       data = data[key.to_i]
       return data if path.length == 0

     elsif data.class == Array and key == ?*
       return data.map do |e|
         stuff = e.get_path Array.new path
       end
       return data if path.length == 0

     else
       return data[key]
     end
  end
end

#graft(a) ⇒ Object



4
5
6
7
# File 'lib/hash-graft.rb', line 4

def graft a
  copy = self.clone
  copy.graft! a
end

#graft!(a) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/hash-graft.rb', line 9

def graft! a
  a.each { |k,v|
    if self[k].class == Hash and a[k].class == Hash
      self[k].graft! a[k]

    elsif self[k].class == Array and a[k].class == Array
      self[k].graft! a[k]

    else
      self[k] = a[k]
    end
  } unless a.nil?

  return self
end

#set_path(path, value, delimiter = ?/, symbols = false) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/hash-graft.rb', line 54

def set_path path, value, delimiter = ?/, symbols = false
  data = self
  path = path[1..-1] if path.class == String and path[0] == delimiter
  path = path.to_s.split(delimiter) if [String, Symbol].include? path.class
  return nil unless path.class == Array
  while key = path.pop
    if key =~ /^\d*$/
      v = value
      value = []
      value[key.to_i] = v
    else
      key = key.to_sym if symbols
      value = {key => value}
    end
  end
  #puts "setting #{path} #{value}"
  data.graft! value
end