Class: Mongoid::Identity

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

Constant Summary collapse

MAII_TABLE_NAME =
'mongoid.auto_increment_ids'.freeze

Class Method Summary collapse

Class Method Details

.generate_id(document) ⇒ Object

Generate auto increment id params:


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mongoid_auto_increment_id.rb', line 14

def generate_id(document)
  if AutoIncrementId.cache_enabled?
    cache_key = self.maii_cache_key(document)
    if ids = Mongoid::AutoIncrementId.cache_store.read(cache_key)
      cached_id = self.shift_id(ids, cache_key)
      return cached_id if !cached_id.blank?
    end
  end

  opts = {
    findAndModify: MAII_TABLE_NAME,
    query: { _id: document.collection_name },
    update: { '$inc' => { c: AutoIncrementId.seq_cache_size } },
    upsert: true,
    new: true
  }
  o = Mongoid.default_client.database.command(opts, {})

  last_seq = o.documents[0]['value']['c'].to_i

  if AutoIncrementId.cache_enabled?
    ids = ((last_seq - AutoIncrementId.seq_cache_size) + 1 .. last_seq).to_a
    self.shift_id(ids, cache_key)
  else
    last_seq
  end
end

.maii_cache_key(document) ⇒ Object


49
50
51
# File 'lib/mongoid_auto_increment_id.rb', line 49

def maii_cache_key(document)
  "maii-seqs-#{document.collection_name}"
end

.shift_id(ids, cache_key) ⇒ Object


42
43
44
45
46
47
# File 'lib/mongoid_auto_increment_id.rb', line 42

def shift_id(ids, cache_key)
  return nil if ids.blank?
  first_id = ids.shift
  AutoIncrementId.cache_store.write(cache_key, ids)
  first_id
end