class MongoidAutoIncrement::Incrementor::Sequence
Public Class Methods
new(sequence, collection_name, seed, step, scope)
click to toggle source
# File lib/mongoid_auto_increment/incrementor.rb, line 6 def initialize(sequence, collection_name, seed, step, scope) @sequence = sequence.to_s @collection = collection_name.to_s @scope = scope || {} exists? || create(seed) @step = step.to_i end
Public Instance Methods
current()
click to toggle source
# File lib/mongoid_auto_increment/incrementor.rb, line 29 def current if defined?(::Mongoid::VERSION) && ::Mongoid::VERSION >= '3' collection.find(query).one['number'] else collection.find_one(query)['number'] end end
inc()
click to toggle source
# File lib/mongoid_auto_increment/incrementor.rb, line 14 def inc if defined?(::Mongoid::VERSION) && ::Mongoid::VERSION >= '5' collection.find(query).find_one_and_update({ '$inc' => { number: @step } }, new: true, upsert: true, return_document: :after)['number'] elsif defined?(::Mongoid::VERSION) && ::Mongoid::VERSION >= '3' collection.find(query).modify({ '$inc' => { number: @step } }, new: true, upsert: true)['number'] else opts = { 'query' => query, 'update' => { '$inc' => { 'number' => @step } }, 'new' => true # return the modified document } collection.find_and_modify(opts)['number'] end end
Private Instance Methods
collection()
click to toggle source
# File lib/mongoid_auto_increment/incrementor.rb, line 51 def collection if defined?(::Mongoid::VERSION) && ::Mongoid::VERSION >= '5' Mongoid.default_client[@collection] elsif defined?(::Mongoid::VERSION) && ::Mongoid::VERSION >= '3' Mongoid.default_session[@collection] else Mongoid.database[@collection] end end
create(number)
click to toggle source
# File lib/mongoid_auto_increment/incrementor.rb, line 43 def create(number) if ::Mongoid::VERSION >= '5' collection.insert_one(query.merge('number' => number)) else collection.insert(query.merge('number' => number)) end end
exists?()
click to toggle source
# File lib/mongoid_auto_increment/incrementor.rb, line 39 def exists? collection.find(query).count > 0 end
query()
click to toggle source
# File lib/mongoid_auto_increment/incrementor.rb, line 61 def query @scope.merge('seq_name' => @sequence) end