initializing ruby singleton

initialization, ruby, rubymotion, singleton

Solution

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

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

Problem

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

Original source