Is the current Ruby method called via super?

后端 未结 5 1585
北海茫月
北海茫月 2021-01-05 19:15

Within a method at runtime, is there a way to know if that method has been called via super in a subclass? E.g.

module SuperDetector
  def via_s         


        
5条回答
  •  迷失自我
    2021-01-05 19:52

    There is probably a better way, but the general idea is that Object#instance_of? is restricted only to the current class, rather than the hierarchy:

    module SuperDetector
      def self.included(clazz)
        clazz.send(:define_method, :via_super?) do
          !self.instance_of?(clazz)
        end
      end
    end
    
    class Foo
      include SuperDetector
    
      def bar
        via_super? ? 'super!' : 'nothing special'
      end
    end
    
    class Fu < Foo
      def bar
        super
      end
    end
    
    Foo.new.bar # => "nothing special"
    Fu.new.bar  # => "super!"
    


    However, note that this doesn't require explicit super in the child. If the child has no such method and the parent's one is used, via_super? will still return true. I don't think there is a way to catch only the super case other than inspecting the stack trace or the code itself.

提交回复
热议问题