New Feature - good random string generation #469

Closed
wants to merge 1 commit into from

2 participants

@nathanstitt

This adds two methods to SecureRandom. random_from_set randomly chooses a given number of items from a set, returning an object of the same type. random_unambiguous_code returns an alpha numeric code which does include characters that could be confused with one another.

I had a need for generating a random string that did not include easily mis-identified characters. Did a search for 'rails generate password' to check if rails already had that functionality and was horrified by what people were suggesting.

The two added methods are so trivial I hesitate to submit them, but people seem to have a hard time with this so perhaps they should be included in rails itself?

I'm not really happy with the names, but couldn't come up with anything better. If anyone has better any ideas I'd be glad to rework the patch.

Feel free to drop the pull request if it is indeed judged too trivial.

@nathanstitt nathanstitt add two methods to secure_random. random_from_set randomly chooses a …
…given number of items from a set, returning an object of the same type. random_unambiguous_code returns an alpha numeric code which does not use characters that could be confused with one another
8b62966
@tenderlove
Ruby on Rails member

I don't think we should add this to core. The API seems strange. Why not just return a set that is ordered randomly, and let the user call first on it. For example: set.sort_by { rand }.first(n). If you really want to use ssl, then call unpack on the bytes, zip, sort, first:

irb(main):008:0> myset = %w{ a b c d e f }
=> ["a", "b", "c", "d", "e", "f"]
irb(main):009:0> OpenSSL::Random.random_bytes(myset.length).unpack('C*').zip(myset).sort_by { |r,_| r }.map { |_,i| i }.first 2
=> ["f", "a"]
irb(main):010:0>

Either way, I don't think this is something that should go in core.

@tenderlove tenderlove closed this May 9, 2011
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment