我正在研究一个具有一些复杂类/ 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", ...]
答案 0 :(得分: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]
答案 1 :(得分: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