开发者

getting in-out from ruby methods

开发者 https://www.devze.com 2023-04-11 22:03 出处:网络
I am using jruby to run bunch of ruby scripts, though I am using pure ruby part of it. It sometimes gets difficult to follow from output what exactly is happening or where exactly something went wro

I am using jruby to run bunch of ruby scripts, though I am using pure ruby part of it.

It sometimes gets difficult to follow from output what exactly is happening or where exactly something went wrong.

I wanted to get something like this in my std out for every method: entered in method A out of method A

Now I can surely go and put those comments in every method ..which feels very wrong. Is there a way to run ruby in a little verbose more开发者_如何学编程 to get this information in my log. Hopefully I would avoid using a lot of gems etc .. since these are on some managed servers and I will have to spend some time to just get more s/f on it. Hoping something would be avail as part of jruby itself

Thanks!


You could use this code:

module InOutHook
  module ClassMethods
    def setup_hooks(*syms)
      syms.each do |sym| # For each symbol
        str_id = "__#{sym}__hooked__"
        unless private_instance_methods.include?(str_id)
          alias_method str_id, sym        # Backup original method
          private str_id                  # Make backup private
          define_method sym do |*args|    # Replace method
            puts ">>> #{self.class}\##{sym} >>>"
            ret = __send__ str_id, *args  # Invoke backup
            puts "<<< #{self.class}\##{sym} >>>"
            ret
          end
        end
      end
    end
  end
  def InOutHook.included(base)
    base.extend(ClassMethods)
  end
end

class TestClass
  def test1
    puts "test!"
  end
  def test2(v)
    puts "Value is #{v}"
  end
  include InOutHook
  setup_hooks(:test1, :test2)
end

# works on existing classes too:
class Array
  include InOutHook
  setup_hooks(:[])
end

tc = TestClass.new
tc.test1
tc.test2(10)

ary = [1,2,3]
puts ary[1..2]

In case you want to add a hoot to every method, just add a splat asterisk:

setup_hooks(*[].methods)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号