Ruby access to symbol "invoked by"

I want to (efficiently) get the symbol an aliased method is called with at runtime. A direct efficient access to a stack frame object of some sort to get it would be the fantasy.

ie:

class Foo
def generic_call(*args)
puts("generic_call() was called by using #{???}")
end

alias :specific_call1 :generic_call
alias :specific_call2 :generic_call

end

Foo.new.specific_call1
Foo.new.specific_call2

the result I'd want


generic_call() was called by using specific_call1()
generic_call() was called by using specific_call2()


class Foo
  def generic_call()
    puts "generic call was called by #{caller[0][/in `([^']+)'/, 1]}"
  end

  def specific_call1() generic_call end
  def specific_call2() generic_call end
end

Foo.new.specific_call2 # Prints: generic call was called by specific_call2

如果您使用的别名创建然而,这将无法正常工作specific_callNgeneric_call因为别名创建的方法实际上是原方法的一个副本-他们不实际调用原来的方法(这就是为什么你可以自由地重新定义了原不影响别名)。


获取当前方法名称的代码片段:

module Kernel
    private
    # Defined in ruby 1.9
    unless defined?(__method__)
      def __method__
        caller[0] =~ /`([^']*)'/ and $1
      end
    end
  end

There's no built-in way to do this. You can kind of hack it like:

def current_method_name
  caller[0].split('`').last.split(''')[0]
end
链接地址: http://www.djcxy.com/p/95426.html

上一篇: 红宝石如何用“<<”来定义写作者的方法

下一篇: Ruby访问符号“由......调用”