Allows to use ActiveRecord transactional callbacks outside of ActiveRecord models, literally everywhere in your application.
Inspired by these articles:
- https://evilmartians.com/chronicles/rails-after_commit-everywhere
- https://blog.arkency.com/2015/10/run-it-in-background-job-after-commit/
after_commit_everywhere is built by Evil Martians, an American design and engineering consultancy for developer tools, AI, and cybersecurity startups.
Add this line to your application's Gemfile:
gem'after_commit_everywhere'And then execute:
$ bundle
Or install it yourself as:
$ gem install after_commit_everywhere
Recommended usage is to include it to your base service class or anything:
classServiceObjectBtwincludeAfterCommitEverywheredefcallActiveRecord::Base.transactiondoafter_commit{puts"We're all done!"}endendendOr just extend it whenever you need it:
extendAfterCommitEverywhereActiveRecord::Base.transactiondoafter_commit{puts"We're all done!"}endOr call it directly on module:
AfterCommitEverywhere.after_commit{puts"We're all done!"}That's it!
But the main benefit is that it works with nested transaction blocks (may be even spread across many files in your codebase):
includeAfterCommitEverywhereActiveRecord::Base.transactiondoputs"We're in transaction now"ActiveRecord::Base.transactiondoputs"More transactions"after_commit{puts"We're all done!"}endputs"Still in transaction…"endWill output:
We're in transaction now
More transactions
Still in transaction…
We're all done!
Will be executed right after outermost transaction have been successfully committed and data become available to other DBMS clients.
If called outside transaction will execute callback immediately.
Will be executed right before outermost transaction will be commited (I can't imagine use case for it but if you can, please open a pull request or issue).
If called outside transaction will execute callback immediately.
Supported only starting from ActiveRecord 5.0.
Will be executed right after transaction in which it have been declared was rolled back (this might be nested savepoint transaction block with requires_new: true).
If called outside transaction will raise an exception!
Please keep in mind ActiveRecord's limitations for rolling back nested transactions. See in_transaction for a workaround to this limitation.
Makes sure the provided block is running in a transaction.
This method aims to provide clearer intention than a typical ActiveRecord::Base.transaction block - in_transaction only cares that some transaction is present, not that a transaction is nested in any way.
If a transaction is present, it will yield without taking any action. Note that this means ActiveRecord::Rollback errors will not be trapped by in_transaction but will propagate up to the nearest parent transaction block.
If no transaction is present, the provided block will open a new transaction.
classServiceObjectBtwincludeAfterCommitEverywheredefcallin_transactiondoan_updateanother_updateafter_commit{puts"We're all done!"}endendendOur service object can run its database operations safely when run in isolation.
ServiceObjectBtw.new.call# This opens a new #transaction blockIf it is later called from code already wrapped in a transaction, the existing transaction will be utilized without any nesting:
ActiveRecord::Base.transactiondonew_updatenext_update# This no longer opens a new #transaction block, because one is already presentServiceObjectBtw.new.callendThis can be called directly on the module as well:
AfterCommitEverywhere.in_transactiondoAfterCommitEverywhere.after_commit{puts"We're all done!"}endReturns true when called inside an open transaction, false otherwise.
defcheck_for_transactionifin_transaction?puts"We're in a transaction!"elseputs"We're not in a transaction..."endendcheck_for_transaction# => prints "We're not in a transaction..."in_transactiondocheck_for_transactionend# => prints "We're in a transaction!"without_txallows to change default callback behavior if called without transaction open.Available values:
:executeto execute callback immediately:warn_and_executeto print warning and execute immediately:raiseto raise an exception instead of executing
prependputs the callback at the head of the callback chain, instead of at the end.
Yes.
While it is convenient to have after_commit method at a class level to be able to call it from anywhere, take care not to call it on models.
So, DO NOT DO THIS:
classPost < ActiveRecord::Basedefself.bulk_opsfind_eachdoafter_commit{raise"Some doesn't expect that this screw up everything, but they should"}endendendBy calling the class level after_commit method on models, you're effectively adding callback for all Post instances, including future ones.
See #13 for details.
In class-level methods call AfterCommitEverywhere.after_commit directly:
classPost < ActiveRecord::Basedefself.bulk_opsfind_eachdoAfterCommitEverywhere.after_commit{puts"Now it works as expected!"}endendendFor usage in instance-level methods include this module to your model class (or right into your ApplicationRecord):
classPost < ActiveRecord::BaseincludeAfterCommitEverywheredefdo_some_stuffafter_commit{puts"Now it works!"}endendHowever, if you do something in models that requires defining such ad-hoc transactional callbacks, it may indicate that your models have too many responsibilities and these methods should be extracted to separate specialized layers (service objects, etc).
After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install.
Bump version number in
lib/after_commit_everywhere/version.rbIn case of pre-releases keep in mind rubygems/rubygems#3086 and check version with command like
Gem::Version.new(AfterCommitEverywhere::VERSION).to_sFill
CHANGELOG.mdwith missing changes, add header with version and date.Make a commit:
git add lib/after_commit_everywhere/version.rb CHANGELOG.md version=$(ruby -r ./lib/after_commit_everywhere/version.rb -e "puts Gem::Version.new(AfterCommitEverywhere::VERSION)") git commit --message="${version}: " --edit
Create annotated tag:
git tag v${version} --annotate --message="${version}: " --edit --sign
Fill version name into subject line and (optionally) some description (list of changes will be taken from
CHANGELOG.mdand appended automatically)Push it:
git push --follow-tags
GitHub Actions will create a new release, build and push gem into rubygems.org! You're done!
Bug reports and pull requests are welcome on GitHub at https://github.com/Envek/after_commit_everywhere.
The gem is available as open source under the terms of the MIT License.