Class: Konjac::Suggestor

Inherits:
Object
  • Object
show all
Defined in:
lib/konjac/suggestor.rb

Overview

A class for suggesting translations

Constant Summary collapse

SUGGEST_COUNT =

The default suggested count

10
SUGGEST_CUTOFF =

The default suggest cutoff

0.5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(from_lang, to_lang, opts = {}) ⇒ Suggestor

Creates a new Suggestor object



14
15
16
# File 'lib/konjac/suggestor.rb', line 14

def initialize(from_lang, to_lang, opts = {})
  @pairs = Dictionary.load(from_lang, to_lang, opts)
end

Instance Attribute Details

#pairsObject

A list of all pairs available



5
6
7
# File 'lib/konjac/suggestor.rb', line 5

def pairs
  @pairs
end

Instance Method Details

#suggest(word, opts = {}) ⇒ Object

Provides suggested translations for a word, providing an array containing the pair distance, fuzzy match used and the suggested replacement



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/konjac/suggestor.rb', line 20

def suggest(word, opts = {})
  # Set defaults for optional arguments
  opts = {
    :count  => SUGGEST_COUNT,
    :cutoff => SUGGEST_CUTOFF
  }.merge opts

  results = []
  matcher = Amatch::PairDistance.new(word)
  @pairs.each do |search, replace, fuzzy|
    if fuzzy.is_a?(String)
      value = matcher.match(fuzzy)
    else
      value = (search =~ word ? 1 : 0)
    end

    if (results.empty? || value > results[0][0]) && value >= opts[:cutoff]
      results << [value, fuzzy, replace]
      results.sort!
      results.shift if results.length > opts[:count]
    end
  end
  results.reverse
end