简体   繁体   English

红宝石中某个类方法的已定义超级方法列表

[英]List of defined super methods for a certain class method in ruby

I am working on a system with a some complex class/mixin hierarchy. 我正在使用具有一些复杂的类/混合层次结构的系统。 As there are several numerous layers scattered over many different files, I want to quickly see what the chain of super calls is for a given method. 由于散布在许多不同文件上的层数众多,因此我想快速了解给定方法的超级调用链。

For example 例如

module AAA
  def to_s
    "AAA " + super()
  end
end

module BBB
  def to_s
    "BBB " + super()
  end
end

class MyArray < Array
  include AAA
  include BBB

  def to_s
    "MyArray " + super()
  end
end

> MyArray.new.to_s
=> "MyArray BBB AAA []"
> method_supers(MyArray,:to_s)
=> ["MyArray#to_s", "BBB#to_s", "AAA#to_s", "Array#to_s", ...]

Perhaps something like this? 也许像这样?

class A
  def foo; p :A; end
end

module B
  def foo; p :B; super; end
end

module C; end

class D < A
  include B, C
  def foo; p :D; super; end
end

p D.ancestors.keep_if { |c| c.instance_methods.include? :foo }  # [D, B, A]

If that seems right, you could amend this function accordingly: 如果看起来正确,则可以相应地修改此功能:

def Object.super_methods(method)
  ancestors.keep_if { |c| c.instance_methods.include? method }
end

p D.super_methods(:foo)  # [D, B, A]
def method_supers(child_class,method_name)
  ancestry = child_class.ancestors

  methods = ancestry.map do |ancestor|
    begin
      ancestor.instance_method(method_name)
    rescue
      nil
    end
  end

  methods.reject!(&:nil?)

  methods.map {|m| m.owner.name + "#" + m.name.to_s}
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM