module TraceCalls
def self.included(klass)
klass.instance_methods(false).each do |existing_method|
wrap(klass, existing_method)
end
def klass.method_added(method)
puts "@@@"
puts method
puts @trace_calls_internal
puts "$$$$"
unless @trace_calls_internal
@trace_calls_internal = true
TraceCalls.wrap(self, method)
@trace_calls_internal = false
end
end
end
def self.wrap(klass, method)
puts "###{}"
puts klass
puts method
puts "*****"
klass.instance_eval do
method_object = instance_method(method)
define_method(method) do |*args, &block|
puts "==> calling #{method} with #{args.inspect}"
result = method_object.bind(self).call(*args, &block)
puts "<== #{method} returned #{result.inspect}"
result
end
end
end
end
class Example
def one(arg)
puts "One called with #{arg}"
end
end
ex1 = Example.new
ex1.one("Hello")
class Example
include TraceCalls
def two(arg1, arg2)
arg1 + arg2
end
end
ex1.one("GoodBye")
puts ex1.two(4, 5)
上面的代码跟踪有点绕,不是很清楚,希望大神们帮解析一下这其中的调用,还有像这种 ruby 元编程的东西有没有什么好方法去学习?