Class: MongomapperId2::Incrementor::Sequence

Inherits:
Object
  • Object
show all
Defined in:
lib/incrementor.rb

Instance Method Summary collapse

Constructor Details

#initialize(sequence) ⇒ Sequence

Returns a new instance of Sequence.



5
6
7
8
# File 'lib/incrementor.rb', line 5

def initialize(sequence)
  @sequence = sequence.to_s
  exists? || create
end

Instance Method Details

#collectionObject



18
19
20
# File 'lib/incrementor.rb', line 18

def collection
  db['sequences']
end

#create(number = 0) ⇒ Object



27
28
29
# File 'lib/incrementor.rb', line 27

def create(number = 0)
  collection.insert(query.merge({ "number" => number }))
end

#currentObject



21
22
23
# File 'lib/incrementor.rb', line 21

def current
  collection.find_one(query)["number"]
end

#dbObject



12
13
14
# File 'lib/incrementor.rb', line 12

def db
  MongoMapper.database # replace this if you're not using MongoMapper
end

#exists?Boolean

Returns:

  • (Boolean)


9
10
11
# File 'lib/incrementor.rb', line 9

def exists?
  collection.find(query).count > 0
end

#incObject



24
25
26
# File 'lib/incrementor.rb', line 24

def inc
  update_number_with("$inc" => { "number" => 1 })
end

#queryObject



15
16
17
# File 'lib/incrementor.rb', line 15

def query
  { "seq_name" => @sequence }
end

#set(number) ⇒ Object



30
31
32
# File 'lib/incrementor.rb', line 30

def set(number)
  update_number_with("$set" => { "number" => number })
end

#update_number_with(mongo_func) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/incrementor.rb', line 33

def update_number_with(mongo_func)
  opts = {
    "query"  => query,
    "update" => mongo_func,
    "new"    => true # return the modified document
  }
  collection.find_and_modify(opts)["number"]
end