Class: Mongoid::Autoinc::Incrementor

Inherits:
Object
  • Object
show all
Defined in:
lib/autoinc/incrementor.rb

Overview

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_name, field_name, options = {}) ⇒ Incrementor

Creates a new incrementor object for the passed field_name

Parameters:

  • model_name (String)

    Part of the name of the increment key

  • field_name (String)

    The name of the field to increment

  • options (Hash) (defaults to: {})

    Options to pass to the incrementer



31
32
33
34
35
36
37
38
39
# 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

Instance Attribute Details

#collectionObject (readonly)

The mongo connection to the autoincrement counters collection.



17
18
19
# File 'lib/autoinc/incrementor.rb', line 17

def collection
  @collection
end

#field_nameObject (readonly)

The name of the field of the autoincrementing model.



10
11
12
# File 'lib/autoinc/incrementor.rb', line 10

def field_name
  @field_name
end

#model_nameObject (readonly)

The name of the autoincrementing model.



7
8
9
# File 'lib/autoinc/incrementor.rb', line 7

def model_name
  @model_name
end

#scope_keyObject (readonly)

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



14
15
16
# File 'lib/autoinc/incrementor.rb', line 14

def scope_key
  @scope_key
end

#seedObject (readonly)

The autoincrement offset.



20
21
22
# File 'lib/autoinc/incrementor.rb', line 20

def seed
  @seed
end

#stepObject (readonly)

How the next autoincrement number should be calculated.



23
24
25
# File 'lib/autoinc/incrementor.rb', line 23

def step
  @step
end

Instance Method Details

#incInteger

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

Returns:

  • (Integer)

    The next value of the incrementor



52
53
54
# 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

#keyString

Returns the increment key

Returns:

  • (String)

    The key to increment



44
45
46
47
# 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