Active Record Suppressor¶ ↑
ActiveRecord::Suppressor 可阻止在给定的代码块中保存接收对象。
例如,当发布新评论时,创建通知的模式如下。(通知可能会触发电子邮件、推送通知,或仅显示在 UI 的某个位置)
class Comment < ActiveRecord::Base belongs_to :commentable, polymorphic: true after_create -> { Notification.create! comment: self, recipients: commentable.recipients } end
大多数情况下,您都希望如此。新评论会创建一个新的通知。但有时也可能出现例外情况,例如复制一个可评论对象及其评论,这时您可能不希望创建通知。因此,您会有一个类似这样的关注点
module Copyable def copy_to(destination) Notification.suppress do # Copy logic that creates new comments that we do not want # triggering notifications. end end end
命名空间