Skip to content

Instantly share code, notes, and snippets.

@RobertAudi
Forked from hugodias/tokenable.rb
Last active August 29, 2015 14:18
Show Gist options
  • Save RobertAudi/41924458c86de36604ed to your computer and use it in GitHub Desktop.
Save RobertAudi/41924458c86de36604ed to your computer and use it in GitHub Desktop.
#
# 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