Skip to content

Instantly share code, notes, and snippets.

@andypalmer
Created March 31, 2015 12:40
Show Gist options
  • Save andypalmer/f1c80a0cdc55ceb2d552 to your computer and use it in GitHub Desktop.
Save andypalmer/f1c80a0cdc55ceb2d552 to your computer and use it in GitHub Desktop.
module MethodLogging
def self.logger=(logger)
@@logger = logger
end
def self.included(base)
base.extend(ClassMethods)
end
def log(method, something)
@@logger.debug("Calling %s#%s with %s" % [method.owner, method.name, something])
end
module ClassMethods
def log_method(*methods)
@logged_methods ||= Set.new
@annotated_methods ||= Set.new
@logged_methods += methods
((instance_methods.to_set & @logged_methods) - @annotated_methods).each { |m| add_logging(m) }
end
def add_logging(method)
return if @annotated_methods.include?(method)
@annotated_methods << method
old_method = instance_method(method)
define_method(method) do |*args|
log(old_method, args)
old_method.bind(self).call(*args)
end
end
def method_added(method)
return unless @logged_methods.include?(method)
return if @working_on == method
@working_on = method
@annotated_methods.delete(method)
(@logged_methods & [method]).each { |m| add_logging(m) }
@working_on = nil
end
end
end
class Example
include MethodLogging
log_method :echo
def echo(message1, message2)
end
end
describe "" do
it "" do
logger = spy('logger')
MethodLogging.logger = logger
x = Example.new
x.echo("Hello", "world")
expect(logger).to have_received(:debug).with("Calling Example#echo with [\"Hello\", \"world\"]")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment