Module: Libis::Workflow::Mongoid::Sequence::ClassMethods

Defined in:
lib/libis/workflow/mongoid/sequence.rb

Overview

noinspection ALL

Instance Method Summary collapse

Instance Method Details

#reset_sequence(_field, value = 0) ⇒ Object



49
50
51
# File 'lib/libis/workflow/mongoid/sequence.rb', line 49

def reset_sequence(_field, value = 0)
  seq_upsert(counter_id(_field), {'$set' => {'value' => value}})
end

#sequence(_field, prefix = nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/libis/workflow/mongoid/sequence.rb', line 23

def sequence(_field, prefix = nil)
  # REPLACE FIELD DEFAULT VALUE
  _field = _field.to_s
  options = fields[_field].options.merge(
      default: lambda {
        self.class.set_from_sequence(_field, prefix)
      },
      pre_processed: false,
      overwrite: true
  )
  (options.keys - ::Mongoid::Fields::Validators::Macro::OPTIONS).each { |key| options.delete key }
  field(_field, options)
end

#set_from_sequence(_field, prefix) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/libis/workflow/mongoid/sequence.rb', line 37

def set_from_sequence(_field, prefix)
  # Increase the sequence value and also avoids conflicts
  catch(:value) do
    value = nil
    begin
      value = seq_upsert(counter_id(_field), {'$inc' => {'value' => 1}}).send('[]', 'value')
      value = "#{prefix.is_a?(Proc) ? instance_eval(prefix.call) : prefix}_#{value}" if prefix
    end until self.where(_field => value).count == 0
    throw :value, value
  end
end