class Koota::Generator

This class uses a parser, compiler, and VM to generate words.

Constants

DEFAULT_CALL_OPTIONS

Public Class Methods

new(parser: Koota::Parser.new, compiler: Koota::Compiler.new, vm: Koota::VM.new) click to toggle source
# File lib/koota/generator.rb, line 17
def initialize(parser: Koota::Parser.new, compiler: Koota::Compiler.new, vm: Koota::VM.new)
  @parser   = parser
  @compiler = compiler
  @vm       = vm
end

Public Instance Methods

call(pattern, options = {}) click to toggle source
# File lib/koota/generator.rb, line 23
def call(pattern, options = {})
  options = DEFAULT_CALL_OPTIONS.merge(options)

  bytecode = compile(pattern)

  syllables = if options[:syllables].is_a?(Integer)
                -> { options[:syllables] }
              elsif options[:syllables].is_a?(Range)
                -> { rand(options[:syllables]) }
              else
                type = options[:syllables].class.to_s
                raise ArgumentError, "expected Integer or Range for syllables option, not #{type}"
              end

  result = Array.new(options[:words]) do
    Array.new(syllables.call) { @vm.call(bytecode) }.join(options[:syllable_separator])
  end

  result.uniq! unless options[:duplicates]

  result
end

Private Instance Methods

collect_all_refs(pattern) click to toggle source
# File lib/koota/generator.rb, line 52
def collect_all_refs(pattern)
  result = {}
  stack = [pattern.refs]

  until stack.empty?
    current = stack.pop
    current.each do |key, subpattern|
      result[key] ||= @parser.call(subpattern.string)
      stack.push(subpattern.refs)
    end
  end

  result
end
compile(pattern) click to toggle source
# File lib/koota/generator.rb, line 48
def compile(pattern)
  @compiler.call(@parser.call(pattern.string), collect_all_refs(pattern))
end