Class: MarkovWords::Generator

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

Overview

This class takes care of word generation, and will store the database into a FileStore object.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Words

Create a new "Words" object

Parameters:

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

Options Hash (opts):

  • :corpus_file (String) — default: '/usr/share/dict/words'

    Your dictionary of words.

  • :data_file (String)

    Location where calculations are persisted to disk.

  • :flush_data (String)

    Remove any previously-stored data from an existing database file.

  • :gram_size (Integer) — default: 2

    Number of n-grams to compute for your database.

  • :max_length (Integer) — default: 16

    Max generated word length.

  • :min_length (Integer) — default: 3

    Minimum generated word length. NOTE: If your corpus size is very small (<1000 words or so), it's hard to guarantee a min_length because so many n-grams will have no association, which terminates word generation.



39
40
41
42
43
44
45
46
# File 'lib/markov_words/generator.rb', line 39

def initialize(opts = {})
  @grams = nil
  @gram_size = opts.fetch :gram_size, 2
  @max_length = opts.fetch :max_length, 16
  @min_length = opts.fetch :min_length, 3

  initialize_data(opts)
end

Instance Attribute Details

#data_storeObject (readonly)

It's useful to be able to access the data store object directly, for example if you were to want to implement storage of related metadata into the same storage system that holds the database.



10
11
12
# File 'lib/markov_words/generator.rb', line 10

def data_store
  @data_store
end

Instance Method Details

#gramsHash

The current database of n-gram mappings

Returns:

  • (Hash)

    n-gram database



14
15
16
17
18
19
20
21
# File 'lib/markov_words/generator.rb', line 14

def grams
  if @grams.nil?
    @grams = @data_store.retrieve_data(:grams) ||
             markov_corpus(@corpus_file, @gram_size)
  else
    @grams
  end
end

#wordString

Generate a new word

Returns:

  • (String)

    The word.



50
51
52
# File 'lib/markov_words/generator.rb', line 50

def word
  generate_word
end