Domanda

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

È stato utile?

Soluzione

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

class MyClass
  def self.instance
    Dispatch.once { @instance ||= new }
    @instance
  end
end

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top