Created
November 25, 2011 13:03
-
-
Save sohocoke/1393479 to your computer and use it in GitHub Desktop.
intercepting ruby method calls to log or add debug behaviour
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
# idea and much of the implementation from http://stackoverflow.com/questions/2135874/cross-cutting-logging-in-ruby | |
# e.g. o.class.add_logging :method | |
# IMPROVE would be very nice if instructions to add logging could be scoped. | |
class Module | |
def add_logging(*method_names) | |
method_names.each do |method_name| | |
original_method = instance_method(method_name) | |
define_method(method_name) do |*args,&blk| | |
puts "logging #{method_name}: #{args}" | |
original_method.bind(self).call(*args,&blk) | |
end | |
end | |
end | |
# TODO unintercept method | |
# TODO consider using glue or AspectR | |
# TODO find out why this often results in a crash in MacRuby | |
def add_intercept(method_name, intercept_action = nil) | |
original_method = instance_method(method_name) | |
if intercept_action | |
define_method(:handle_intercept) do |*args,&blk| | |
self.instance_exec(*args, blk, &intercept_action) | |
end | |
end | |
begin | |
handler_method = instance_method(:handle_intercept) | |
rescue Exception => e | |
raise "#{e}: probably no proc passed in, no handle_intercept(*args) method defined." | |
end | |
define_method(method_name) do |*args,&blk| | |
puts "begin intercept of #{method_name} on instance #{self.object_id}" | |
begin | |
handler_method.bind(self).call(*args, &blk) | |
rescue Exception => err | |
puts "Error while performing intercept action: #{err}" | |
end | |
puts "end intercept of #{method_name}" | |
original_method.bind(self).call(*args,&blk) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment