07-18-2023, 11:05 PM
Here is another method:
- It uses the secure random number generator instead of rand()
- Can be used in URLs and file names
- Contains uppercase, lowercase characters and numbers
- Has an option not to include ambiguous characters I0l01
Needs `require "securerandom"`
def secure_random_string(length = 32, non_ambiguous = false)
characters = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
%w{I O l 0 1}.each{ |ambiguous_character|
characters.delete ambiguous_character
} if non_ambiguous
(0...length).map{
characters[ActiveSupport::SecureRandom.random_number(characters.size)]
}.join
end
- It uses the secure random number generator instead of rand()
- Can be used in URLs and file names
- Contains uppercase, lowercase characters and numbers
- Has an option not to include ambiguous characters I0l01
Needs `require "securerandom"`
def secure_random_string(length = 32, non_ambiguous = false)
characters = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
%w{I O l 0 1}.each{ |ambiguous_character|
characters.delete ambiguous_character
} if non_ambiguous
(0...length).map{
characters[ActiveSupport::SecureRandom.random_number(characters.size)]
}.join
end