Skip to content

Instantly share code, notes, and snippets.

@chriseppstein
Created May 3, 2009 23:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseppstein/106184 to your computer and use it in GitHub Desktop.
Save chriseppstein/106184 to your computer and use it in GitHub Desktop.
Tracing ruby method calls
module Tracer
def trace(method)
method, ending = split_method_name(method)
define_method "#{method}_with_trace#{ending}" do |*arguments|
puts "called #{self.class}##{method}#{ending}(#{arguments.map(&:inspect).join(', ')})"
returning(send("#{method}_without_trace#{ending}", *arguments)) do |v|
if block_given?
yield self, v
end
puts "#{self.class}##{method}#{ending} => #{v.inspect}"
end
end
alias_method_chain "#{method}#{ending}", :trace
end
private
def split_method_name(method)
if ['?', '!'].include?(method.to_s[-1..-1])
[method.to_s[0..-2], method.to_s[-1..-1]]
else
[method, nil]
end
end
end
class Foo
extend Tracer
def foo
puts "inside foo"
end
trace :foo
end
irb(main):087:0> Foo.new.foo
called Foo#foo()
inside foo
Foo#foo => nil
=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment