Last active
December 16, 2015 12:28
-
-
Save xpepper/5434580 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 TraceCalls | |
def self.included(including_class) | |
class << including_class | |
def methods | |
@methods ||= [] | |
end | |
def method_added(name) | |
unless methods.include?(name) | |
methods << name | |
method = instance_method(name) | |
define_method(name) do |*args, &block| | |
puts "==> calling #{name} with #{args.inspect}" if TraceCalls.should_trace? | |
result = method.bind(self).call(*args, &block) | |
puts "<<= returns #{result}" if TraceCalls.should_trace? | |
return result | |
end | |
end | |
end | |
end | |
suppress_tracing do | |
including_class.instance_methods(false).each { |m| including_class.method_added(m.to_sym) } | |
end | |
end | |
def suppress_tracing(&block) | |
old_value = Thread.current["suppress_tracing"] | |
Thread.current["suppress_tracing"] = true | |
begin | |
block.call | |
ensure | |
Thread.current["suppress_tracing"] = old_value | |
end | |
end | |
module_function :suppress_tracing | |
def should_trace? | |
!Thread.current["suppress_tracing"] | |
end | |
module_function :should_trace? | |
end | |
class One | |
include TraceCalls | |
def one | |
t = Two.new | |
t.two | |
end | |
end | |
class Two | |
include TraceCalls | |
def two | |
99 | |
end | |
end | |
One.new.one | |
"ciao" + "pollo" | |
class Example | |
include TraceCalls | |
def some_method(arg1, arg2) | |
arg1 + arg2 | |
end | |
def method2(arg) | |
yield * arg | |
end | |
def name=(val) | |
@name = val | |
end | |
def name | |
@name | |
end | |
end | |
ex = Example.new | |
ex.some_method(4,5) # simple method | |
ex.method2(99) {2} # method with block | |
ex.name = "Piero" # setter and getter methods | |
puts ex.name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment