Forum: Ruby Wait until a Singleton instantiated?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
E6b040ecc51de500ee5a6f83aa3adc68?d=identicon&s=25 Kfir Lavi (Guest)
on 2009-05-09 19:20
(Received via mailing list)
Hi,
I have singleton class I want to observe with another class. The
problem is that the singleton class will create the instance of the
class that wants to observe it.
Here is an example:
require 'singleton'
require 'observer'

class A
  include Singleton
  include Observable

  def initialize
    B.new
    sleep 10
  end
end

class B
  def initialize
    # register for A updates
    A.instance.add_observer(self) # will fail, because it waits for A
  end
end

A.instance

You need to stop the program with Control-C and you get:

^C/usr/lib/ruby/1.8/singleton.rb:149:in `sleep': Interrupt
        from /usr/lib/ruby/1.8/singleton.rb:149:in `_instantiate?'
        from /usr/lib/ruby/1.8/singleton.rb:105:in `instance'
        from c.rb:21:in `initialize'
        from c.rb:10:in `new'
        from c.rb:10:in `initialize'
        from /usr/lib/ruby/1.8/singleton.rb:94:in `new'
        from /usr/lib/ruby/1.8/singleton.rb:94:in `instance'
        from c.rb:25

Command terminated

The problem is that A didn't finish initializing, and B in order to
add_observer waits for A to finish initialize. So both A and B
sleeping waiting for each other.

I thought to solve it by creating a thread that will wait for A to
finish initialize.
Something like this:
Thread.new(self) do |me|
  while A.instance.not_initialize? do
    sleep 2
  end
  A.instance.add_observer(self)
end

But how do I monitor if A finished initialize?
Also, is there a better way of doing this? Idiom?

Thanks,
Kfir
8f6f95c4bd64d5f10dfddfdcd03c19d6?d=identicon&s=25 Rick Denatale (rdenatale)
on 2009-05-09 23:03
(Received via mailing list)
On Sat, May 9, 2009 at 1:20 PM, Kfir Lavi <lavi.kfir@gmail.com> wrote:
>  include Observable
>
>  def initialize
>    B.new
>    sleep 10
>  end
> end

Why are you instantiating B here?  This is odd for several reasons:

1. The whole point of the observer pattern is that the observable
object doesn't shouldn't know about the actual observers or who
created them.

2. Your initialize method creates an instance of B and then ignores
it, it's subject to be GCed since there are no references to it.

So why not:

class A
 include Singleton
 include Observable

 def initialize
   sleep 10
 end
end

class B
 def initialize
   A.instance.add_observer(self)
 end
end

a_observer = B.new



--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale
This topic is locked and can not be replied to.