Skip to content

Instantly share code, notes, and snippets.

@hugodias
Created December 30, 2013 15:04
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hugodias/8183115 to your computer and use it in GitHub Desktop.
Save hugodias/8183115 to your computer and use it in GitHub Desktop.
Create a best random token for any model in ruby on rails
# app/models/mymodel.rb
# include Tokenable
###
# app/models/concerns/tokenable.rb
module Tokenable
extend ActiveSupport::Concern
included do
before_create :generate_token
end
protected
def generate_token
self.token = loop do
random_token = SecureRandom.urlsafe_base64(nil, false)
break random_token unless self.class.exists?(token: random_token)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment