Module: Multiton

Included in:
Infinity
Defined in:
lib/carat/multiton.rb

Defined Under Namespace

Modules: New, Semi

Constant Summary collapse

VERSION =
"2.0"
POOLS =

pools of objects cached on class type

{}
MULTITON_ID_HOOK =

method which can be defined by a class to determine object uniqueness

:multiton_id
MULTITON_NEW_HOOK =

method which can be defined by a class to create multiton objects

:multiton_new

Class Method Summary collapse

Class Method Details

.append_features(klass) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/carat/multiton.rb', line 85

def self.append_features(klass)
  klass.private_class_method(:new)
  def klass.instance(*args, &block)
    # if the class defined 'multiton_id' we use this as the key
    # otherwise we simply use the argument list.
    k = (respond_to?(MULTITON_ID_HOOK) ? send(MULTITON_ID_HOOK, *args, &block) : args)
    unless (obj = (POOLS[self] ||= {})[k])
      begin
        critical = Thread.critical
        Thread.critical = true
        meth = self.respond_to?(MULTITON_NEW_HOOK) ? MULTITON_NEW_HOOK : :new
        obj = (POOLS[self][k] = self.send(meth, *args, &block))
      ensure
        Thread.critical = critical # restore state
      end
    end
    return obj
  end
end