Skip to content

Instantly share code, notes, and snippets.

@blt04
Created January 27, 2011 16:40
Show Gist options
  • Save blt04/798759 to your computer and use it in GitHub Desktop.
Save blt04/798759 to your computer and use it in GitHub Desktop.
Manual Versioning for Mongoid 2.0
module Mongoid #:nodoc:
# Include this module to get manual versioning of root level documents.
# This will add a version field to the +Document+ and a has_many association
# with all the versions contained in it.
# Unlike Mongoid::Versioning, you must manually increment the version field
# when you want to bump versions
module Versioning
module Manual
extend ActiveSupport::Concern
include Mongoid::Versioning
# Create a new version of the +Document+. This will load the previous
# document from the database and set it as the next version before saving
# the current document. It then increments the version number. If a #max_versions
# limit is set in the model and it's exceeded, the oldest version gets discarded.
def revise
if @modifications.has_key?('version')
last_version = self.class.first(:conditions => { :_id => id, :version => @modifications['version'][0] })
if last_version
versions.target << last_version.clone
versions.shift if version_max.present? && versions.length > version_max
@modifications['versions'] = [ nil, versions.as_document ] if @modifications
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment