Mongoid::Locking
It adds Optimistic Locking to Mongoid::Document
objects.
This gem is inspired in the ActiveRecord::Locking module.
Installation
Install the gem and add to the application's Gemfile by executing:
$ bundle add mongoid-locking
If bundler is not being used to manage dependencies, install the gem by executing:
$ gem install mongoid-locking
Usage
- Include
Mongoid::Locking
module
class Order
include Mongoid::Document
include Mongoid::Locking
end
- Handle
Mongoid::StaleObjectError
when performing updates
# ...
def update_order
Order.update(attributes)
rescue Mongoid::StaleObjectError => e
add_error("This order has been changed ...")
end
end
- Use
with_locking
to automatically handleMongoid::StaleObjectError
By default, with_locking
will retry the update 3 times in case of a
Mongoid::StaleObjectError
.
def process_with_locking
Order.with_locking do
# Ensure the block is idempotent
# Reload object(s) within the block to get the latest changes
order.reload
# Your code here
# ...
end
end
Adjust the max_retries
parameter to control the number of retry attempts in
case of a Mongoid::StaleObjectError
.
# ...
def update_order
order.with_locking(max_retries: 2) do
order.update(attributes)
end
end
end
- Use
with_locking
at the instance level to automatically reload the instance on each retry
def process_with_locking
order.with_locking do
# The instance is automatically reloaded for each retry
# Your code here
# ...
end
end
The with_locking method at the instance level combines class-level locking with automatic reloading on each retry. This ensures that the instance reflects the latest changes, providing seamless control over optimistic locking.
NOTE: The with_locking
method will add a delay between retries to avoid
contention. More info.
Development
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
. To release a new version, update the version number in version.rb
, and then run bundle exec rake release
, which will create a git tag for the version, push git commits and the created tag, and push the .gem
file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/fullhealthmedical/fhweb/mongoid-locking. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
License
The gem is available as open source under the terms of the MIT License.
Code of Conduct
Everyone interacting in the Mongoid::Locking project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.
Version Compability
Gem version | Mongoid version |
---|---|
0.1.2 | >= 6.0, < 7.2 |
1.0.0 | ~> 7.2.0 |
~> 1.1.0 | ~> 7.2 |