Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created January 17, 2012 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahoward/1623766 to your computer and use it in GitHub Desktop.
Save ahoward/1623766 to your computer and use it in GitHub Desktop.
class Code
include Mongoid::Document
field(:name)
field(:codes, :default => [])
validates_presence_of(:name)
validates_uniqueness_of(:name)
index(:name, :unique => true)
Cache = Map.new
class << Code
def for(name)
name = name.to_s
Cache[name] ||= (
begin
create!(:name => name)
rescue
where(:name => name).first || create!(:name => name)
end
)
end
alias_method('[]', 'for')
end
def next
42.times do
code = String.random
query = {
'$and' => [
{:_id => id},
{'codes' => {'$nin' => [code]}}
]
}
update = {
'$addToSet' => {:codes => code}
}
if Code.collection.find_and_modify(:query => query, :update => update)
reload
return code
end
end
raise IndexError
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment