From: Robert Feldt Date: 2001-05-07T23:55:20+09:00 Subject: [ruby-talk:14773] Re: SimpleDelegator assymetry On Mon, 7 May 2001, Wyss Clemens wrote: > The Ruby "delegate" implementation takes the object from the constructor > (the super-call) to find out the API which is to be implemented (i.e. to be > delegated). These methods are then dynamically "added" to the > Delegator-class (i.e. ANB). > In your third example, it is the NilClass! > __setobj__ has no influence on the Delegator-API. > Yes, I know. Sorry for being brief but my question is really: Is this the behavior we want? I implemented the "symmetrical" behavior and there's a diff below. I probably introduced a couple of bugs in the process... ;-) Regards, Robert --- /usr/local/lib/ruby/1.7/delegate.rb.old Mon May 7 16:25:30 2001 +++ /usr/local/lib/ruby/1.7/delegate.rb Mon May 7 16:54:22 2001 @@ -19,6 +19,11 @@ class Delegator def initialize(obj) + @__delegated_methods = Array.new + create_methods_of_object(obj) + end + + def create_methods_of_object(obj) preserved = ::Kernel.instance_methods preserved -= ["to_s","to_a","inspect","==","=~","==="] for t in self.type.ancestors @@ -27,8 +32,9 @@ preserved |= t.protected_instance_methods break if t == Delegator end - for method in obj.methods - next if preserved.include? method + new_delegated_methods = (obj.methods - preserved) || [] + for method in (new_delegated_methods - @__delegated_methods) + @__delegated_methods.push method eval <<-EOS def self.#{method}(*args, &block) begin @@ -41,7 +47,9 @@ end EOS end - end + # Maybe we should undef the methods in + # (@__delegated_methods-new_delegated_methods) here? + end def __getobj__ raise NotImplementError, "need to define `__getobj__'" @@ -61,6 +69,7 @@ end def __setobj__(obj) + create_methods_of_object(obj) unless @obj.methods == obj.methods @obj = obj end end