class Mongoid::Autoinc::Incrementor

Object which wraps the mongodb operations needed to allow for autoincrementing fields in Mongoid::Document models.

Attributes

collection[R]

The mongo connection to the autoincrement counters collection.

field_name[R]

The name of the field of the autoincrementing model.

model_name[R]

The name of the autoincrementing model.

scope_key[R]

The constraint, allowing for more then one series on the same model_name field_name combination.

seed[R]

The autoincrement offset.

step[R]

How the next autoincrement number should be calculated.

Public Class Methods

new(model_name, field_name, options = {}) click to toggle source

Creates a new incrementor object for the passed field_name

@param [ String ] model_name Part of the name of the increment key @param [ String ] field_name The name of the field to increment @param [ Hash ] options Options to pass to the incrementer

# File lib/autoinc/incrementor.rb, line 31
def initialize(model_name, field_name, options = {})
  @model_name = model_name.to_s
  @field_name = field_name.to_s
  @scope_key = options.fetch(:scope, nil)
  @step = options.fetch(:step, 1)
  @seed = options.fetch(:seed, nil)
  @collection = ::Mongoid.default_client['auto_increment_counters']
  create if @seed && !exists?
end

Public Instance Methods

inc() click to toggle source

Increments the value of the key and returns it using an atomic op

@return [ Integer ] The next value of the incrementor

# File lib/autoinc/incrementor.rb, line 52
def inc
  find.find_one_and_update({'$inc' => {c: step}}, upsert: true, return_document: :after).fetch('c')
end
key() click to toggle source

Returns the increment key

@return [ String ] The key to increment

# File lib/autoinc/incrementor.rb, line 44
def key
  return "#{model_name.underscore}_#{field_name}" if scope_key.blank?
  "#{model_name.underscore}_#{field_name}_#{scope_key}"
end

Private Instance Methods

create() click to toggle source

Persists the incrementor using key as id and seed as value of c.

# File lib/autoinc/incrementor.rb, line 67
def create
  collection.insert_one(_id: key, c: seed)
end
exists?() click to toggle source

Checks if the incrementor is persisted

@return [ true, false ] If the incrementor is already persisted.

# File lib/autoinc/incrementor.rb, line 74
def exists?
  find.count > 0
end
find() click to toggle source

Find the incrementor document, using the key id.

@return [ Hash ] The persisted version of this incrementor.

# File lib/autoinc/incrementor.rb, line 61
def find
  collection.find(_id: key)
end