class Defer
Defers the initialization of an instance until a method is called.
Standard Usage:
Initialization:
instance = Defer.defer
{
instance.new instance.do_something
}
Runtime:
instance.do_another_thing # starts the initialization here, not above
Public Class Methods
defer(&block)
click to toggle source
Initializes defer on a block of code
# File lib/defer/defer.rb, line 18 def self.defer(&block) Defer.new(&block) end
new(&block)
click to toggle source
# File lib/defer/defer.rb, line 22 def initialize(&block) @deferred_init = block @semaphore = Mutex.new end
Public Instance Methods
get_instance()
click to toggle source
Gets an instance of the object, calling the deferred method if needed
# File lib/defer/defer.rb, line 28 def get_instance @semaphore.synchronize do if @object.nil? @object = @deferred_init.call else @object end end end
method_missing(method, *args, &block)
click to toggle source
After initialization is done, defer passes the arguments through
this block to ensure that everything is completed as required
# File lib/defer/defer.rb, line 40 def method_missing(method, *args, &block) object = get_instance object.send(method, *args, &block); end