如何检查子方法是否称为super

时间:2018-02-07 08:50:51

标签: ruby-on-rails ruby

class Parent
  def a_method
    # some crucial work has to run for every child class
  end
end
# Example 1
class Child < Parent
  def a_method
    super
  end
end

# Example 2
class Child < Parent
  def a_method
  end
end

我希望在示例2的情况下引发错误 必须在重写方法

上调用super

1 个答案:

答案 0 :(得分:2)

  

我希望在示例2的情况下引发错误,必须在重写方法上调用super

这是一个错误的工具。你无法决定孩子该做什么。使用一些OO设计可以做得更好。如果某些工作总是,那么不要建议子类覆盖该方法。相反,只覆盖“自定义”部分。例如:

class Parent
  def a_method
    crucial_work do
      custom_handling
    end
  end

  # child classes override this one, not a_method
  def custom_handling
    # no-op
  end
end

class Child < Parent
  def custom_handling
    "doing custom handling here"
  end
end
相关问题