Overriding Object::send


#1

Why doesn’t this work?

class Object
alias_method :old_send, :send
def send meth, *args
STDERR.puts “#{ meth } was called”
old_send meth, args
end
end


#2

On Monday 16 January 2006 15:11, Joe Van D. wrote:

Why doesn’t this work?

It works for me if I use “module Kernel” instead of “class Object”.


#3

On Tue, 17 Jan 2006, Joe Van D. wrote:

harp:~ > cat a.rb
class Object
def send meth, *a, &b
STDERR.puts “#{ self.class }##{ meth }”
send meth, *a, &b
end
end

42.send “display”

harp:~ > ruby a.rb
Fixnum#display
42

hth.

-a


#4

On 1/16/06, Jacob F. removed_email_address@domain.invalid wrote:

The difference is the splat in front of args in the invocation of
foo.send(:bar). It just so happens the the default implementation of
send just forwards to send. And overwriting send is a bad
idea. :slight_smile:

Hm. Well, essentially what I want to do is output print statements
every time I enter and leave a method. (having problems identifying
what’s going on in my code)


#5

Try:

class Object
alias_method :old_send, :send
def send meth, *args
STDERR.puts “#{ meth } was called”
old_send meth, *args
end
end

The difference is the splat in front of args in the invocation of
old_send. With the splat there, it seems to work for me.

irb> -1.send(:abs)
abs was called
=> 1

This used to give me an error about wrong number of arguments.

Note: this still doesn’t work without invoking send explicitly, since
foo.bar is actually equivalent to foo.send(:bar), not
foo.send(:bar). It just so happens the the default implementation of
send just forwards to send. And overwriting send is a bad
idea. :slight_smile:

Jacob F.


#6

On 1/16/06, Joe Van D. removed_email_address@domain.invalid wrote:

Hm. Well, essentially what I want to do is output print statements
every time I enter and leave a method. (having problems identifying
what’s going on in my code)

Check out set_trace_func, may be what you need:

http://www.rubycentral.com/book/ref_m_kernel.html#Kernel.set_trace_func

Jacob F.


#7

On 1/16/06, Jacob F. removed_email_address@domain.invalid wrote:

On 1/16/06, Joe Van D. removed_email_address@domain.invalid wrote:

Hm. Well, essentially what I want to do is output print statements
every time I enter and leave a method. (having problems identifying
what’s going on in my code)

Check out set_trace_func, may be what you need:

http://www.rubycentral.com/book/ref_m_kernel.html#Kernel.set_trace_func

Aha, I forgot about that one.

Say I want to display the arguments that each function gets. Could I
get that from a binding object?