Ruby 拥有类时查找方法的源位置

Ruby 拥有类时查找方法的源位置,ruby,metaprogramming,Ruby,Metaprogramming,我正在研究捕获基类上定义的每个方法,查找它在哪个文件中定义,然后在此基础上执行一些逻辑 我目前有: # Defined in some file class Subclass < Base def foo end end class Base self.method_added(method) # self is a given subclass (Subclass) # This doesn't work. :(

我正在研究捕获基类上定义的每个方法,查找它在哪个文件中定义,然后在此基础上执行一些逻辑

我目前有:

  # Defined in some file
  class Subclass < Base
    def foo
    end
  end


  class Base
    self.method_added(method)
      # self is a given subclass (Subclass)

      # This doesn't work. :(
      self.method(method).source_location
    end
  end
但我不认为我应该实例化任何东西来让它工作

有什么想法吗?

您可以使用方法获取类的实例方法:

instance_method(method).source_location  # `self` is unnecessary, it is added implicitly
# => ["/home/alex/Projects/test/test.rb", 23]
实例\u方法(符号)→ 无约束法

返回表示mod中给定实例方法的UnboundMethod


有没有一种方法可以仅仅显示而不是提供其位置?
instance_method(method).source_location  # `self` is unnecessary, it is added implicitly
# => ["/home/alex/Projects/test/test.rb", 23]