Created
September 30, 2011 22:28
-
-
Save thegrubbsian/1255175 to your computer and use it in GitHub Desktop.
Mongoid Numeric Identity Module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mongoid | |
module NumericIdentity | |
module InstanceMethods | |
def generate_identity | |
id_attempt = (self.class.last.try(:id) || 0) + 1 | |
dup_check = self.class.where(:id => id_attempt).first | |
if dup_check.nil? | |
self.id = id_attempt | |
else | |
generate_identity | |
end | |
end | |
end | |
module ClassMethods | |
def id(id) | |
return any_in(:_id => id) if id.kind_of? Array | |
return where(:_id => id) | |
end | |
end | |
def self.included(base) | |
base.send :include, InstanceMethods | |
base.send :extend, ClassMethods | |
base.before_create :generate_identity | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment