Created
May 3, 2009 23:02
-
-
Save chriseppstein/106184 to your computer and use it in GitHub Desktop.
Tracing ruby method calls
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| | |
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 |
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 | |
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