Sha256: b3804d4130fa7d654666b07efbce5dc7a6dfe35b65d6e9ee409e8e4cd1b6acaf

Contents?: true

Size: 1.02 KB

Versions: 1

Compression:

Stored size: 1.02 KB

Contents

# Lazy object wrapper.
#
# Pass a block to the initializer, which returns an instance of the target
# object. Lazy object forwards all method calls to the target. The block only
# gets called the first time a method is forwarded.
#
# Example:
#
# lazy = LazyObject.new { VeryExpensiveObject.new } # At this point the VeryExpensiveObject hasn't been initialized yet.
# lazy.get_expensive_results(foo, bar) # Initializes VeryExpensiveObject and calls 'get_expensive_results' on it, passing in foo and bar
class LazyObject < BasicObject
  def self.version
    '0.0.3'
  end

  def initialize(&callable)
    @__callable__ = callable
  end

  def ==(item)
    __target_object__ == item
  end

  def !=(item)
    __target_object__ != item
  end

  def !
    !__target_object__
  end

  # Cached target object.
  def __target_object__
    @__target_object__ ||= @__callable__.call
  end

  # Forwards all method calls to the target object.
  def method_missing(method_name, *args, &block)
    __target_object__.send(method_name, *args, &block)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lazy_object-0.0.3 lib/lazy_object.rb