-
-
Save chrismo/3715115 to your computer and use it in GitHub Desktop.
Rails compatible method logging. Use this to log all calls to instance methods of a class to the log.
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
# converted to stand-alone script | |
require 'minitest/autorun' | |
require 'minitest/unit' | |
require 'stringio' | |
# fake out the logger | |
class Rails | |
@@logger = StringIO.new | |
def self.logger | |
@@logger | |
end | |
end | |
module MethodLogger | |
def self.included(base) | |
methods = base.instance_methods(false) + base.private_instance_methods(false) | |
base.class_eval do | |
methods.each do |method_name| | |
original_method = instance_method(method_name) | |
define_method(method_name) do |*args, &block| | |
Rails.logger.puts "-> #{base}##{method_name}(#{args.inspect})" | |
return_value = original_method.bind(self).call(*args, &block) | |
Rails.logger.puts "<- #{base}##{method_name} #=> #{return_value.inspect}" | |
return_value | |
end | |
end | |
end | |
end | |
end | |
class Model | |
def foo | |
"bar" | |
end | |
# maybe inside Rails, things are different enough to allow including the module at | |
# the top of the class, but in stand-alone the include must come after the methods | |
# have been defined for this to work. | |
include MethodLogger | |
end | |
class TestMethodLogger < MiniTest::Unit::TestCase | |
def test_it | |
model = Model.new | |
model.foo | |
Rails.logger.rewind | |
assert_equal "-> Model#foo([])\n<- Model#foo #=> \"bar\"\n", Rails.logger.read | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment