Module: Mongoid::Autoinc::ClassMethods

Defined in:
lib/autoinc.rb

Overview

Mongoid::Autoinc class methods to allow for autoincrementing fields.

Instance Method Summary collapse

Instance Method Details

#incrementing_fieldsHash

Returns all incrementing fields of the document

Examples:

class Invoice
  include Mongoid::Document
  include Mongoid::Autoinc

  field :number, type: Integer
  increments :number
end
Invoice.incrementing_fields # => {number: {auto: true}}

Returns:

  • (Hash)

    Hash with fields and their autoincrement options



39
40
41
42
43
44
45
# File 'lib/autoinc.rb', line 39

def incrementing_fields
  if superclass.respond_to?(:incrementing_fields)
    @incrementing_fields ||= superclass.incrementing_fields.dup
  else
    @incrementing_fields ||= {}
  end
end

#increments(field, options = {}) ⇒ Object

Set an autoincrementing field for a Mongoid::Document

Examples:

class Invoice
  include Mongoid::Document
  include Mongoid::Autoinc

  field :number, type: Integer
  increments :number
end
class User
  include Mongoid::Document
  include Mongoid::Autoinc

  field :number, type: Integer
  increments :number, auto: false
end

Parameters:

  • field (Symbol)

    The name of the field to apply autoincrement to

  • options (Hash) (defaults to: {})

    The options to pass to that field



69
70
71
72
# File 'lib/autoinc.rb', line 69

def increments(field, options = {})
  incrementing_fields[field] = options.reverse_merge!(auto: true)
  attr_protected(field) if respond_to?(:attr_protected)
end