Module: Spider::HashDottedAccess

Included in:
MultiLevelHash
Defined in:
lib/spiderfw/utils/multi_level_hash.rb

Overview

Utility that makes the including Hash accept a dotted syntax for keys. The dotted syntax can be used to access and create on the fly sub-hashes. Example:

h = MultiLevelHash.new
h['one.two.three'] = 'some val'
p h => {'one' => {'two' => {'three' => 'some val'}}}
p h['one.two.three'] => 'some val'
p h['four.five'] => nil

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ Object



19
20
21
22
23
# File 'lib/spiderfw/utils/multi_level_hash.rb', line 19

def [](key)
    parts = key.to_s.split('.', 2)
    return super(key) unless parts[1]
    return self[parts[0]][parts[1]]
end

#[]=(key, val) ⇒ Object



12
13
14
15
16
17
# File 'lib/spiderfw/utils/multi_level_hash.rb', line 12

def []=(key, val)
    parts = key.to_s.split('.', 2)
    return super(key, val) unless parts[1]
    self[parts[0]] ||= self.class.new
    self[parts[0]][parts[1]] = val
end