class Faker::Internet
def password(min_length: 8, max_length: 16, mix_case: true, special_characters: false)
-
(String)
-
Parameters:
-
special_characters
(Boolean
) -- Toggles if special characters are allowed. If true, at least one will be added. -
mix_case
(Boolean
) -- Toggles if uppercased letters are allowed. If true, at least one will be added. -
max_length
(Integer
) -- The maximum length of the password -
min_length
(Integer
) -- The minimum length of the password
def password(min_length: 8, max_length: 16, mix_case: true, special_characters: false) raise ArgumentError, 'min_length and max_length must be greater than or equal to one' if min_length < 1 || max_length < 1 raise ArgumentError, 'min_length must be smaller than or equal to max_length' unless min_length <= max_length character_types = [] required_min_length = 0 if mix_case character_types << :mix_case required_min_length += 2 end if special_characters character_types << :special_characters required_min_length += 1 end raise ArgumentError, "min_length should be at least #{required_min_length} to enable #{character_types.join(', ')} configuration" if min_length < required_min_length target_length = rand(min_length..max_length) password = [] character_bag = [] # use lower_chars by default and add upper_chars if mix_case lower_chars = self::LLetters password << sample(lower_chars) character_bag += lower_chars digits = ('0'..'9').to_a password << sample(digits) character_bag += digits if mix_case upper_chars = self::ULetters password << sample(upper_chars) character_bag += upper_chars end if special_characters special_chars = %w[! @ # $ % ^ & *] password << sample(special_chars) character_bag += special_chars end password << sample(character_bag) while password.length < target_length shuffle(password).join end