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 =
"4.0.0"

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



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

def evaluate_scope(scope)
  case scope
  when Symbol then send(scope)
  when Proc then instance_exec &scope
  else raise 'scope is not a Symbol or a Proc'
  end
end

#evaluate_step(step) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/autoinc.rb', line 63

def evaluate_step(step)
  case step
  when Integer then step
  when Proc then evaluate_step_proc(step)
  else raise 'step is not an Integer or a Proc'
  end
end

#evaluate_step_proc(step_proc) ⇒ Object



71
72
73
74
75
# File 'lib/autoinc.rb', line 71

def evaluate_step_proc(step_proc)
  result = instance_exec &step_proc
  return result if result.is_a? Integer
  raise 'step Proc does not evaluate to an Integer'
end

#increment!(field, options) ⇒ Object



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

def increment!(field, options)
  options = options.dup
  model_name = (options.delete(:model_name) || self.class.model_name).to_s
  options[:scope] = evaluate_scope(options[:scope]) if options[:scope]
  options[:step] = evaluate_step(options[:step]) if options[:step]
  write_attribute(
      field.to_sym, Mongoid::Autoinc::Incrementor.new(model_name, field, options).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