Create a gist now

Instantly share code, notes, and snippets.

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