开发者

Ruby call method on all following def calls?

I've seen some code that makes a class method such that you can write

class_method :instance_method,
开发者_如何学JAVA

to alias instance_method and call it from in a wrapper method every time it is called. Is there a way to be able to call class_method and have it apply to all the following definition calls (like how private works)?


I don't quite understand your question. In the future, please provide a specification of what it is exactly that you are trying to do, preferably in the form of an executable testsuite, so that we can check for ourselves whether our answers really answer your question.

Are you perhaps talking about something like this?

module MethodHook
  private

  def class_method(m=nil)
    return if @__recursing__ # prevent infinite recursion
    return @__class_method__ = true unless m

    @__recursing__ = true

    old_m = instance_method(m)
    define_method(m) do |*args, &block|
      puts "before #{m}(#{args.join(', ')})" # wrap wrap wrap
      old_m.bind(self).(*args, &block)
      puts "after #{m}" # more wrapping
    end

    @__recursing__ = nil
  end

  def method_added(m)
    class_method(m) if @__class_method__
    super
  end
end

Use like this:

class Foo
  extend MethodHook

  def unwrapped
    puts __method__
  end

  class_method

  def wrapped
    puts __method__
  end
end

f = Foo.new

f.unwrapped
# unwrapped

f.wrapped
# before wrapped()
# wrapped
# after wrapped

class Foo
  class_method(:unwrapped)
end

f.unwrapped
# before unwrapped()
# wrapped
# after unwrapped
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜