class Mongoid::Identity

Constants

MAII_TABLE_NAME

Public Class Methods

generate_id(document) click to toggle source

Generate auto increment id params:

# 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) click to toggle source
# 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) click to toggle source
# 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