Skip to content

Instantly share code, notes, and snippets.

@xpepper
Last active December 16, 2015 14:49
Show Gist options
  • Save xpepper/5451772 to your computer and use it in GitHub Desktop.
Save xpepper/5451772 to your computer and use it in GitHub Desktop.
The orrible first implementation of the trace class problem
module TraceCalls
def self.included(including_class)
def including_class.method_added(name)
return if @_adding_a_method
@_adding_a_method = true
TraceCalls.wrap_method(self, name)
@_adding_a_method = false
end
end
def self.wrap_method(klass, name)
original_method = "original_#{name}"
body = %{
alias_method :#{original_method}, :#{name}
def #{name}(*args, &block)
puts "==> Calling #{name} with \#{args.inspect}"
result = #{original_method}(*args, &block)
puts "<== result = \#{result}"
result
end
}
klass.class_eval body
end
end
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)
ex.method2(99) {2}
ex.name = "Piero"
puts ex.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment