From: Gregory Millam Date: 2004-02-27T02:49:56+09:00 Subject: Re: Callback Received: Fri, 27 Feb 2004 02:29:48 +0900 And lo Han wrote: > class A > def callback(name, obj) > @obj = obj > eval("def #{name}; @obj.keys; end") > end > end > > class B > attr_reader :keys > def initialize(k, cb) > @keys = k > cb.callback('cassette', self) > end > end > > a = A.new > g = B.new([1,2,3], a) > puts a.cassette > class A def initialize @cb_hash = Hash.new(nil) end def callback(name,&block) @cb_hash[name.to_sym] = block if block_given? end def method_missing(name,*args) return @cb_hash[name].call(*args) if @cb_hash.has_key?(name) end end a = A.new a.callback("mykeys") { [1,2,3] } puts a.mykeys.join(', ') #=> 1, 2, 3 class B def initialize(k,cb) cb.callback("cassette") { k } end end b = B.new([4,5,6],a) puts a.cassette.join(', ') #=> 4, 5, 6 Personally, I think writing a caller in class A (i.e a.call("cassette").join) instead of method missing makes more sense, but it's up to you. Options left to the reader: allow 'callback' to accept blocks and non-blocks, and have method_missing (or call()) act differently depending on if it's a proc block or not: i.e returning the value instead of calling it. I hope this helped, - Greg