I'm trying to initializing a singleton in ruby. Here's some code:
class MyClass
attr_accessor :var_i_want_to_init
# singleton
@@instance = MyClass.new
def self.instance
@@instance
end
def initialize # tried 1. initialize, 2. new, 3. self.initialize, 4. self.new
puts "I'm being initialized!"
@var_i_want_to_init = 2
end
end
The problem is that initialize is never called and thus the singleton never initialized. I tried naming the init method initialize, self.initialize, new, and self.new. Nothing worked. "I'm being initialized" was never printed and the variable never initialized when I instantiated with
my_var = MyClass.instance
How can I setup the singleton so that it gets initialized? Help appreciated,
Pachun
Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Singleton has almost the same pros and cons as global variables. Although they're super-handy, they break the modularity of your code.
The Singleton Ruby mixin itself is thread safe. It means that you are guaranteed to get the same instance in all threads, and only that! It doesn't mean that methods which you implement for a singleton class by yourself will be thread safe.
The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object. Below are some points about Initialize : We can define default argument. It will always return a new object so return keyword is not used inside initialize method.
Finally, let's try to give a proper definition of the eigenclass in Ruby: The eigenclass is an unnamed instance of the class Class attached to an object and which instance methods are used as singleton methods of the defined object. Voilà!
There's a standard library for singletons:
require 'singleton'
class MyClass
include Singleton
end
To fix your code you could use the following:
class MyClass
attr_accessor :var_i_want_to_init
def self.instance
@@instance ||= new
end
def initialize # tried 1. initialize, 2. new, 3. self.initialize, 4. self.new
puts "I'm being initialized!"
@var_i_want_to_init = 2
end
end
Rubymotion (1.24+) now seems to support using GCD for singleton creation
class MyClass
def self.instance
Dispatch.once { @instance ||= new }
@instance
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With