public
Created

  • Download Gist
code.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.