Created
January 28, 2018 23:12
-
-
Save lukaszx0/d9de212ee130e85be5c63623c64ed6bd to your computer and use it in GitHub Desktop.
Tokenable concern for Rails models
This file contains hidden or 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
# 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