Is the current Ruby method called via super?

后端 未结 5 1558
北海茫月
北海茫月 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:53

    Edit Improved, following Stefan's suggestion.

    module SuperDetector
      def via_super?
        m0, m1 = caller_locations[0].base_label, caller_locations[1]&.base_label
        m0 == m1 and
        (method(m0).owner rescue nil) == (method(m1).owner rescue nil)
      end
    end
    

提交回复
热议问题