Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Rails Snippet For Generating A Unique Token

DZone's Guide to

Rails Snippet For Generating A Unique Token

·
Free Resource

  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

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}