On Jan 15, 2008, at 10:32 AM, Andrew Stewart wrote:

> Hi Everyone,
>
> I believe one can add methods to a class by including a module but  
> not override existing methods.  Indeed Dr Nic said as much here:
>
> http://ruby.tie-rack.org/6/safely-overriding-method_missing-in-a- 
> class-that-already-has-it/#comment-7



i personally avoid aliases like that - they stack when you double  
require or double include a module and throw into a loop.  this kind  
of thing can be done safely and generically using a variable for the  
previous method that's protected from the gc and a lookup in the new  
method:



cfp:~ > cat a.rb
class A
   def foo
     p "A.foo"
   end
end
class B
end

module M
   NoGC = []

   def self.included other
     other.module_eval do
       if((foo = instance_method 'foo' rescue false))
         NoGC.push foo
         supra = "ObjectSpace._id2ref(#{ foo.object_id }).bind 
(self).call(*a, &b)"
       end
       eval <<-code
         def foo *a, &b
           #{ supra }
           p "M.foo"
         end
       code
     end
   end
end

A.send :include, M
B.send :include, M

A.new.foo
B.new.foo


cfp:~ > ruby a.rb
"A.foo"
"M.foo"
"M.foo"


this allows you to both override and super up, in any combination,  
with a method injected late into a class hierarchy


kind regards


a @ http://codeforpeople.com/
--
it is not enough to be compassionate.  you must act.
h.h. the 14th dalai lama