Created
April 7, 2016 18:57
-
-
Save strukturedkaos/7751c0f194925b80b0410df080ceff22 to your computer and use it in GitHub Desktop.
Module concern for generating token
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 | |
included do | |
before_save :ensure_token | |
def ensure_token | |
generate_token(length: 32) if token.blank? | |
end | |
private | |
def generate_token(length: 32) | |
begin | |
self.token = SecureRandom.urlsafe_base64(length).gsub(/[\-_]/, "").first(length) | |
end while self.class.where(token: token).exists? | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment