Class: Mongoid::Autoinc::Incrementor

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Incrementor.



8
9
10
11
12
13
14
15
16
# File 'lib/autoinc/incrementor.rb', line 8

def initialize(model_name, field_name, options={})
  self.model_name = model_name.to_s
  self.field_name = field_name.to_s
  self.scope_key = options[:scope]
  self.step = options[:step] || 1
  self.seed = options[:seed]
  self.collection = ::Mongoid.default_session['auto_increment_counters']
  create if seed && !exists?
end

Instance Attribute Details

#collectionObject

Returns the value of attribute collection.



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

def collection
  @collection
end

#field_nameObject

Returns the value of attribute field_name.



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

def field_name
  @field_name
end

#model_nameObject

Returns the value of attribute model_name.



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

def model_name
  @model_name
end

#scope_keyObject

Returns the value of attribute scope_key.



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

def scope_key
  @scope_key
end

#seedObject

Returns the value of attribute seed.



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

def seed
  @seed
end

#stepObject

Returns the value of attribute step.



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

def step
  @step
end

Instance Method Details

#incObject



25
26
27
28
29
30
31
32
# File 'lib/autoinc/incrementor.rb', line 25

def inc
  collection.find(
    '_id' => key
  ).modify(
    {'$inc' => { 'c' => step }},
    :new => true, :upsert => true
  )['c']
end

#keyObject



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

def key
  "".tap do |str|
    str << "#{model_name.underscore}_#{field_name}"
    str << "_#{scope_key}" unless scope_key.blank?
  end
end