Last active
December 29, 2015 16:19
-
-
Save RyanNielson/7696909 to your computer and use it in GitHub Desktop.
Add automatic token generation to a Rails model using concerns. Required a string field called token on the model.
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
module Tokenable | |
extend ActiveSupport::Concern | |
included do | |
before_validation :generate_token, unless: :persisted?, if: Proc.new { |tokenable| tokenable.token.blank? } | |
end | |
protected | |
def generate_token | |
self.token = loop do | |
random_token = SecureRandom.urlsafe_base64(8, false) | |
break random_token unless self.class.exists?(token: random_token) | |
end | |
end | |
end |
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
class TokenableModel < ActiveRecord::Base | |
include Tokenable | |
validates :token, presence: true, uniqueness: true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment