1

我正在开发一个具有一些复杂类/mixin 层次结构的系统。由于有许多层分散在许多不同的文件中,我想快速查看给定方法的超级调用链是什么。

例如

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", ...]
4

2 回答 2

1

也许是这样的?

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]

如果这看起来正确,您可以相应地修改此函数:

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

p D.super_methods(:foo)  # [D, B, A]
于 2013-06-22T12:54:28.573 回答
0
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
于 2013-06-21T19:20:11.833 回答