Class: Hash

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

Instance Method Summary collapse

Instance Method Details

#access(path) ⇒ Object Also known as: vine


14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/vine.rb', line 14

def access(path)
  value = self
  
  path.to_s.split('.').each do |p|
    if p.to_i.to_s == p
      value = value[p.to_i]
    else
      value = value[p].nil? ? value[p.to_sym] : value[p]
    end
    break if value.nil?
  end
  
  value
end

#set(path, value) ⇒ Object


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/vine.rb', line 29

def set(path, value)
  keys = []
  path = path.to_s.split('.')

  [*path, nil].each_cons(2) do |key,nextkey|
    tmp_hash = keys.inject(self, :fetch)

    if key.to_i.to_s == key
      key = key.to_i
    elsif tmp_hash[key].nil?
      key = key.to_sym
    end

    if tmp_hash[key].nil?
      tmp_hash[key] = {}
    elsif nextkey.to_i.to_s == nextkey && !tmp_hash[key].is_a?(Array)
      tmp_hash[key] = []
    elsif !nextkey.nil? && !tmp_hash[key].is_a?(Hash)
      tmp_hash[key] = {}
    end

    keys << key
  end # each_cons

  last_key = keys.pop
  keys.inject(self, :fetch)[last_key] = value
end