| Path: | lib/singleton.rb |
| Last Update: | Sat Sep 22 12:31:31 +0000 2007 |
The Singleton module implements the Singleton pattern.
Usage:
class Klass
include Singleton
# ...
end
a,b = Klass.instance, Klass.instance a == b # => true a.new # NoMethodError - new is private …
class OtherKlass
include Singleton
# ...
end
ObjectSpace.each_object(OtherKlass){} # => 0.
This is achieved by marking
Providing (or modifying) the class methods
def Klass.instance()
return @__instance__
end
The instance method of Singleton are
# File lib/singleton.rb, line 157
157: def __init__(klass)
158: klass.instance_eval { @__instance__ = nil }
159: class << klass
160: define_method(:instance,FirstInstanceCall)
161: end
162: klass
163: end
# File lib/singleton.rb, line 169
169: def append_features(mod)
170: # help out people counting on transitive mixins
171: unless mod.instance_of?(Class)
172: raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}"
173: end
174: super
175: end