Class: Object

Inherits:
BasicObject
Defined in:
lib/nested_hash_tricks/main.rb,
lib/nested_hash_tricks/main.rb

Instance Method Summary collapse

Instance Method Details

#dot_get(str) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/nested_hash_tricks/main.rb', line 2

def dot_get(str)
  str = str.split(".") if str.is_a?(String)
  res = self
  last_f = last_res = nil
  str.each do |f|
    if f.num? && !res.kind_of?(Array)
      last_res[last_f] = res = []
    end
    last_res = res
    if res.kind_of?(Array)
      temp = res[f.safe_to_i]
      if !temp
        res << {}
        temp = res.last
        raise "can only add new row at end" unless res.size-1 == f.safe_to_i
      end
      res = temp
    else
      res = res[f]
    end
    last_f = f
  end
  res
end

#dot_set(str, val = nil, &b) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/nested_hash_tricks/main.rb', line 26

def dot_set(str,val=nil,&b)
  mylog 'dot_set', :k => str, :v => val, :block_given => block_given?, :self => self    
  KeyParts.with_parts(str) do |first,lst,mult|
    return self[str] = val unless mult
    obj = dot_get(first)
    return obj unless obj
    obj.nested_set(lst,val,&b)
  end
end

#nested_set(k, v = nil, &b) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/nested_hash_tricks/main.rb', line 38

def nested_set(k,v=nil,&b)
  mylog 'dot_set', :context => 'nested_set', :k => k, :v => v, :block_given => block_given?, :self => self
  v = yield(self) if block_given?
  v = v.tmo if v.respond_to?(:tmo)
  self[k] = v
  self.delete(k) unless v.present?
  v
end