Path: | lib/singleton.rb |
Last Update: | Tue Jan 17 18:02:18 +0000 2012 |
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 156 156: def __init__(klass) 157: klass.instance_eval { @__instance__ = nil } 158: class << klass 159: define_method(:instance,FirstInstanceCall) 160: end 161: klass 162: end
# File lib/singleton.rb, line 168 168: def append_features(mod) 169: # help out people counting on transitive mixins 170: unless mod.instance_of?(Class) 171: raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}" 172: end 173: super 174: end