Class: TfgSupport::DeepHashAccessor

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

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ DeepHashAccessor

Returns a new instance of DeepHashAccessor.



4
5
6
# File 'lib/tfg_support/deep_hash_accessor.rb', line 4

def initialize(hash)
  @hash = hash
end

Instance Method Details

#[](*keys) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/tfg_support/deep_hash_accessor.rb', line 8

def [](*keys)
  target = @hash

  keys.each do |key|
    return nil unless target.respond_to?(:[])
    target = target[key]
  end
  target
end

#[]=(*keys) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/tfg_support/deep_hash_accessor.rb', line 18

def []=(*keys)
  value = keys.pop()
  set_key = keys.pop()

  target = @hash
  keys.each do |key|
    hash = target[key]
    if hash.nil?
      hash = {}
      target[key] = hash
    end
    target = hash
  end

  target[set_key] = value
end