Created
August 21, 2008 22:44
-
-
Save chriseppstein/6666 to your computer and use it in GitHub Desktop.
Trace method entrances and exists. Requires ActiveSupport.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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