Skip to content

Instantly share code, notes, and snippets.

@sterrym
Created January 23, 2012 16:03
Show Gist options
  • Save sterrym/1663978 to your computer and use it in GitHub Desktop.
Save sterrym/1663978 to your computer and use it in GitHub Desktop.
auto-create a unique youtube-like token to uniquely identify a records
class Foo < ActiveRecord::Base
before_create :make_token
private
TOKEN_SYMBOLS = (('A'..'Z').to_a + ('a'..'z').to_a + (0..9).to_a)
def make_token
self.token = (1..12).inject(""){|token, num| token += TOKEN_SYMBOLS.rand.to_s }
make_token if self.class.find_by_token(self.token)
self.token
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment