Class: WordsMatrix::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/words_matrix/service.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Service

Returns a new instance of Service.



4
5
6
7
8
9
10
11
12
13
14
# File 'lib/words_matrix/service.rb', line 4

def initialize(config={})
  config = WordsMatrix::Config::DEFAULTS.merge(config) { |key, default, local|
    local || default
  }

  validate_options!(config)
  @matrix = WordsMatrix::Matrix.new(config[:n].to_i, config[:min_length].to_i)
  @dictionary = WordsMatrix::Dictionary.new(config[:min_length].to_i, config[:n].to_i, config[:dict_path])

  @words = []
end

Instance Attribute Details

#dictionaryObject (readonly)

Returns the value of attribute dictionary.



2
3
4
# File 'lib/words_matrix/service.rb', line 2

def dictionary
  @dictionary
end

#matrixObject (readonly)

Returns the value of attribute matrix.



2
3
4
# File 'lib/words_matrix/service.rb', line 2

def matrix
  @matrix
end

#wordsObject (readonly)

Returns the value of attribute words.



2
3
4
# File 'lib/words_matrix/service.rb', line 2

def words
  @words
end

Instance Method Details

#find_wordsObject



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/words_matrix/service.rb', line 16

def find_words
  @matrix.tokens.each_pair do |letter, tokens|
    next unless @dictionary.words.has_key?(letter)
    words = @dictionary.words[letter].keys

    tokens.each do |token|
      words_found = words.select { |word| token =~ /^#{word}.*/ }

      @words += words_found.map { |word| @dictionary.words[letter][word] }
    end
  end
  @words.uniq!
end

#to_sObject



30
31
32
33
34
35
36
37
# File 'lib/words_matrix/service.rb', line 30

def to_s
  words_found = @words.any? ? @words.join("\n") : "none :("
  ["Matrix:",
    matrix.to_s,
    "",
    "Words found:",
    words_found].join("\n")
end