Hello all.
Noticed this behavior:
require ‘singleton’
=> trueclass A; include Singleton; end
=> AA.instance
=> #<A:0x3703c38>class A; include Singleton; end
=> AA.instance
=> #<A:0x36d7a60>
A second singleton?
Cheers!
-r
Hello all.
Noticed this behavior:
require ‘singleton’
=> trueclass A; include Singleton; end
=> AA.instance
=> #<A:0x3703c38>class A; include Singleton; end
=> AA.instance
=> #<A:0x36d7a60>
A second singleton?
Cheers!
-r
From singleton.rb:
def included(klass)
super
klass.private_class_method :new, :allocate
klass.extend SingletonClassMethods
Singleton.init(klass)
end
and a bit earlier:
def init(klass)
klass.instance_eval { @instance = nil }
…
Perhaps that should be instead:
klass.instance_eval { @__instance__ = nil unless defined?
@instance }
Or somewhat more obscure, I think this would do:
klass.instance_eval { @__instance__ ||= nil }
Roger P. wrote in post #986564:
Hello all.
Noticed this behavior:
require ‘singleton’
=> trueclass A; include Singleton; end
=> AA.instance
=> #<A:0x3703c38>
I looked through the ruby docs and neither BasicObject, Object, Kernel,
Module, Class, nor Singelton have a method named ‘instance’. Where does
that come from?
On Mar 9, 2011, at 14:34 , 7stud – wrote:
=> #<A:0x3703c38>
I looked through the ruby docs and neither Object, Module, Class, nor
Singelton have a method named ‘instance’. Where does that come from?
9998 % ri Singleton
= Singleton
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
# ...
…
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs