Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Addon for Mongoid to allow optimistic locking (CAS)
Ruby
branch: master

This branch is 30 commits behind burgalon:master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
spec
.gitignore
Gemfile
LICENSE
README.md
Rakefile
mongoid_optimistic_locking.gemspec

README.md

mongoid_optimistic_locking

This gem helps to abstract "Update if current" method which may be used as a replacement for transactions in Mongo The gem is an addon over Mongoid ODM.

Compatibility

So far it works with the Rails 3 and Mongoid 2.4.

Rails 3 Installation

Add the gem to your gemfile

gem 'mongoid_optimistic_locking'

Usage

To use it, all you have to do is add include Mongoid::Lockable

class Post
  include Mongoid::Document
  include Mongoid::Lockable

  field :text
end

This will add a _lock_version field in the document which will be incremented every time a save is called. In order a to save a document in a save manner, use the new save_optimistic! and rescue Mongoid::Errors::StaleDocument to handle applicative logic in case the object was changed.

For example:

class PostController < ApplicationController
    ## Adds an "UPDATE: ...some text..." to an existing document
    def add_update
        begin
            post = Post.find(params[:id])
            post.text += "---UPDATE---  " + params[:more_text]
            post.save_optimistic!!
        rescue Mongoid::Errors::StaleDocument
            retry
        end
    end
end

That's it

Open sourced by

Boxee

References

Mongo Developer FAQ - How do I do transactions/locking?

Mongo Atomic Operations - "Update if Current"

Something went wrong with that request. Please try again.