Class: Icasework::LazyHash

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/icasework/lazy_hash.rb

Overview

A hash which will attempt to lazy load a value from given block when the key is missing.

Instance Method Summary collapse

Constructor Details

#initialize(hash, key = nil, &block) ⇒ LazyHash

Returns a new instance of LazyHash.



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/icasework/lazy_hash.rb', line 11

def initialize(hash, key = nil, &block)
  @hash = hash
  @key = key
  @block = block

  @hash.default_proc = proc do |h, k|
    new_hash = @block.call
    new_hash = new_hash[@key] if @key
    h[k] = new_hash.fetch(k)
  end

  super(@hash)
end

Instance Method Details

#[](key) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/icasework/lazy_hash.rb', line 25

def [](key)
  value = @hash[key]
  case value
  when Hash
    LazyHash.new(value, key, &@block)
  else
    value
  end
end