Permalink
Browse files

Added a token generator plugin [DHH]

  • Loading branch information...
0 parents commit 78d73fc32c435bf177c4a93a517766d02c69b404 @dhh dhh committed May 29, 2006
Showing with 42 additions and 0 deletions.
  1. +29 −0 README
  2. +13 −0 lib/token_generator.rb
29 README
@@ -0,0 +1,29 @@
+TokenGenerator
+==============
+
+Mix-in for classes that needs to have a token generated using MD5. You can set the length of the token
+and provide it with an optional block that'll check the validity of the generated token (usually whether it's
+already taken or not).
+
+The two methods are generate_token, which will just return a new token, and set_token, which will assume
+that there's a writer for the instance variable "token" and that the class has a "find_by_token" method to check
+validity (if a duplicate exists, generate another token).
+
+Examples:
+
+ class Invitation < ActiveRecord::Base
+ include TokenGenerator
+ before_create :set_token
+ end
+
+ class ImperialInvitation < ActiveRecord::Base
+ include TokenGenerator
+ before_create :set_token
+
+ private
+ def set_token
+ self.token = generate_token { |token| complies_to_imperial_standards?(token) }
+ end
+ end
+
+Copyright (c) 2005 David Heinemeier Hansson, Marcel Molina Jr. released under the MIT license
13 lib/token_generator.rb
@@ -0,0 +1,13 @@
+module TokenGenerator
+ def generate_token(size = 12, &validity)
+ begin
+ token = Digest::MD5.hexdigest("#{inspect}#{Time.now}").first(size)
+ end while validity.call(token) if block_given?
+
+ token
+ end
+
+ def set_token
+ self.token = generate_token { |token| !self.find_by_token(token) }
+ end
+end

0 comments on commit 78d73fc

Please sign in to comment.