[英]How can I programmatically determine which class/module defines a method being called?
在Ruby中,我如何以編程方式確定哪個類/模塊定義了被調用的方法?
在給定的范圍內說我調用some_method()
。 在相同的范圍內,我想調用一個函數find_method(:some_method)
,它將返回哪個Class,Singleton類或Module定義some_method
。
這里有一些代碼來說明我的意思:
class Foo
include ...
def bar
...
some_method() # calls a method in scope, assume it exists
find_method(:some_method) # Returns where the method is defined
# e.g. => SomeClassOrModule
...
end
end
我猜我必須使用復雜的反射函數混合,從self
開始並使用self.ancestors
走向繼承樹,使用method_defined?
檢查是否在類或模塊上定義了一個方法,並且可能還有一些其他技巧來檢查從最里面到最外層的范圍(因為代碼可以在其中運行,例如, instance_eval
)。
我只是不知道正確的順序和Ruby元模型的所有細微之處來實現find_method
這樣它在搜索中都是詳盡無遺的,並且從方法調度解析的角度來看是正確的。
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.