-
-
Save RobertAudi/41924458c86de36604ed to your computer and use it in GitHub Desktop.
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
# | |
# Generate a unique token before the creating a | |
# new record. Option to specify an array of | |
# attributes as predicates for the uniqueness check. | |
# The tokenable attribute is always appended to | |
# the list of predicates. | |
# | |
# Example usage in a model: | |
# | |
# class Contribution < ActiveRecord::Base | |
# include Tokenable | |
# # The 'by: []' argument is optional | |
# tokenable_attr :payment_token, by: [:contributor_id, :project_id] | |
# | |
# # ... | |
# end | |
# | |
module Tokenable | |
extend ActiveSupport::Concern | |
included do |klass| | |
def klass.tokenable_attr(name, options = {}) | |
before_create do |k| | |
k.generate_token name, options[:by] | |
end | |
end | |
protected | |
def generate_token(attribute, predicates = []) | |
predicates = Hash[predicates.map { |n| [n, self[n]] }] | |
self[attribute] = loop do | |
random_token = SecureRandom.urlsafe_base64(nil, false) | |
break random_token unless self.class.exists?(predicates.merge(attribute => random_token)) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment