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, scope_key = nil, seed = nil) ⇒ Incrementor

Returns a new instance of Incrementor.



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

def initialize(model_name, field_name, scope_key=nil, seed=nil)
  self.model_name = model_name
  self.field_name = field_name.to_s
  self.scope_key = scope_key
  self.collection = ::Mongoid.default_session['auto_increment_counters']
  self.seed = seed
  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

Instance Method Details

#incObject



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

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

#keyObject



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

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