Class: Needle::Lifecycle::Singleton

Inherits:
Pipeline::Element show all
Defined in:
lib/needle/lifecycle/singleton.rb

Overview

The instantiation pipeline element that enforces the singleton multiplicity.

Instance Attribute Summary

Attributes inherited from Pipeline::Element

#name, #options, #priority, #service_point, #succ

Instance Method Summary collapse

Methods inherited from Pipeline::Element

#<=>, #initialize, set_default_priority

Constructor Details

This class inherits a constructor from Needle::Pipeline::Element

Instance Method Details

#call(container, point) ⇒ Object

Returns the cached reference, if it has been previously cached. Otherwise, invokes the next element in the pipeline and caches the result. The cached reference is returned.



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/needle/lifecycle/singleton.rb', line 38

def call( container, point )
  unless @is_cached
    @mutex.synchronize do
      unless @is_cached
        @cached = succ.call( container, point )
        @is_cached = true
      end
    end
  end

  @cached
end

#initialize_elementObject

Creates the mutex to use and sets the cached reference to nil.



29
30
31
32
33
# File 'lib/needle/lifecycle/singleton.rb', line 29

def initialize_element
  @mutex = QueryableMutex.new
  @cached = nil
  @is_cached = false
end

#reset!Object

Resets the cached singleton instance, so that the next time it is requested it is re-constructed.



53
54
55
56
57
58
# File 'lib/needle/lifecycle/singleton.rb', line 53

def reset!
  @mutex.synchronize do
    @cached = nil
    @is_cached = false
  end
end