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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.