From: Damphyr Date: 2006-02-02T01:45:37+09:00 Subject: Re: callbacks, events, notification in general ara.t.howard@noaa.gov wrote: > On Thu, 2 Feb 2006, Damphyr wrote: > >> OK, bare with me, this is brainstorming of a sorts: >> I want to have some kind of event notification from my classes. >> Typically what I would do would be to pass a logger object and let the >> class log by itself, but I'm not really satisfied with this solution in >> most cases. >> >> What I would prefer was define a callback method and give this to the >> object. Then I could do whatever I want with it and not only use logs. >> Mostly I want to have progress reports. >> >> something like >> >> class A >> def set_callback notify >> @notify=notify >> end >> def something >> puts "something" >> send(@notify) if @notify >> end >> end >> >> def coocoo >> puts "hey" >> end >> a=A.new >> a.something >> a.set_callback(:coocoo) >> a.something >> >> Now this does exactly what I want and can be wrapped up in a module to >> be included for general use. >> Question: Is there a "better" solution? What are my alternatives? >> Cheers, >> V.- > > harp:~ > cat a.rb > require "observer" > > class A > include Observable > def something > changed and notify_observers 42 > end > end > > class B > def update arg > p arg > end > end > > a = A::new > b = B::new > > a.add_observer b > a.something > > > harp:~ > ruby a.rb > 42 > > always a good start to read about the stdlibs! ;-) Well, actually it would be a good start to remember the names of the patterns :) . *Then* I can remember that there is an implementation in the standard library. I've been staring at the screen for too long I guess. There is a slight difference though: In Observer the observer is an object that needs to specify the update method. I was aiming to provide the notifier with a method, any method, to call. Mine is a one-to-one callback between instances. With the observer pattern you get one-to-many and the observer can observe *any* observable object. More generic and at the end more practical because I will end up naming everything the same every time I use it. Just need to be careful to add one/delete one instead of reassigning the callback in order to replace an observer. Cheers, V.- -- http://www.braveworld.net/riva ____________________________________________________________________ http://www.freemail.gr - ������ �������� ������������ ������������. http://www.freemail.gr - free email service for the Greek-speaking.