Skip to content

Instantly share code, notes, and snippets.

@chrismo
Forked from nhance/method_logger.rb
Created September 13, 2012 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismo/3715115 to your computer and use it in GitHub Desktop.
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.
# 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