Reputation: 20815
I'm attempting to create a class that uses the Singleton module:
class Foo
include Singleton
# def initialize
# puts "Initialized!"
# end
singleton_class.class_eval do
attr_accessor :bar
end
end
The problem here is that bar
does not have a default/initial value. I've added a initialize
method to my class in hopes that it would be invoked once but this doesn't seem to be the case. What is the proper way to ensure that bar
has a value when this class is loaded?
Upvotes: 1
Views: 651
Reputation: 19228
As you implemented it the accessors for @bar
are methods of the class Foo
, thus you have define @bar
as a class instance variable of Foo
, not of the instance of Foo
:
class Foo
include Singleton
@bar = 0
singleton_class.class_eval do
attr_accessor :bar
end
end
Foo.bar
# => 0
Upvotes: 3