journal of recreational computer science


Roll your own ID scheme with Mongoid

28 May 2012

Suppose, that for some reason the built-in BSON::ObjectId-based identifiers are unfit for what you're trying to do. Perhaps, you'd like them to be uppercase letters, or elements of fibonacci series, or perhaps, in your case you just want to experiment and see what works best. Mongoid will let you easily roll your own ID scheme.

First, you need to tell mongoid about the type of your ID field - the identity class method is used precisely for that purpose.

class Post
  include Mongoid::Document
  include Mongoid::Timestamps

  identity :type => String

  field :title, :type => String
  field :body, :type => String

Next, you'll need to fiddle with the Mongoid::Identity class. Whenever you create a new object and intend to persist it to the database, a new instance gets created, and a new identifier is generated. All you have to do is redefine the generate_id method, and you're done.

class Mongoid::Identity
  Generator = Prime.instance.each

  def generate_id
comments powered by Disqus