加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 在拥有Class时查找方法的source_location

发布时间:2020-12-17 02:31:31 所属栏目:百科 来源:网络整理
导读:我正在研究捕获基类上定义的每个方法,查找它定义的文件,然后根据它做一些逻辑. 我目前有: # 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

我希望能够找到该方法的源位置.

我可以这样做:

self.new.method(source).source_location

但是,不要认为我应该实例化任何东西以使其工作.

有任何想法吗?

解决方法

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

instance_method(method).source_location  # `self` is unnecessary,it is added implicitly
# => ["/home/alex/Projects/test/test.rb",23]

instance_method(symbol) → unbound_method

Returns an UnboundMethod representing the given instance method in mod.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读