module

Moongoon::Collection::Versioning

Inherits Moongoon::Traits::Database::Versioning

Include this module to enable resource versioning.

Instance methods

count_versions

Counts the number of versions associated with this model.

user = User.new name: "Jane"
user.insert
user.create_version
nb_of_versions = User.count_versions user
Source
create_version

Saves a copy of the model in the history collection and returns the id of the copy.

NOTE: Does not use the model data but reads the latest version from the database before copying.

user = User.new name: "Jane"
user.insert
user.create_version
Source
create_version

Saves a copy with changes of the model in the history collection and returns the id of the copy.

The block argument can be used to alter the model before insertion.

user = User.new name: "Jane", age: 20
user.insert
user.create_version &.tap { |data|
  # "data" is the model representation of the document that gets copied.
  data.key = data.key + 1
}
Source
find_all_versions

Finds all versions of the model and returns an array of Moongoon::Collection instances.

NOTE: Versions are sorted by creation date.

user = User.new name: "Jane"
user.insert
user.create_version
versions = user.find_all_versions
Source
find_latest_version

Finds the latest version of a model and returns an instance of Moongoon::Collection.

Same syntax as Moongoon::Collection#find_by_id, except that specifying the id is not needed.

user = User.new
user.id = "123456"
user_version = user.find_latest_version
Source

Macros

versioning(*, ref_field = nil, auto = false, create_index = false, &transform)

Enable versioning for this collection.

Manages a history in separate mongo collection and adds query methods. The name of the versioning collection is equal to the name of the base collection with a "_history" suffix appended.

NOTE: Documents in the history collection will follow the same data model as the base documents, except for an extra field that will contain a back reference to the base document id.

Arguments

  • ref_field: The name of the reference field that will point to the original document. Defaults to the name of the Class in pascal_case with an "_id" suffix appended.
  • create_index: if set to true, will create an index on the reference field in the history collection.
  • auto: if the auto flag is true, every insertion and update will be recorded. Without the auto flag, a version will only be created programatically when calling the create_version methods.
  • transform: a block that will be executed to transform the BSON document before insertion.
class MyModel < Moongoon::Collection
  include Versioning

  collection "my_model"
  versioning auto: true
end
Source

Nested types