Module: Cowtech::RubyOnRails::Models::Mongoid::Sequence::ClassMethods

Defined in:
app/models/cowtech/ruby_on_rails/models/mongoid/sequence.rb

Instance Method Summary collapse

Instance Method Details

#reset_sequence(_field) ⇒ Object



49
50
51
52
53
# File 'app/models/cowtech/ruby_on_rails/models/mongoid/sequence.rb', line 49

def reset_sequence(_field)
	sequences = self.db.collection("__sequences")
	counter_id = "#{self.class.name.underscore}_#{_field.to_s}"
	sequences.find_and_modify(query: {"_id" => counter_id}, :update=> {"$set" => {"value" => 0}}, new: true, upsert: true)
end

#sequence(_field) ⇒ Object



24
25
26
27
28
# File 'app/models/cowtech/ruby_on_rails/models/mongoid/sequence.rb', line 24

def sequence(_field)
	# REPLACE FIELD DEFAULT VALUE
	_field = _field.to_s
	field(_field, fields[_field].options.merge(default: lambda{ self.class.set_from_sequence(_field)}))
end

#set_from_sequence(_field) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'app/models/cowtech/ruby_on_rails/models/mongoid/sequence.rb', line 30

def set_from_sequence(_field)
	sequences = self.db.collection("__sequences")
	counter_id = "#{self.class.name.underscore}_#{_field}"

	# Increase the sequence value and also avoids conflicts
	catch(:value) do
		value = nil
		begin
			value = sequences.find_and_modify(
				query: {"_id" => counter_id},
					:update=> {"$inc" => {"value" => 1}},
					new: true,
					upsert: true
			).send("[]", "value")
		end while self.first({conditions: {_field => value}})
		throw :value, value
	end
end