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)
这可能吗?
简单回答是不。但是,您可以使用caller,它使您可以访问调用堆栈,就像异常回溯一样:
def this_method_was_called_internally?
caller[1].include?(...)
end
Run Code Online (Sandbox Code Playgroud)
(caller[1]将是之前的调用,即调用的方法this_method...)
这是非常hackish的,你从中获得的信息caller可能还不够。
请不要将其用于实验以外的用途。
| 归档时间: |
|
| 查看次数: |
65 次 |
| 最近记录: |