class Icasework::LazyHash

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

Public Class Methods

new(hash, key = nil, &block) click to toggle source
Calls superclass method
# 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

Public Instance Methods

[](key) click to toggle source
# 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