当它在方法中作为块执行时,如何在方法 bb 中获取方法 bb 的调用者

how to get method bb's caller in method bb when it excuted in method aa's block

标题可能不清楚

这是代码

  def self.aa(&block)
    instance_eval &block
  end

  def self.bb
    # i want to get aa info here
    p caller[0]
  end

 #shuriken is a module 
 Shuriken.aa do
  bb
 end

我想在aa块中执行bb时获取aa的信息

这个问题怎么解决或者可以解决?谢谢;

作为我的回答的前缀:这是非常糟糕的做法。不要在生产代码中这样做。

使用binding_of_caller gem,我们评估当前方法两帧向上(第一帧向上是BasicObject#instance_eval,第二帧向上是Shuriken.aa) :

require 'binding_of_caller'

class Shuriken
  def self.aa(&block)
    instance_eval &block
  end

  def self.bb
    the_aa = binding.of_caller(2).eval('method(__method__)')
    puts the_aa
    # => #<Method: Shuriken.aa>
  end
end

Shuriken.aa do
  bb
end