首页
/ 开源项目 `after_commit_everywhere` 使用教程

开源项目 `after_commit_everywhere` 使用教程

2024-08-27 10:28:38作者:滕妙奇

项目介绍

after_commit_everywhere 是一个 Ruby 库,允许在 ActiveRecord 模型之外的任何地方使用 ActiveRecord 的事务性回调(如 after_commitbefore_commitafter_rollback)。这个库特别适用于需要在事务提交后执行某些操作的场景,即使这些操作不在 ActiveRecord 模型内部。

项目快速启动

安装

首先,将以下行添加到你的应用程序的 Gemfile 中:

gem 'after_commit_everywhere'

然后执行:

$ bundle

或者手动安装:

$ gem install after_commit_everywhere

使用示例

推荐的使用方式是将其包含到你的基础服务类或其他类中:

class ServiceObjectBtw
  include AfterCommitEverywhere

  def call
    ActiveRecord::Base.transaction do
      # 你的事务代码
      after_commit { puts "We're all done!" }
    end
  end
end

或者在需要时直接扩展它:

extend AfterCommitEverywhere

ActiveRecord::Base.transaction do
  # 你的事务代码
  after_commit { puts "We're all done!" }
end

应用案例和最佳实践

应用案例

假设你有一个需要在事务提交后发送通知的服务对象:

class NotificationService
  include AfterCommitEverywhere

  def send_notification(user)
    ActiveRecord::Base.transaction do
      # 更新用户数据
      user.update(status: 'updated')

      after_commit do
        NotificationMailer.notify(user).deliver_later
      end
    end
  end
end

最佳实践

  1. 避免在模型中过度使用:虽然可以在模型中使用,但过度使用可能会导致模型职责过多。建议将这些回调逻辑移至服务对象或其他专用层。
  2. 确保事务正确嵌套after_commit_everywhere 支持嵌套事务,确保在所有事务完成后执行回调。

典型生态项目

after_commit_everywhere 通常与其他 Ruby on Rails 生态项目一起使用,例如:

  • ActiveJob:用于在事务提交后异步执行任务。
  • Sidekiq:一个强大的后台任务处理库,可以与 after_commit_everywhere 结合使用,确保任务在事务提交后执行。

这些生态项目可以增强 after_commit_everywhere 的功能,使其更加强大和灵活。

登录后查看全文
热门项目推荐