Created
February 3, 2014 13:51
-
-
Save mskeen/8784185 to your computer and use it in GitHub Desktop.
rails: random token for a model
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_create :generate_token | |
end | |
protected | |
def generate_token | |
self.token = loop do | |
random_token = SecureRandom.urlsafe_base64(nil, false)[0..5] | |
break random_token unless self.class.exists?(token: random_token) | |
end | |
end | |
end | |
# add to model: | |
# include Tokenable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment