Created
October 16, 2020 15:35
-
-
Save jordanhudgens/7aba3386cc11cc34a7802dfb0b50d484 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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