On Thu, Sep 30, 2010 at 11:32 PM, Jeremy Bopp <jeremy / bopp.net> wrote:
> On 9/30/2010 2:53 PM, Alex Stahl wrote:
>> But is there a way to call the original method instead of just quitting
>> out?
>
> If you want to know if you can conditionally define the method and skip
> the exit, yes, you can. =A0Just leave out the else clause of the example.
> =A0That way, your method is called only if the original one didn't alread=
y
> exist. =A0I used this once to implement Enumerable#none? only under
> versions of Ruby where that method was not yet implemented.
>
> If you want to have a kind of functionality similar to that provided by
> the super keyword, you can do that too:
>
> class String
> =A0if method_defined?(:my_method) then
> =A0 =A0alias :my_method_orig :my_method
> =A0end
>
> =A0def my_method
> =A0 =A0# Maybe do some extra stuff here.
> =A0 =A0...
>
> =A0 =A0# Call the original method if there is one.
> =A0 =A0if methods.include?("my_method_orig") then
> =A0 =A0 =A0my_method_orig
> =A0 =A0end
>
> =A0 =A0# Maybe do more extra stuff here.
> =A0 =A0...
> =A0end
> end
>
> This will alias the original instance of my_method, if there is one, to
> my_method_orig. =A0Your new my_method definition can call the alias if it
> exists and skip it otherwise. =A0I suppose this would be good for
> instrumenting methods to add logging and the like, but I would take care
> with using this generally since it can make some unnecessarily
> complicated code.

Shouldn't we be using respond_to? instead of method_defined? or
methods.include?.
This way, if the method is handled dynamically through method_missing
you can check that too, and not "override" the behaviour.

Jesus.