Forum: Ruby best praxis to wrap methods?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
48d1aca7191f2d16e184971054c7c143?d=identicon&s=25 Meinrad Recheis (Guest)
on 2006-03-07 10:42
(Received via mailing list)
hello fellow rubyists,

is there an elegant way to define a singleton method from a given symbol
without using eval? what i am doing is this:

def make_wrapper object, method
  eval %{
    def object.#{method}
       # do something here
       super # call the wrapped method
    end
  }
end

# example of usage:
make_wrapper STDOUT, :puts

using eval works, but it seems not to be the best solution. is there
annother way do define methods from a given symbol?

-- henon
48d1aca7191f2d16e184971054c7c143?d=identicon&s=25 Meinrad Recheis (Guest)
on 2006-03-07 10:45
(Received via mailing list)
On 3/7/06, Meinrad Recheis <meinrad.recheis@gmail.com> wrote:
>        super # call the wrapped method
>     end
>   }
> end


sorry the  above code does not work, (needs to be done using
object.instance_eval) but you get the idea what i mean

# example of usage:
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 Robert Klemme (Guest)
on 2006-03-07 10:51
(Received via mailing list)
Meinrad Recheis wrote:
>     end
>   }
> end
>
> # example of usage:
> make_wrapper STDOUT, :puts
>
> using eval works, but it seems not to be the best solution. is there
> annother way do define methods from a given symbol?

Are you sure the code you presented actually works?  IMHO your code will
fail if the method is defined in the same class (i.e. no "super"
possible).

You could use Delegator for this.  And, if the method you want to wrap
does not use a block define_method usually works quite well.

Kind regards

    robert
48d1aca7191f2d16e184971054c7c143?d=identicon&s=25 Meinrad Recheis (Guest)
on 2006-03-07 11:03
(Received via mailing list)
On 3/7/06, Robert Klemme <bob.news@gmx.net> wrote:
>
> Meinrad Recheis wrote:
> [snipped]
>
> Are you sure the code you presented actually works?  IMHO your code will
> fail if the method is defined in the same class (i.e. no "super"
> possible).


afaik calling super in a singleton method calls the overridden method of
that object (of course i assert that the method to be wrapped exists).
here is the working code snippet:
def make_wrapper object, method
        object.instance_eval %{
            def self.#{method}(*args, &block)
                puts "wrapped method #{method}"
                super
            end
        }
end

You could use Delegator for this.  And, if the method you want to wrap
> does not use a block define_method usually works quite well.


ah, object.send( :define_method) is what i was looking for. thanks

Kind regards
This topic is locked and can not be replied to.