The Singleton module implements
the Singleton pattern.
Usage:
class Klass
include Singleton
# ...
end
- this ensures that only one instance of Klass lets call it ``the
instance’’ can be created.
a,b = Klass.instance, Klass.instance a == b # => true a.new # NoMethodError - new is private
…
- ``The instance’’ is created at instantiation time, in other
words the first call of Klass.instance(), thus
class OtherKlass
include Singleton
# ...
end
ObjectSpace.each_object(OtherKlass){} # => 0.
- This behavior is preserved under inheritance and cloning.
This is achieved by marking
- Klass.new and Klass.allocate - as private
Providing (or modifying) the class methods
The instance method of Singleton
are
- clone and dup - raising TypeErrors to prevent cloning or duping
- _dump(depth) - returning the empty string. Marshalling strips by default
all state information, e.g. instance variables and taint state, from ``the
instance’’. Providing custom _load(str) and _dump(depth) hooks
allows the (partially) resurrections of a previous state of ``the
instance’’.