How do I call a super class method

前端 未结 5 815
栀梦
栀梦 2020-12-24 01:44

I have two classes A, and B. Class B overrides the foo method of class A. Class B has a b

相关标签:
5条回答
  • 2020-12-24 02:10

    Based on @Sony's answer.

    In case when you want to call the method method on some my_object and it's already overriden somewhere several classes higher (like for the Net::HTTPRequest#method), instead of doing .superclass.superclass.superclass use the:

    Object.instance_method(:method).bind(my_object)
    

    Like this:

    p Object.instance_method(:method).bind(request).call(:basic_auth).source_location
    
    0 讨论(0)
  • 2020-12-24 02:17

    In this particular case you can just alias :bar :foo before def foo in class B to rename the old foo to bar, but of course you can alias to any name you like and call it from that. This question has some alternative ways to do it further down the inheritance tree.

    0 讨论(0)
  • 2020-12-24 02:22

    You can alias old_foo foo before redefining it to keep the old implementation around under a new name. (Technically it is possible to take a superclass's implementation and bind it to an instance of a subclass, but it's hacky, not at all idiomatic and probably pretty slow in most implementation to boot.)

    0 讨论(0)
  • 2020-12-24 02:27

    You can do:

     def bar
       self.class.superclass.instance_method(:foo).bind(self).call
     end
    
    0 讨论(0)
  • 2020-12-24 02:30

    In Ruby 2.2, you can use Method#super_method now

    For example:

    class B < A
      def foo
        super + " world"
      end
    
      def bar
        method(:foo).super_method.call
      end
    end
    

    Ref: https://bugs.ruby-lang.org/issues/9781#change-48164 and https://www.ruby-forum.com/topic/5356938

    0 讨论(0)
提交回复
热议问题