ruby - 如何处理来自父(通过超级)和子方法调用的结果?
问题描述
考虑这个笨拙的人为示例:
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。
一些注意事项/问题:
- 我知道这个例子有一些怪癖,这很奇怪,但它公平地代表了现有工作的局限性。
- 是否可以在子方法中执行逻辑之前短路超级方法调用并返回该结果?
- 我应该/可以在超级调用中将整个孩子传递给父母并在那里编写整个逻辑检查吗?
- 我的想法可能在这里,我把这一切都搞混了吗?有没有更好的方法来管理检查孩子和父母的结果?
解决方案
做你所要求的:
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
推荐阅读
- c# - 如何在 asp.net 核心中正确格式化堆栈跟踪信息
- google-cloud-automl - 如何格式化 CSV 文件以将多个文件导入 Google Cloud AutoML Translate?
- reactjs - reactjs中堆叠进度条中的进度条工具提示
- firebase - 使用 Cloud Functions 从节点的每个子节点中删除节点
- winapi - NtWriteFile() 可以产生短写吗?
- java - 使用文件移动操作后,我是否需要在文件描述符上调用同步?
- javascript - 在页面加载后单击带有 Javascript 的按钮/一旦元素加载
- flutter - Flutter - 如何控制圆形进度指示器的边框宽度?
- html - 如何在 HTML/CSS 中编辑按钮的活动颜色
- oracle - Oracle SQL TO_CHAR (num, format) - 尾随零