Posted 562 days ago
Part of my new comment system for Blosxonomy includes an email verification system that requests the user to confirm their email before their comments will be displayed on the blog. To do this, I wrote a simple random-hex-code generator to build unique url's. When a comment is posted by a user with an unconfirmed email address, a random URL is generated using the random hex code, and emailed to that user.
Generating such codes in ruby is very simple, and often useful, so I thought I'd post the method I wrote to do it:
def generateUniqueHexCode( codeLength )
validChars = ("A".."F").to_a + ("0".."9").to_a
length = validChars.size
hexCode = ""
1.upto(codeLength) { |i| hexCode << validChars[rand(length-1)] }
hexCode
end
validChars is initialized to be an array containing characters 'A' through 'F', and '0' through '9'. I then append codeLength random characters from that array to the hexCode string and return it.
While a more robust implementation would validate uniqueness against the list of already generated IDs, the assumption is that these ID's are short lived, and the likelihood of generating repeats IDs given a sufficient length (I use 64) is miniscule.
add to
del.icio.us