DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Rails Snippet For Generating A Unique Token

11.06.2008
| 6779 views |
  • submit to reddit
        
  before_create :generate_token

  def generate_token(length=8)
    alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
    self.token = alphanumerics.sort_by{rand}.to_s[0..length]

    # Ensure uniqueness of the token..
    generate_token unless Widget.find_by_token(self.token).nil?
  end

    

Comments

Snippets Manager replied on Mon, 2012/05/07 - 3:04pm

ActiveSupport::SecureRandom.hex(8) works too.

Snippets Manager replied on Tue, 2008/12/16 - 1:23am

Can we reduce its probability of expected collision? by concatenating Time.now.to_i or some other factor.