Class: LazyObject

Inherits:
BasicObject
Defined in:
lib/lazy_object.rb

Overview

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 Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&callable) ⇒ LazyObject

Returns a new instance of LazyObject.



16
17
18
# File 'lib/lazy_object.rb', line 16

def initialize(&callable)
  @__callable__ = callable
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object

Forwards all method calls to the target object.



38
39
40
# File 'lib/lazy_object.rb', line 38

def method_missing(method_name, *args, &block)
  __target_object__.send(method_name, *args, &block)
end

Class Method Details

.versionObject



12
13
14
# File 'lib/lazy_object.rb', line 12

def self.version
  '0.0.3'
end

Instance Method Details

#!Object



28
29
30
# File 'lib/lazy_object.rb', line 28

def !
  !__target_object__
end

#!=(item) ⇒ Object



24
25
26
# File 'lib/lazy_object.rb', line 24

def !=(item)
  __target_object__ != item
end

#==(item) ⇒ Object



20
21
22
# File 'lib/lazy_object.rb', line 20

def ==(item)
  __target_object__ == item
end

#__target_object__Object

Cached target object.



33
34
35
# File 'lib/lazy_object.rb', line 33

def __target_object__
  @__target_object__ ||= @__callable__.call
end