Sha256: c21c29a01a1143d282e28777195ffe6f15ad61f2a161aceec307e4dce917ecfb

Contents?: true

Size: 906 Bytes

Versions: 1

Compression:

Stored size: 906 Bytes

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.2'
  end

  def initialize(&callable)
    @__callable__ = callable
  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.2 lib/lazy_object.rb