Skip to content

Instantly share code, notes, and snippets.

@robertomiranda
Last active August 29, 2015 14:10
Show Gist options
  • Save robertomiranda/d5749156136947ac371e to your computer and use it in GitHub Desktop.
Save robertomiranda/d5749156136947ac371e to your computer and use it in GitHub Desktop.
module HasSecureToken
extend ActiveSupport::Concern
module ClassMethods
def has_secure_token(*attrs)
include InstanceMethodsOnActivation
cattr_accessor :token_columns
self.token_columns = attrs
before_create :_generate_token
end
end
module InstanceMethodsOnActivation
def _generate_token
self.class.token_columns.each do |attribute|
self.send("#{attribute}=", loop do
random_token = SecureRandom.hex
break random_token unless self.class.exists?(attribute => random_token)
end)
end
end
end
end
class User
tokenize :auth_token, :another_token
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment