Class: Uniword::Spellcheck::HunspellAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/uniword/spellcheck/hunspell_adapter.rb

Overview

Thin wrapper around the hunspell command-line spell checker.

Responsibility: Interface with the hunspell binary for spell checking and suggestion retrieval.

Examples:

Check a word

adapter = HunspellAdapter.new(language: "en_US")
adapter.check("hello")  #=> true
adapter.check("helo")   #=> false

Get suggestions

adapter.suggest("helo")  #=> ["hello", "helot", ...]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(language: "en_US") ⇒ HunspellAdapter

Initialize the hunspell adapter.

Parameters:

  • language (String) (defaults to: "en_US")

    Dictionary language (default: “en_US”)

Raises:



26
27
28
29
# File 'lib/uniword/spellcheck/hunspell_adapter.rb', line 26

def initialize(language: "en_US")
  @language = language
  verify_hunspell!
end

Instance Attribute Details

#languageObject (readonly)

Returns the value of attribute language.



20
21
22
# File 'lib/uniword/spellcheck/hunspell_adapter.rb', line 20

def language
  @language
end

Instance Method Details

#check(word) ⇒ Boolean

Check whether a word is spelled correctly.

Parameters:

  • word (String)

    The word to check

Returns:

  • (Boolean)

    true if word is correct, false otherwise



35
36
37
38
39
40
41
42
43
44
# File 'lib/uniword/spellcheck/hunspell_adapter.rb', line 35

def check(word)
  return true if word.strip.empty?
  return true unless word.match?(/\p{L}/)

  stdout, _stderr, _status = Open3.capture3(
    "hunspell", "-d", language, "-l",
    stdin_data: "#{word}\n"
  )
  stdout.strip.empty?
end

#suggest(word) ⇒ Array<String>

Get spelling suggestions for a word.

Parameters:

  • word (String)

    The word to get suggestions for

Returns:

  • (Array<String>)

    Array of suggested corrections



50
51
52
53
54
55
56
57
58
59
# File 'lib/uniword/spellcheck/hunspell_adapter.rb', line 50

def suggest(word)
  return [] if word.strip.empty?
  return [] unless word.match?(/\p{L}/)

  stdout, _stderr, _status = Open3.capture3(
    "hunspell", "-d", language, "-a",
    stdin_data: "#{word}\n"
  )
  parse_suggestions(stdout)
end