class Faker::Internet

def username(specifier: nil, separators: %w[. _])

Parameters:
  • separators (Array) --
  • specifier (Integer, Range, String) -- When int value passed it returns the username longer than specifier. Max value can be 10^6

Returns:
  • (String) -
def username(specifier: nil, separators: %w[. _])
  with_locale(:en) do
    case specifier
    when ::String
      names = specifier.gsub("'", '').scan(/[[:word:]]+/)
      shuffled_names = shuffle(names)
      return shuffled_names.join(sample(separators)).downcase
    when Integer
      # If specifier is Integer and has large value, Argument error exception is raised to overcome memory full error
      raise ArgumentError, 'Given argument is too large' if specifier > 10**6
      tries = 0 # Don't try forever in case we get something like 1_000_000.
      result = nil
      loop do
        result = username(specifier: nil, separators: separators)
        tries += 1
        break unless result.length < specifier && tries < 7
      end
      return result * (specifier / result.length + 1) if specifier.positive?
    when Range
      tries = 0
      result = nil
      loop do
        result = username(specifier: specifier.min, separators: separators)
        tries += 1
        break unless !specifier.include?(result.length) && tries < 7
      end
      return result[0...specifier.max]
    end
    sample([
             Char.prepare(Name.first_name),
             [Name.first_name, Name.last_name].map do |name|
               Char.prepare(name)
             end.join(sample(separators))
           ])
  end
end