Class: Needle::Lifecycle::Proxy

Inherits:
Object
  • Object
show all
Defined in:
lib/needle/lifecycle/proxy.rb

Overview

A proxy class to aid in deferred instantiation of service points. This is used primarily by the “deferred” service models.

Instance Method Summary collapse

Constructor Details

#initialize(proc_obj = nil, *args, &callback) ⇒ Proxy

Create a new proxy object that wraps the object returned by either the proc_obj or callback. (Only one of proc_obj or callback should be specified.)



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/needle/lifecycle/proxy.rb', line 29

def initialize( proc_obj=nil, *args, &callback )
  if proc_obj && callback
    raise ArgumentError, "only specify argument OR block, not both"
  end

  @callback = proc_obj || callback or
    raise ArgumentError, "callback required"

  @args = args
  @mutex = QueryableMutex.new
  @instantiation_failed = false
  @instance = nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

Attempts to invoke the given message on the service. If the service has not yet been instantiated, it will be instantiated and stored.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/needle/lifecycle/proxy.rb', line 45

def method_missing( sym, *args, &block )
  unless @instance || @instantiation_failed
    @mutex.synchronize do
      unless @instance || @instantiation_failed
        begin
          @instance = @callback.call( *@args )
        rescue Exception
          @instantiation_failed = true
          raise
        end
      end
    end
  end

  unless @instantiation_failed
    @instance.__send__ sym, *args, &block
  else
    # just return nil... this way, a failed instantiation won't barf
    # more than once... I hope...
  end
end

Instance Method Details

#inspectObject



84
85
86
87
# File 'lib/needle/lifecycle/proxy.rb', line 84

def inspect
  "#<#{self.class.name}:#{"0x%08x"%self.object_id}:" +
  "instantiated=>#{@instance ? true : false}>"
end