module NameGenerator

Constants

ACCEPTABLE_AFTER
INVALID_ENDINGS

Not technically invalid, just not things I think make good names. I'm not good at naming things. (As you may have guessed.)

InvalidNameError
LETTERS
NameTooShortError
VERSION

Public Class Methods

call(options) click to toggle source
# File lib/name_generator.rb, line 89
def self.call(options)
  min_length = Integer(options["min_length"])
  max_length = Integer(options["max_length"])

  length = rand(min_length..max_length)
  result = ""

  while result.length < length
    valid = LETTERS.select { |l| can_follow?(result, l) }
    current = valid.sample

    # Break if nothing can follow.
    break if !result.empty? && valid.empty?

    if options["debug"]
      puts "can_follow?(#{result.inspect}, #{current.inspect}) #=> #{can_follow?(result[-1], current)}"
    end

    if result.empty? || can_follow?(result, current)
      result << current
    elsif options["debug"]
      warn "Cannot append #{current} to #{result}."
    end

    # 25% chance if breaking the loop if we've met or exceeded min_length
    # and the current name is valid.
    break if rand(1..100) <= 25 && length >= min_length && valid_name?(name)
  end

  # HACK: Yes, this is very gross.
  raise NameTooShortError if result.length < min_length
  raise InvalidNameError  if !valid_name?(result)

  result
rescue NameTooShortError
  if options[:debug]
    warn "#{result.inspect} is too short and cannot be expanded; retrying."
  end

  retry
rescue InvalidNameError
  if options[:debug]
    warn "#{result.inspect} is an invalid name; retrying."
  end

  retry
end

Private Class Methods

can_follow?(result, current) click to toggle source
# File lib/name_generator.rb, line 137
def self.can_follow?(result, current)
  ACCEPTABLE_AFTER.any? { |regex, value|
    (result =~ regex) && value && value.include?(current)
  }
end
valid_name?(name) click to toggle source
# File lib/name_generator.rb, line 144
def self.valid_name?(name)
  INVALID_ENDINGS.none? { |ending| name.end_with?(ending) }
end