Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing ruby singleton

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

like image 718
pachun Avatar asked May 24 '12 08:05

pachun


People also ask

What is singleton Ruby?

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.

Is Ruby singleton thread safe?

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.

What is initialize method in Ruby?

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.

What is a ruby Eigenclass?

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à!


2 Answers

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
like image 61
Koraktor Avatar answered Oct 19 '22 20:10

Koraktor


Rubymotion (1.24+) now seems to support using GCD for singleton creation

class MyClass
  def self.instance
    Dispatch.once { @instance ||= new }
    @instance
  end
end
like image 6
k107 Avatar answered Oct 19 '22 19:10

k107