Module: Poefy::Generation

Included in:
PoefyGen
Defined in:
lib/poefy/generation.rb

Instance Method Summary collapse

Instance Method Details

#poem(poetic_form = @poetic_form) ⇒ Object

Generate specific poem types.

Raises:

  • (ArgumentError)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/poefy/generation.rb', line 17

def poem poetic_form = @poetic_form

  if !@db.exists?
    return handle_error 'ERROR: Database does not yet exist', nil
  end

  # Validate the poetic form hash.
  raise ArgumentError, 'Argument must be a hash' unless
        poetic_form.is_a?(Hash)
  poetic_form = validate_poetic_form poetic_form
  poetic_form = @poetic_form.merge poetic_form

  # Make sure the hash contains ':form' or ':rhyme' keys.
  if !(poetic_form[:form] or poetic_form[:rhyme])
    return handle_error \
      "ERROR: No valid rhyme or form option specified.\n" +
      "       Try again using the -f or -r option.\n" +
      "       Use -h or --help to view valid forms."
  end

  # Loop until we find a valid poem.
  # There are cases where valid permutations are not able to be
  #   genned on the first try, so keep trying a few more times.
  output, count_down = nil, 10
  loop do
    output = gen_poem_using_conditions poetic_form
    break if !output.nil? || count_down == 0
    count_down -= 1
  end

  # Return nil if poem could not be created.
  return nil if (output.nil? or output == [] or output == [''])

  # Indent the output using the :indent string.
  output = do_indent(output, get_poetic_form_indent(poetic_form))

  # Append blank lines to the end if the :rhyme demands it.
  rhyme = tokenise_rhyme get_poetic_form_rhyme poetic_form
  (output.length...rhyme.length).each do |i|
    output[i] = ''
  end

  output
end

#rhymes(word, key = nil) ⇒ Object

Get all rhyming lines for the word.



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/poefy/generation.rb', line 63

def rhymes word, key = nil
  return nil if word.nil?
  sproc = @db.db.prepare %Q[
    SELECT rhyme, final_word, syllables, line
    FROM lines
    WHERE rhyme = ?
    ORDER BY rhyme, final_word, syllables, line
  ]
  output = word.to_phrase.rhymes.keys.map do |rhyme|
    sproc.reset!
    sproc.bind_param(1, rhyme)
    sproc.execute.to_a
  end.flatten
  sproc.close
  if !key.nil? and %w[rhyme final_word syllables line].include?(key)
    output.map!{ |i| i[key] }
  end
  output
end