Skip to content

Instantly share code, notes, and snippets.

@chriseppstein
Created August 21, 2008 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseppstein/6666 to your computer and use it in GitHub Desktop.
Save chriseppstein/6666 to your computer and use it in GitHub Desktop.
Trace method entrances and exists. Requires ActiveSupport.
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|
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.last)
[method.to_s[0..-2], method.to_s.last]
else
[method, nil]
end
end
end
class Foo
extend Tracer
def foo(*args)
'foo'
end
trace :foo
end
>> Foo.new.foo
called Foo#foo()
Foo#foo => "foo"
=> "foo"
>> Foo.new.foo(1)
called Foo#foo(1)
Foo#foo => "foo"
=> "foo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment