查找是在外部还是在内部调用类方法

Rya*_*wis 5 ruby

class MyParent
  def self.foo
    if this_method_was_called_internally?
      puts "yay" 
    else
      puts "boo"
    end
  end
end

class MyLibrary < MyParent
  foo # yay
end

MyLibrary.foo # boo
Run Code Online (Sandbox Code Playgroud)

这可能吗?

The*_*heo 2

简单回答是不。但是,您可以使用caller,它使您可以访问调用堆栈,就像异常回溯一样:

def this_method_was_called_internally?
  caller[1].include?(...)
end
Run Code Online (Sandbox Code Playgroud)

caller[1]将是之前的调用,即调用的方法this_method...

这是非常hackish的,你从中获得的信息caller可能还不够。

请不要将其用于实验以外的用途。