module Singleton
def clone
raise TypeError, "can't clone instance of singleton #{self.class}"
end
def dup
raise TypeError, "can't dup instance of singleton #{self.class}"
end
def _dump(depth=-1)
''
end
end
class << Singleton
FirstInstanceCall = proc do
Thread.critical = true
if @__instance__.nil?
@__instance__ = false
Thread.critical = false
begin
@__instance__ = new
ensure
if @__instance__
class <<self
remove_method :instance
def instance; @__instance__ end
end
else
@__instance__ = nil end
end
elsif _instantiate?()
Thread.critical = false
else
@__instance__ = false
Thread.critical = false
begin
@__instance__ = new
ensure
if @__instance__
class <<self
remove_method :instance
def instance; @__instance__ end
end
else
@__instance__ = nil
end
end
end
@__instance__
end
module SingletonClassMethods
def clone
Singleton.__init__(super)
end
def _load(str)
instance
end
private
def inherited(sub_klass)
super
Singleton.__init__(sub_klass)
end
def _instantiate?()
while false.equal?(@__instance__)
Thread.critical = false
sleep(0.08) Thread.critical = true
end
@__instance__
end
end
def __init__(klass)
klass.instance_eval { @__instance__ = nil }
class << klass
define_method(:instance,FirstInstanceCall)
end
klass
end
private
undef_method :extend_object
def append_features(mod)
unless mod.instance_of?(Class)
raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}"
end
super
end
def included(klass)
super
klass.private_class_method :new, :allocate
klass.extend SingletonClassMethods
Singleton.__init__(klass)
end
end
if __FILE__ == $0
def num_of_instances(klass)
"#{ObjectSpace.each_object(klass){}} #{klass} instance(s)"
end
class SomeSingletonClass
include Singleton
end
puts "There are #{num_of_instances(SomeSingletonClass)}"
a = SomeSingletonClass.instance
b = SomeSingletonClass.instance puts "basic test is #{a == b}"
begin
SomeSingletonClass.new
rescue NoMethodError => mes
puts mes
end
puts "\nThreaded example with exception and customized #_instantiate?() hook"; p
Thread.abort_on_exception = false
class Ups < SomeSingletonClass
def initialize
self.class.__sleep
puts "initialize called by thread ##{Thread.current[:i]}"
end
end
class << Ups
def _instantiate?
@enter.push Thread.current[:i]
while false.equal?(@__instance__)
Thread.critical = false
sleep 0.08
Thread.critical = true
end
@leave.push Thread.current[:i]
@__instance__
end
def __sleep
sleep(rand(0.08))
end
def new
begin
__sleep
raise "boom - thread ##{Thread.current[:i]} failed to create instance"
ensure
class << self
remove_method :new
end
end
end
def instantiate_all
@enter = []
@leave = []
1.upto(9) {|i|
Thread.new {
begin
Thread.current[:i] = i
__sleep
instance
rescue RuntimeError => mes
puts mes
end
}
}
puts "Before there were #{num_of_instances(self)}"
sleep 3
puts "Now there is #{num_of_instances(self)}"
puts "#{@enter.join '; '} was the order of threads entering the waiting loop"
puts "#{@leave.join '; '} was the order of threads leaving the waiting loop"
end
end
Ups.instantiate_all
puts "\nLets see if class level cloning really works"
Yup = Ups.clone
def Yup.new
begin
__sleep
raise "boom - thread ##{Thread.current[:i]} failed to create instance"
ensure
class << self
remove_method :new
end
end
end
Yup.instantiate_all
puts "\n\n","Customized marshalling"
class A
include Singleton
attr_accessor :persist, :die
def _dump(depth)
Marshal.dump(@persist,depth)
end
end
def A._load(str)
instance.persist = Marshal.load(str)
instance
end
a = A.instance
a.persist = ["persist"]
a.die = "die"
a.taint
stored_state = Marshal.dump(a)
a.persist = nil
a.die = nil
b = Marshal.load(stored_state)
p a == b p a.persist p a.die
puts "\n\nSingleton with overridden default #inherited() hook"
class Up
end
def Up.inherited(sub_klass)
puts "#{sub_klass} subclasses #{self}"
end
class Middle < Up
include Singleton
end
class Down < Middle; end
puts "and basic \"Down test\" is #{Down.instance == Down.instance}\n
Various exceptions"
begin
module AModule
include Singleton
end
rescue TypeError => mes
puts mes end
begin
'aString'.extend Singleton
rescue NoMethodError => mes
puts mes end
end