mongoid-autoinc

Versions

Use 0.1.3 for mongoid 2.0

use 0.3.0 for mongoid 3.0

A mongoid plugin to add auto incrementing fields to your documents.

<img src=“https://secure.travis-ci.org/80beans/mongoid-autoinc.png” /> <img src=“https://codeclimate.com/badge.png” />

Installation

in gemfile:

gem 'mongoid-autoinc'

in class:

require 'autoinc'

Usage

# app/models/user.rb
class User
  include Mongoid::Document
  include Mongoid::Autoinc
  field :name
  field :number, :type => Integer

  increments :number
end

user = User.create(:name => 'Dr. Percival "Perry" Ulysses Cox')
user.id # BSON::ObjectId('4d1d150d30f2246bc6000001')
user.number # 1

another_user = User.create(:name => 'Bob Kelso')
another_user.number # 2

Scopes

You can scope on document fields. For example:

class PatientFile
  include Mongoid::Document
  include Mongoid::Autoinc

  field :name
  field :number, :type => Integer

  increments :number, :scope => :patient_id

  belongs_to :patient

end

Scope can also be a Proc:

increments :number, :scope => lambda { patient.name }

Custom Increment Trigger

You can trigger the assignment of an increment field manually by passing: :auto => false to the increment field. This allows for more flexible assignment of your increment number:

class Intern
  include Mongoid::Document
  include Mongoid::Autoinc

  field :name
  field :number

  increments :number, :auto => false

  after_save :assign_number_to_jd

  protected

  def assign_number_to_jd
    assign!(:number) if number.blank? && name == 'J.D.'
  end

end

Seeds

You can use a seed to start the incrementing field at a given value. The first document created will start at ‘seed + 1`.

class Vehicle
  include Mongoid::Document
  include Mongoid::Autoinc

  field :model
  field :vin

  increments :vin, seed: 1000

end

car = Vehicle.new(model: "Coupe")
car.vin # 1001

Development

$ gem install bundler (if you don't have it)
$ bundle install
$ bundle exec spec

Contributions

Thanks to Johnny Shields (@johnnyshields) for implementing proc support to scopes And to Marcus Gartner (@mgartner) for implementing the seed functionality

See LICENSE for details