【发布时间】:2011-04-25 17:19:11
【问题描述】:
在 Ruby 中,如何以编程方式确定哪个类/模块定义了正在调用的方法?
假设在给定范围内我调用some_method()。在同一个范围内,我想调用一个函数find_method(:some_method),它会返回哪个类、单例类或模块定义了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)。
我只是不知道实现 find_method 的 Ruby 元模型的正确顺序和所有细微之处,因此它在搜索中既详尽无遗,而且从方法分派解决方案的角度来看是正确的。
谢谢!
【问题讨论】:
标签: ruby methods metaprogramming dispatch