From: ara.t.howard@... Date: 2006-02-02T03:10:38+09:00 Subject: Re: callbacks, events, notification in general On Thu, 2 Feb 2006, Damphyr wrote: > Well, actually it would be a good start to remember the names of the > patterns :) . heh. i'm guilty often on that count too - the design patterns books is pretty dry reading to be sure. > *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. you can leverage the exiting code: harp:~ > cat a.rb require "yaml" require "observer" module SoloObservable include Observable module Updateable attr_accessor "update_method" attr_accessor "update_context" def update *a, &b if Proc === update_method begin self.update_context = [a, b] instance_eval &update_method ensure self.update_context = nil end else send update_method, *a, &b end end end def add_observer observer, cb = nil, &cbb observer.extend Updateable observer.update_method = cb || cbb delete_observers super observer end def notify_observer *a, &b changed and notify_observers *a, &b end end class A include SoloObservable def method_that_notifies() notify_observer 42 end end class B def callback(arg) y "arg" => arg end end class C attr "answer" def initialize() @answer = "forty-two" end def klass() self.class.name end end a, b, c = [A,B,C].map{|k| k::new} a.add_observer b, "callback" a.method_that_notifies puts a.add_observer(c){ y "update_context" => update_context.inspect, "klass" => klass, "answer" => answer } a.method_that_notifies harp:~ > ruby a.rb --- arg: 42 --- klass: C answer: forty-two update_context: "[[42], nil]" this allows arbitrary method/block callbacks and confines to a single observer. blocks are evaluated in instance scope and have access to notification params via update_context. hth. -a -- happiness is not something ready-made. it comes from your own actions. - h.h. the 14th dali lama