Mongoid Versioning
Versioning of Mongoid documents. Past versions are stored in separate collection.
This gem is intended for versioning of whole documents. However, it might be possible to extend its support to embedded documents as well. Pull requests are welcome.
Installation
Add this line to your application's Gemfile:
gem 'mongoid_versioning'And then execute:
$ bundle
Or install it yourself as:
$ gem install mongoid_versioning
Usage
Include the MongoidVersioning::Versioned module into your model:
class MyVersionedDocument
include Mongoid::Document
include MongoidVersioning::Versioned
endYour class will then have:
field :_version, type: Integer
field :_based_on_version, type: IntegerCreating versions
To create new version of your document:
doc = MyVersionedDocument.new
doc.revise # => true
doc._version # => 1
doc._based_on_version # => nilThe #revise method validates the document and runs :revise, :save and :update callbacks. (Please note that running #revise on new document will resort to standard #save.)
A #revise! method, raising Mongoid::Errors::Validations and Mongoid::Errors::Callbacks exceptions, is also available.
Retrieving versions
To access all previous versions:
doc.previous_versions # => Mongoid::CriteriaThese versions are stored in separate collection, by default named by appending .versions to name of the source collection. In the above example it is my_versioned_documents.versions.
To access latest version (as stored in the db):
doc.latest_version # => MyVersionedDocumentTo retrieve all versions of a document:
doc.versions # => ArrayTo retrieve specific version:
doc.version(2) # => MyVersionedDocumentRemoving versions
By default, past versions are never removed. This way it is possible to implement some sort of recovery mechanism of deleted documents.
It should be however trivial to implement removal of versions on destroy. For example:
after_destroy -> doc { doc.previous_versions.destroy_all }Further Reading
See Further Thoughts on How to Track Versions with MongoDB.
Contributing
- Fork it ( https://github.com/tomasc/mongoid_versioning/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request