Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Feature - good random string generation #469

Closed
wants to merge 1 commit into from
Closed

New Feature - good random string generation #469

wants to merge 1 commit into from

Conversation

nathanstitt
Copy link
Contributor

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.

…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
@tenderlove
Copy link
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
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants