Skip to content

Instantly share code, notes, and snippets.

@timuruski
Created August 31, 2011 21:01
Show Gist options
  • Save timuruski/1184709 to your computer and use it in GitHub Desktop.
Save timuruski/1184709 to your computer and use it in GitHub Desktop.
A concise way to generate random values until a unique one is found.
class Device
include MongoMapper::Document
key :token, :unique => true, :default = lambda { generate_token }
def self.generate_token
token = ActiveSupport::SecureRandom.hex until token_available?(token)
token
end
def self.token_available?(token)
token && count(:device_token => token) == 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment