Class: Kotoshu::Suggestions::Strategies::PhoneticStrategy
- Inherits:
-
BaseStrategy
- Object
- BaseStrategy
- Kotoshu::Suggestions::Strategies::PhoneticStrategy
- 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.
Constant Summary collapse
- ALGORITHMS =
Supported algorithms.
%i[soundex metaphone].freeze
Instance Attribute Summary
Attributes inherited from BaseStrategy
Instance Method Summary collapse
-
#generate(context) ⇒ SuggestionSet
Generate suggestions based on phonetic similarity.
-
#handles?(context) ⇒ Boolean
Check if this strategy should handle the context.
-
#initialize(name: :phonetic, **config) ⇒ PhoneticStrategy
constructor
Create a new phonetic strategy.
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.
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.
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.
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 |