Class: Koota::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/koota/generator.rb

Overview

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

Constant Summary collapse

DEFAULT_CALL_OPTIONS =
{
  words: 100,
  syllables: 1,
  syllable_separator: '',
  duplicates: false
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(parser: Koota::Parser.new, compiler: Koota::Compiler.new, vm: Koota::VM.new) ⇒ Generator

Returns a new instance of Generator.



17
18
19
20
21
# 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

Instance Method Details

#call(pattern, options = {}) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 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