首页 > 解决方案 > 如何处理来自父(通过超级)和子方法调用的结果?

问题描述

考虑这个笨拙的人为示例:

class Notification
  def should_send?
    enrollment_status ? true : false
  end
end

class Sms < Notification
  attr_reader :enrollment_status

  def should_send?
    super(enrollment_status)
    # a method call dealing with logic specific to text messages would go here
  end
end

class PhoneCall < Notification
  attr_reader :enrollment_status

  def should_send?
    super(enrollment_status)
    # a method call dealing with logic specific to phone call would go here
  end
end

这个例子是行不通的,但是,想象一下还有很多 Notification 子类,并且添加false if user.unenrolled?到每个子类中并不是很枯燥。但是,每个子类也将实现自己的自定义逻辑。一个关键的考虑因素是父通知检查需要取代子类中的自定义逻辑。换句话说,如果父方法调用返回 true,则遵循子方法调用中的结果,如果父调用返回 false,则无论自定义逻辑如何,原始子方法调用都应返回 false。

一些注意事项/问题:

标签: ruby

解决方案


做你所要求的:

class Notification
  attr_reader :enrollment_status

  def should_send?
    !!enrollment_status
  end
end

class Sms < Notification
  def should_send?
    super && call_sms_method
  end
end

class PhoneCall < Notification
  def should_send?
    super && call_phone_method
  end
end

推荐阅读