Created
December 24, 2008 20:05
-
-
Save eric/39759 to your computer and use it in GitHub Desktop.
This file contains 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
require 'rails_generator/secret_key_generator' | |
module TokenGenerator | |
def generate_token(size = 32, &validity) | |
constant = "#{self.class.name}#{id}" | |
generator = Rails::SecretKeyGenerator.new(constant) | |
begin | |
token = generator.generate_secret.first(size) | |
end while !validity.call(token) if block_given? | |
token | |
end | |
end |
This file contains 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 User < ActiveRecord::Base | |
include TokenGenerator | |
before_save :set_token | |
private | |
def set_token | |
if self.token.blank? | |
write_attribute :token, generate_token(9) { |token| self.class.find_by_token(token).nil? } | |
end | |
true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment