Class: RandomWords::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/random-words/generator.rb

Overview

Random character, word, and sentence generator

Constant Summary collapse

SENTENCE_PARTS =

Define the default sentence parts These parts will be used to generate random sentences and character strings

%w[random_article random_adjective random_noun random_adverb random_verb random_adjective
random_verb random_adverb random_phrase].freeze
TEMPLATES =
[
  # Simple declarative
  i[random_article random_adjective random_noun random_verb],
  i[random_plural_article random_adjective random_plural_noun random_plural_verb],

  # With adverb
  i[random_article random_adjective random_noun random_adverb random_verb],
  i[random_name random_adverb random_verb],

  # Passive voice
  i[random_article random_noun random_passive_verb random_preposition random_article random_noun],

  # With prepositional phrase
  i[random_article random_adjective random_noun random_verb random_preposition random_article random_noun],

  # Compound sentence
  i[random_article random_noun random_verb random_coordinating_conjunction random_article random_noun random_verb],

  # Subordinate clause
  i[random_clause random_article random_noun random_verb],

  # With phrase
  i[random_phrase],

  # Name as subject
  i[random_name random_verb random_article random_noun],

  # Plural with adverb and preposition
  i[random_plural_article random_plural_noun random_adverb random_plural_verb random_preposition random_article random_noun],

  # Coordinating conjunction joining two clauses
  i[random_article random_noun random_verb random_coordinating_conjunction random_plural_article random_plural_noun random_plural_verb
     random_phrase],

  # Subordinate conjunction
  i[random_subordinate_conjunction random_article random_noun random_verb random_article random_noun random_verb],

  # With random_adjective and random_adverb in various places
  i[random_adverb random_article random_adjective random_noun random_verb],
  i[random_article random_noun random_verb random_adverb],

  # Name with phrase
  i[random_name random_verb random_phrase],

  # Plural passive
  i[random_plural_article random_plural_noun random_passive_verb random_preposition random_article random_noun],

  # Name with subordinate clause
  i[random_name random_verb random_subordinate_conjunction random_article random_noun random_verb]
].freeze
OPTIONAL_PARTS =
i[adjectives adverbs].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source = :english, options = {}) ⇒ Generator

Initialize the generator with a source and options

Examples:

generator = RandomWords::Generator.new(:english, sentence_length: :medium, paragraph_length: 5)
generator.source = :french
generator.lengths = { short: 50, medium: 150 }
generator.sentence_length = :long
generator.paragraph_length = 3

Parameters:

  • source (Symbol) (defaults to: :english)

    The source of the words (e.g., :english)

  • options (Hash) (defaults to: {})

    Options for the generator (e.g., length, paragraph_length)



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/random-words/generator.rb', line 104

def initialize(source = :english, options = {})
  @debug = options[:debug] || false
  @tested = []
  @config = RandomWords::Config.new(source)
  @source = source

  @nouns = @config.dictionary[:nouns]
  @plural_nouns = @config.dictionary[:plural_nouns]
  @verbs = @config.dictionary[:verbs]
  @plural_verbs = @config.dictionary[:plural_verbs]
  @passive_verbs = @config.dictionary[:passive_verbs]
  @adverbs = @config.dictionary[:adverbs]
  @adjectives = @config.dictionary[:adjectives]
  @articles = @config.dictionary[:articles]
  @plural_articles = @config.dictionary[:plural_articles]
  @prepositions = @config.dictionary[:prepositions]
  @clauses = @config.dictionary[:clauses]
  @coordinating_conjunctions = @config.dictionary[:coordinating_conjunctions]
  @subordinate_conjunctions = @config.dictionary[:subordinate_conjunctions]
  @numbers = @config.dictionary[:numbers]
  @sources = @config.sources
  @terminators = @config.dictionary[:terminators]
  @names = [@config.dictionary[:first_names], @config.dictionary[:last_names], @config.dictionary[:full_names]]
  @phrases = @config.dictionary[:phrases]
  @all_words = @config.dictionary[:all_words]

  @options = {
    sentence_length: :medium,
    paragraph_length: 5,
    use_extended_punctuation: false
  }

  @options.merge!(options) if options.is_a?(Hash)
  @sentence_length = @options[:sentence_length]
  @paragraph_length = @options[:paragraph_length]
  @use_extended_punctuation = @options[:use_extended_punctuation]

  @terminators.concat(@config.dictionary[:extended_punctuation]) if @use_extended_punctuation

  lengths
end

Instance Attribute Details

#adjectivesArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def adjectives
  @adjectives
end

#adverbsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def adverbs
  @adverbs
end

#all_wordsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def all_words
  @all_words
end

#articlesArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def articles
  @articles
end

#clausesArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def clauses
  @clauses
end

#configObject (readonly)

return [Hash] configuration



16
17
18
# File 'lib/random-words/generator.rb', line 16

def config
  @config
end

#coordinating_conjunctionsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def coordinating_conjunctions
  @coordinating_conjunctions
end

#debugBoolean

Debug mode

Returns:

  • (Boolean)

    true if debug mode is enabled, false otherwise



36
37
38
# File 'lib/random-words/generator.rb', line 36

def debug
  @debug
end

#extended_punctuationArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def extended_punctuation
  @extended_punctuation
end

#namesArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def names
  @names
end

#nounsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def nouns
  @nouns
end

#numbersArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def numbers
  @numbers
end

#paragraph_lengthInteger

Returns Number of sentences in paragraphs.

Returns:

  • (Integer)

    Number of sentences in paragraphs



23
24
25
# File 'lib/random-words/generator.rb', line 23

def paragraph_length
  @paragraph_length
end

#passive_verbsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def passive_verbs
  @passive_verbs
end

#phrasesArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def phrases
  @phrases
end

#plural_articlesArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def plural_articles
  @plural_articles
end

#plural_nounsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def plural_nouns
  @plural_nouns
end

#plural_verbsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def plural_verbs
  @plural_verbs
end

#prepositionsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def prepositions
  @prepositions
end

#sentence_lengthSymbol

Returns Sentence length (:short, :medium, :long, :very_long).

Returns:

  • (Symbol)

    Sentence length (:short, :medium, :long, :very_long)



26
27
28
# File 'lib/random-words/generator.rb', line 26

def sentence_length
  @sentence_length
end

#sourceSymbol

Returns Dictionary in use.

Returns:

  • (Symbol)

    Dictionary in use



29
30
31
# File 'lib/random-words/generator.rb', line 29

def source
  @source
end

#sourcesHash<String, RandomWords::Source> (readonly)

Returns List of available sources.

Returns:



32
33
34
# File 'lib/random-words/generator.rb', line 32

def sources
  @sources
end

#subordinate_conjunctionsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def subordinate_conjunctions
  @subordinate_conjunctions
end

#terminatorsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def terminators
  @terminators
end

#use_extended_punctuationBoolean

Whether to use extended punctuation

Returns:

  • (Boolean)

    true if extended punctuation is used, false otherwise



20
21
22
# File 'lib/random-words/generator.rb', line 20

def use_extended_punctuation
  @use_extended_punctuation
end

#verbsArray<String> (readonly)

Returns arrays of elements of speech.

Returns:



11
12
13
# File 'lib/random-words/generator.rb', line 11

def verbs
  @verbs
end

Instance Method Details

#characters(min, max = nil, whole_words: true, whitespace: true, article: true, dead_switch: 0) ⇒ String

Generate a series of random words up to a specified length

Examples:

characters(50) # Generates a string with at least 50 characters
characters(50, 100) # Generates a string with between 50 and 100 characters
characters(50, whole_words: false) # Generates a string with 50 characters allowing word truncation

Parameters:

  • min (Integer)

    The minimum length of the generated string

  • max (Integer) (defaults to: nil)

    (Optional) The maximum length of the generated string

  • whole_words (Boolean) (defaults to: true)

    (Optional) Whether to generate whole words or not

  • dead_switch (Integer) (defaults to: 0)

    (Optional) A counter to prevent infinite loops

Returns:

  • (String)

    The generated string of random words

Raises:

  • (ArgumentError)


309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/random-words/generator.rb', line 309

def characters(min, max = nil, whole_words: true, whitespace: true, article: true, dead_switch: 0)
  result = ''
  max ||= min
  raise ArgumentError, 'Infinite loop detected' if dead_switch > 40

  whole_words = false if dead_switch > 15

  space = whitespace ? ' ' : ''
  current_part = article ? 0 : 1
  while result.length < max && result.length < min
    word = send(SENTENCE_PARTS[current_part].to_sym)
    word = word.gsub(/ +/, '') unless whitespace
    current_part = (current_part + 1) % SENTENCE_PARTS.length
    new_result = "#{result}#{space}#{word}".compress

    if new_result.length > max
      return handle_overflow(OverflowConfig.new(new_result, result, min, max, whole_words, whitespace,
                                                dead_switch))
    end
    return new_result if new_result.length == max

    result = new_result
  end

  result.strip
end

#code_langSymbol

Generate a random code language

Returns:

  • (Symbol)

    A randomly selected code language



392
393
394
395
# File 'lib/random-words/generator.rb', line 392

def code_lang
  code_langs = i[python ruby swift javascript css rust go java]
  code_langs[Random.rand(code_langs.count)]
end

#code_snippet(lang = nil) ⇒ String

Return random code snippet

Parameters:

  • lang (Symbol) (defaults to: nil)

    The language of the code snippet

Returns:

  • (String)

    A randomly generated code snippet



400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/random-words/generator.rb', line 400

def code_snippet(lang = nil)
  code_snippets = {
    python: %(def hello_world():\n    print("Hello, World!")),
    ruby: %(def hello_world\n  puts "Hello, World!"\nend),
    swift: %(func helloWorld() {\n    print("Hello, World!")\n}),
    javascript: %(function helloWorld() {\n    console.log("Hello, World!");\n}),
    css: %(body {\n    background-color: #f0f0f0;\n    font-family: Arial, sans-serif;\n}\nh1 {\n    color: #333;\n}),
    rust: %(fn main() {\n    println!("Hello, World!");\n}),
    go: %(package main\nimport "fmt"\nfunc main() {\n    fmt.Println("Hello, World!")\n}),
    java: %(public class HelloWorld {\n    public static void main(String[] args) {\n        System.out.println("Hello, World!");\n    }\n})
  }
  lang ||= code_lang
  code_snippets[lang.to_sym]
end

#create_dictionary(title) ⇒ Symbol

Shortcut for RandomWords::Config.create_user_dictionary

Examples:

create_dictionary('my_custom_dictionary')

Parameters:

  • title (String)

    The title of the user dictionary

Returns:

  • (Symbol)

    The symbolized name of the dictionary



158
159
160
# File 'lib/random-words/generator.rb', line 158

def create_dictionary(title)
  @config.create_user_dictionary(title)
end

#dbg(msg) ⇒ Object

Display debug message



147
148
149
150
151
# File 'lib/random-words/generator.rb', line 147

def dbg(msg)
  return unless @debug

  "%#{msg}%"
end

#generate_combined_sentence(length = nil) ⇒ String

Generate a random sentence, combining multiple sentences if necessary This method generates a random sentence and checks its length. If the length is less than the defined length, it combines it with another sentence. The final sentence is returned with proper capitalization and termination.

Examples:

generate_combined_sentence # Generates a combined sentence

Parameters:

  • length (Symbol) (defaults to: nil)

    The desired length of the sentence, :short, :medium, :long, or :very_long

Returns:

  • (String)

    A randomly generated sentence



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/random-words/generator.rb', line 360

def generate_combined_sentence(length = nil)
  length ||= define_length(@sentence_length)
  sentence = generate_sentence
  return sentence.to_sent(random_terminator).fix_caps(terminators).expand_debug if sentence.length > length

  while sentence.length < length
    # Generate a random number of sentences to combine
    new_sentence = generate_sentence(length / 2)

    # Combine the sentences with random conjunctions
    sentence = "#{sentence.strip.no_term(terminators)}, #{random_coordinating_conjunction} #{new_sentence.no_term(terminators)}"
  end

  sentence.to_sent(random_terminator).fix_caps(terminators).expand_debug
end

#html(settings = {}) ⇒ String

Generate random HTML

Parameters:

  • settings (Hash) (defaults to: {})

    Settings for generating HTML

Returns:

  • (String)

    A randomly generated HTML string



433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/random-words/generator.rb', line 433

def html(settings = {})
  html = RandomWords::LoremHTML.new(settings)
  if settings[:complete]
    style = settings[:style] || 'style.css'
    "      <!DOCTYPE html>\n      <html lang=\"en\">\n      <head>\n      \\t<meta charset=\"UTF-8\">\n      \\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n      \\t<title>\#{html.title}</title>\n      \\t<link rel=\"stylesheet\" href=\"\#{style}\">\n      </head>\n      <body>\n        \#{html.output.indent(\"\\t\")}\n      </body>\n      </html>\n    EOOUTPUT\n  else\n    html.output\n  end\nend\n"

#lengthsObject

Refactored lengths and lengths= methods This method returns the lengths of sentences The default lengths are set to the following values: short: 20, medium: 60, long: 100, very_long: 300



269
270
271
# File 'lib/random-words/generator.rb', line 269

def lengths
  @lengths ||= { short: 20, medium: 60, long: 100, very_long: 300 }
end

#lengths=(new_lengths) ⇒ Hash

This method allows you to set new lengths for the sentences It merges the new lengths with the existing ones Example: lengths = { short: 50, medium: 150 }

Examples:

lengths = { short: 50, medium: 150 }

Parameters:

  • new_lengths (Hash)

    A hash containing the new lengths for the sentences

Returns:

  • (Hash)

    The updated lengths hash



280
281
282
# File 'lib/random-words/generator.rb', line 280

def lengths=(new_lengths)
  @lengths = lengths.merge(new_lengths)
end

#markdown(settings = {}) ⇒ String

Generate random markdown

Parameters:

  • settings (Hash) (defaults to: {})

    Settings for generating markdown

Returns:

  • (String)

    A randomly generated markdown string



418
419
420
421
422
423
424
425
426
427
428
# File 'lib/random-words/generator.rb', line 418

def markdown(settings = {})
  input = RandomWords::LoremHTML.new(settings)
  meta = {}
  if settings[:meta_type]
    meta[:type] = settings[:meta_type]
    meta[:title] = input.title if input.title
    meta[:style] = settings[:style] || 'style.css'
    meta[:date] = Time.now.strftime('%Y-%m-%d %H:%M:%S')
  end
  RandomWords::HTML2Markdown.new(input, nil, meta).to_s
end

#nameString

Generate a random name

Returns:

  • (String)

    A randomly generated name



458
459
460
# File 'lib/random-words/generator.rb', line 458

def name
  "#{dbg('NAM')}#{random_name}"
end

#paragraph(length = @paragraph_length) ⇒ String

Generate a random paragraph This method generates a random paragraph by combining multiple sentences. It uses the generate_combined_sentence method to create each sentence.

Parameters:

  • length (Integer) (defaults to: @paragraph_length)

    The desired number of sentences in the paragraph

Returns:

  • (String)

    A randomly generated paragraph

See Also:



382
383
384
385
386
387
388
# File 'lib/random-words/generator.rb', line 382

def paragraph(length = @paragraph_length)
  sentences = []
  length.times do
    sentences << generate_combined_sentence
  end
  sentences.join(' ').strip.compress
end

#sentence(length = nil) ⇒ String

Generate a random sentence

Parameters:

  • length (Integer) (defaults to: nil)

    The desired length of the sentence in characters

Returns:

  • (String)

    A randomly generated sentence



339
340
341
# File 'lib/random-words/generator.rb', line 339

def sentence(length = nil)
  generate_combined_sentence(length)
end

#sentences(number) ⇒ Array

Generate a specified number of random sentences

Examples:

sentences(5) # Generates an array of 5 random sentences

Parameters:

  • number (Integer)

    The number of sentences to generate

Returns:

  • (Array)

    An array of generated sentences



348
349
350
# File 'lib/random-words/generator.rb', line 348

def sentences(number)
  Array.new(number) { generate_combined_sentence }
end

#wordString

Generate a random word

Returns:

  • (String)

    A randomly generated word



286
287
288
# File 'lib/random-words/generator.rb', line 286

def word
  generate_word
end

#words(number) ⇒ Object

Generate a set number of random words

Parameters:

  • number (Integer)

    The number of words to generate



292
293
294
295
296
297
# File 'lib/random-words/generator.rb', line 292

def words(number)
  result = SENTENCE_PARTS.cycle.take(number).map { |part| send(part.to_sym) }.take(number)
  result.map do |word|
    word.split(/ /).last
  end.join(' ').article_agree.compress
end