Module: Multiton::New

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

Overview

A new-multiton uses the #new method rather than the #instance method.

Class Method Summary collapse

Class Method Details

.append_features(klass) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/carat/multiton.rb', line 107

def self.append_features(klass)
  def klass.new(*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
        if self.respond_to?(MULTITON_NEW_HOOK)
          obj = (POOLS[self][k] = self.send(MULTITON_NEW_HOOK, *args, &block))
        else
          obj = super
        end
      ensure
        Thread.critical = critical # restore state
      end
    end
    return obj
  end
end