Class: Kotoshu::Suggestions::Strategies::PhoneticStrategy

Inherits:
BaseStrategy
  • Object
show all
Defined in:
lib/kotoshu/suggestions/strategies/phonetic_strategy.rb

Overview

Phonetic suggestion strategy.

Generates suggestions by finding words with similar phonetic codes using algorithms like Soundex and Metaphone.

Examples:

Creating a phonetic strategy

strategy = PhoneticStrategy.new(algorithm: :soundex)
result = strategy.generate(context)

Constant Summary collapse

ALGORITHMS =

Supported algorithms.

%i[soundex metaphone].freeze

Instance Attribute Summary

Attributes inherited from BaseStrategy

#config, #name

Instance Method Summary collapse

Methods inherited from BaseStrategy

#calculate_ngram_similarity, #create_suggestion, #create_suggestion_set, #enabled?, #generate_ngrams, #get_config, #has_config?, #max_results, #priority, #to_s

Constructor Details

#initialize(name: :phonetic, **config) ⇒ PhoneticStrategy

Create a new phonetic strategy.

Parameters:

  • name (String, Symbol) (defaults to: :phonetic)

    Name of the strategy

  • config (Hash)

    Configuration options

Options Hash (**config):

  • algorithm (Symbol)

    The algorithm to use (:soundex or :metaphone)

  • max_results (Integer)

    Maximum results to return



24
25
26
# File 'lib/kotoshu/suggestions/strategies/phonetic_strategy.rb', line 24

def initialize(name: :phonetic, **config)
  super(name: name, **config)
end

Instance Method Details

#generate(context) ⇒ SuggestionSet

Generate suggestions based on phonetic similarity.

Parameters:

  • context (Context)

    The suggestion context

Returns:



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
# File 'lib/kotoshu/suggestions/strategies/phonetic_strategy.rb', line 32

def generate(context)
  word = context.word
  algorithm = get_config(:algorithm, :soundex)
  max_dist = 2

  all_words = dictionary_words(context)

  # Get phonetic code for input word
  word_code = phonetic_code(word, algorithm)

  # Find words with same phonetic code
  results = []
  all_words.each do |dict_word|
    next if dict_word == word

    dict_code = phonetic_code(dict_word, algorithm)
    next unless dict_code == word_code

    dist = edit_distance(word, dict_word)
    next if dist > max_dist || dist.zero?

    results << [dict_word, dist]
  end

  # Sort by distance and convert to suggestions
  sorted_words = results.sort_by { |_, dist| dist }.map(&:first)
  create_suggestion_set(sorted_words)
end

#handles?(context) ⇒ Boolean

Check if this strategy should handle the context.

Parameters:

  • context (Context)

    The suggestion context

Returns:

  • (Boolean)

    True if the word needs correction



65
66
67
68
69
# File 'lib/kotoshu/suggestions/strategies/phonetic_strategy.rb', line 65

def handles?(context)
  return false unless enabled?

  !dictionary_lookup(context, context.word)
end