Class: MongoAutoIncrement::Identity

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

Overview

Your code goes hereā€¦

Constant Summary collapse

MAII_TABLE_NAME =
'auto_increment_ids'.freeze

Class Method Summary collapse

Class Method Details

.generate_id(document) ⇒ Object

Generate auto increment id params:



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

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

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

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

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

.generated_token(cache_key) ⇒ Object



45
46
47
# File 'lib/mongo_auto_increment.rb', line 45

def generated_token(cache_key)
  return DateTime.now.strftime("%Q").to_i + cache_key
end

.maii_cache_key(document) ⇒ Object



56
57
58
# File 'lib/mongo_auto_increment.rb', line 56

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

.shift_id(ids, cache_key) ⇒ Object



49
50
51
52
53
54
# File 'lib/mongo_auto_increment.rb', line 49

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