百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
A

ar_after_transaction

> 编程语言
开源

只有在事务未回滚时才执行不可逆操作

159 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

只有在事务未回滚时才执行不可逆操作

Do something only after the currently open transactions have finished.

Normally everything gets rolled back when a transaction fails, but you cannot roll back sending an email or adding a job to Resque.

Install

bash
gem install ar_after_transaction

Usage

just-in-time callbacks

ruby
class User
  after_create :do_stuff, :oops

  def do_stuff
    after_transaction do
      send_an_email # cannot be rolled back
    end
    comments.create(...) # will be rolled back
  end

  def oops
    raise "do the rolback!"
  end
end

General 'this should be rolled back when in a transaction' code like jobs

ruby
class Resque
  def revertable_enqueue(*args)
    ActiveRecord::Base.after_transaction do
      enqueue(*args)
    end
  end
end

When not in a transaction

after_transaction will perform the given block immediately

Transactional fixtures normally_open_transactions

after_transaction assumes zero open transactions.

If you use transactional fixtures you should change it in test mode.

Rspec:

ruby
# spec/rails_helper.rb
  config.before(:suite) do
    ActiveRecord::Base.normally_open_transactions = 1
  end

Adding new rails versions

  • bump in ar_after_transaction.gemspec
  • create a new gemfiles/.gemfile
  • BUNDLE_GEMFILE=gemfiles/.gemfile bundle
  • BUNDLE_GEMFILE=gemfiles/.gemfile bundle exec rake
  • update .github/workflows/actions.yml
  • make a PR

Alternative

Rails 3+

  • basic support is built in, use it if you can!
  • after_commit :foo
  • after_commit :bar, on: :create / :update
  • after_commit everywhere

after_commit

  • pro: threadsafe

  • pro: more fine-grained callbacks (before_commit, after_commit, before_rollback, after_rollback)

  • con: doesn't let you define after_transaction callbacks anywhere like ar_after_transaction does (outside of the after_commit, etc. callbacks which only happen at certain points in the model's life cycle)

  • con: more complex

Authors

Original idea and code from Jamis Buck (post by Jeremy Kemper)

Contributors

  • Bogdan Gusiev
  • Benedikt Deicke
  • Tyler Rick
  • Michael Wu
  • C.W.
  • Ben Weintraub
  • Vladimir Temnikov
  • Mark Gangl
  • Alex Vondrak

Michael Grosser

[email protected]

License: MIT

Issues· 1 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言