Module: Mongoid::Autoinc

Extended by:
ActiveSupport::Concern
Defined in:
lib/autoinc.rb,
lib/autoinc/version.rb,
lib/autoinc/incrementor.rb

Defined Under Namespace

Modules: ClassMethods Classes: Incrementor

Constant Summary collapse

AlreadyAssignedError =
Class.new(StandardError)
AutoIncrementsError =
Class.new(StandardError)
VERSION =
"0.5.1"

Instance Method Summary collapse

Instance Method Details

#assign!(field) ⇒ Object



32
33
34
35
36
37
# File 'lib/autoinc.rb', line 32

def assign!(field)
  options = self.class.incrementing_fields[field]
  raise AutoIncrementsError if options[:auto]
  raise AlreadyAssignedError if send(field).present?
  increment!(field, options)
end

#evaluate_scope(scope) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/autoinc.rb', line 54

def evaluate_scope(scope)
  if scope.is_a? Symbol
    send(scope)
  elsif scope.is_a? Proc
    instance_exec &scope
  else
    raise 'scope is not a Symbol or a Proc'
  end
end

#increment!(field, options) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/autoinc.rb', line 45

def increment!(field, options)
  scope_key = options[:scope] ? evaluate_scope(options[:scope]) : nil
  seed = options[:seed]
  write_attribute(
      field.to_sym, Mongoid::Autoinc::Incrementor.new(
      self.class.model_name, field, scope_key, seed).inc
  )
end

#update_auto_incrementsObject



39
40
41
42
43
# File 'lib/autoinc.rb', line 39

def update_auto_increments
  self.class.incrementing_fields.each do |field, options|
    increment!(field, options) if options[:auto]
  end
end