Reputation: 1404
I implemented this example below for use of the Observer Pattern on Ruby. I tried follow this, but didn't work.
require "observer"
class AAnyClass
extend Observable
changed
notify_observers self
end
module AnObserver
extend self
def update constant
p "Constant #{constant} has been called."
end
def observe constant
constant.add_observer(self)
end
end
AnObserver.observe AAnyClass
# must return "Constant AAnyClass has been called."
AAnyClass
# must return "Constant AAnyClass has been called."
AAnyClass
UPDATE
I converted the module AnObserver
into a class, like this:
class AnObserver
def update constant
$stdout.puts "Constant #{constant} has been called."
end
end
And change the class AAnyClass
adding the Observable
methods into a constructor and passing AnObserver
instance as parameter to method add_observer
, like this:
class AAnyClass
include Observable
def initialize
add_observer AnObserver.new
changed
notify_observers AAnyClass
end
end
And, finally, I added a little code that modifies the eigenclass
of AAnyClass
with the same code of the AAnyClass’s
constructor.
class << AAnyClass
extend Observable
add_observer AnObserver.new
changed
notify_observers AAnyClass
end
AAnyClass
AAnyClass.new
AAnyClass.new
That’s it.
Upvotes: 0
Views: 280
Reputation: 689
I think you are using modules and "extends" where you should be using classes and "includes". Something like this might be what you're looking for:
require "observer"
class AAnyClass
include Observable
def run
changed
notify_observers(self)
end
end
class AnObserver
def initialize(ob)
ob.add_observer(self)
end
def update constant
p "Constant #{constant} has been called."
end
def observe constant
constant.add_observer(constant)
end
end
ob = AAnyClass.new
AnObserver.new ob
ob.run
Upvotes: 1