如何以编程方式确定哪个类/模块定义了被调用的方法?

Ale*_*ert 4 ruby methods metaprogramming dispatch

在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
Run Code Online (Sandbox Code Playgroud)

我猜我不得不使用的反射功能,从复杂的混合物self,用self.ancestors走了继承树,使用method_defined?检查的方法在类或模块,并且可能是一些其他技巧来检查从范围界定最里面到最外层(因为代码可以在例如a内运行instance_eval).

我只是不知道正确的顺序和Ruby的元模型的所有细微之处来实现find_method,使得它在其搜索既详尽和正确的方法分派分辨率的观点.

谢谢!

Mat*_*chu 8

发现这非常简单.整齐!

扩展此答案,以显示如何实际返回所有者类:

foo.method(:some_method).owner
Run Code Online (Sandbox Code Playgroud)

如果你觉得有必要,可以在实例方法中包装,但那不是那么糟糕,是吗?