junk junk - 25 days ago 8
Ruby Question

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

The title may not be clear.

here is the code

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


i want to get the info of aa when bb is execute in aa block

how to solve this problem or it can be solved? thanks;

Answer

To prefix my answer: This is extremely bad practice. Do not do this in production code.

Using the binding_of_caller gem, we evaluate the current method two frames up (the first frame up is the BasicObject#instance_eval, the second frame up is 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