Calling super's super method

前端 未结 3 2095
慢半拍i
慢半拍i 2021-02-07 10:11

Is is possible to do something like super.super in the overriden method? That is, to bypass the direct parent\'s super and call \"grandparent\'s\" super?

3条回答
  •  [愿得一人]
    2021-02-07 10:51

    you could modify the method's arguments to allow some kind of optional 'pass to parent' parameter. in the super class of your child, check for this parameter and if so, call super from that method and return, otherwise allow execution to continue.

    class Grandparent; def method_name(opts={}); puts "Grandparent called."; end; end
    class Parent < Grandparent
    def method_name(opts={})
      return super if opts[:grandparent]
      # do stuff otherwise...
      puts "Parent called."
    end
    end
    class Child < Parent
    def method_name(opts={})
      super(:grandparent=>true)
    end
    end
    
    ruby-1.9.2-p0 > Child.new.method_name
    Grandparent called.
      => nil   
    

    otherwise i agree with @Femaref, just b/c something is possible doesn't mean it's a good idea. reconsider your design if you think this is necessary.

提交回复
热议问题