Skip to content

Instantly share code, notes, and snippets.

@jordanhudgens
Created October 16, 2020 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanhudgens/7aba3386cc11cc34a7802dfb0b50d484 to your computer and use it in GitHub Desktop.
Save jordanhudgens/7aba3386cc11cc34a7802dfb0b50d484 to your computer and use it in GitHub Desktop.
module Tokenable
extend ActiveSupport::Concern
# To add to a model with pre-existing records
# ModelName.all.each do |i|
# i.token = loop do
# random_token = SecureRandom.urlsafe_base64(nil, false)
# break random_token unless i.class.exists?(token: random_token)
# end
# i.save!
# end
included do
before_create :generate_token
end
protected
def generate_token
if !self.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
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment