Skip to content

Instantly share code, notes, and snippets.

@lukaszx0
Created January 28, 2018 23:12
Show Gist options
  • Save lukaszx0/d9de212ee130e85be5c63623c64ed6bd to your computer and use it in GitHub Desktop.
Save lukaszx0/d9de212ee130e85be5c63623c64ed6bd to your computer and use it in GitHub Desktop.
Tokenable concern for Rails models
# app/models/concerns/tokenable.rb
module Tokenable
extend ActiveSupport::Concern
included do
before_create :generate_token
end
protected
def generate_token
max_attempts = 0
self.token = loop do
random_token = SecureRandom.urlsafe_base64(nil, false)
break random_token unless self.class.exists?(token: random_token)
attempts = attempts + 1
raise "Max attempts to generate token reached" if attempts > max_attempts
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment