Skip to content

Instantly share code, notes, and snippets.

@strukturedkaos
Created April 7, 2016 18:57
Show Gist options
  • Save strukturedkaos/7751c0f194925b80b0410df080ceff22 to your computer and use it in GitHub Desktop.
Save strukturedkaos/7751c0f194925b80b0410df080ceff22 to your computer and use it in GitHub Desktop.
Module concern for generating token
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