Created
February 27, 2015 23:58
-
-
Save fsaravia/47739914c4fd032a62e8 to your computer and use it in GitHub Desktop.
Random strings in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Randomizer | |
PATTERNS = { | |
lowercase: Array("a".."z"), | |
uppercase: Array("A".."Z"), | |
numbers: Array(0..9), | |
special: %w(- _ .) | |
} | |
module_function | |
def configure(options) | |
@patterns = options[:patterns] if options[:patterns] | |
@extra = options[:extra] if options[:extra] | |
end | |
def patterns | |
@patterns ||= PATTERNS.keys | |
end | |
def extra | |
@extra | |
end | |
def next(size=10) | |
source = patterns.map{ |p| PATTERNS.fetch(p) }.flatten | |
source.concat(extra) if extra | |
# Multiply size of source when needed | |
iterations = (size / source.size.to_f).ceil | |
chars = iterations.times.map{ source }.to_a.flatten | |
chars.sample(size).join | |
end | |
end | |
puts Randomizer.next(20) #=> bLVFpcDGm6_iClaTZSd0 | |
Randomizer.configure(patterns: [:special], extra: ("a".."f").to_a) | |
puts Randomizer.next(20) #=> -ede.fffd._acbea-ba. | |
Randomizer.configure(patterns: [:uppercase, :lowercase]) | |
puts Randomizer.next(20) #=> VfGhorYglBmKAcUnCbTO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment