On Apr 7, 2004, at 8:29 AM, Vadim Nasardinov wrote:

> It occurred to me that it would be useful to be able to trace all
> messages sent to an object in order to figure out how the object is
> used.  So, for example, I would like to be able to see all messages
> sent to baz when it's zipped with foo like so:
>
>      foo.zip(baz)

I believe the "standard" way of tracing method calls would be to use 
the set_trace_func() Kernel method. But it doesn't provide any simple 
ways (that I can see) for only displaying method calls to a particular 
instance of an object.

> I found tracer.rb in the Ruby library, but it seems to have been
> written for a different purpose.  I'm thinking of something similar
> to this:
>
>     #!/usr/bin/ruby
>
>     class Tracer < Array
>         Tracer.new.methods.each do |mm|
>             undef_method mm unless mm == "__send__"
>         end
>
>         def initialize(proxied_object, name)
>             @proxied_object = proxied_object
>             @name = name
>         end
>
>         def method_missing(sym, *args)
>             puts "#{sym} called for #{name}"
>             @proxied_object.method(sym).call(*args)
>         end
>     end
>
>
>     a = Tracer.new([1,2,3,4,5], "a")
>     b = Tracer.new([6,7,8,9,10], "b")
>
>     a.zip(b)
>
> It almost looks like it should work.  Unfortunately, this script
> causes my Ruby interpreter to segfault.  (I'm using Ruby 1.8.0 that
> ships with Fedora Core 1.)
>
> So, I guess my two questions are:
>
>  (a) Has anyone written something like this already?
>  (b) What does the above segfault on me?

Well, here's the immediate problem: the line
   puts "#{sym} called for #{name}"
should be
   puts "#{sym} called for #{@name}"
...to interpolate the instance variable.

also, you should call @proxied_object.send(sym,*args) instead of the 
other way, which I think doesn't work.

The bigger problem is that the way you did this is really probably a 
bad idea. You undefined some critical methods, so the interpreter has 
trouble giving meaningful error messages, even has trouble recovering 
from them at all :)

--Mark