Class: Forspell::Speller
- Inherits:
-
Object
- Object
- Forspell::Speller
- Defined in:
- lib/forspell/speller.rb
Constant Summary collapse
- HUNSPELL_DIRS =
[File.join(__dir__, 'dictionaries')]
- RUBY_DICT =
File.join(__dir__, 'ruby.dict')
Instance Attribute Summary collapse
-
#dictionary ⇒ Object
readonly
Returns the value of attribute dictionary.
Instance Method Summary collapse
- #correct?(word) ⇒ Boolean
-
#initialize(main_dictionary, *custom_dictionaries, suggestions_size: 0) ⇒ Speller
constructor
A new instance of Speller.
- #suggest(word) ⇒ Object
Constructor Details
#initialize(main_dictionary, *custom_dictionaries, suggestions_size: 0) ⇒ Speller
Returns a new instance of Speller.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/forspell/speller.rb', line 13 def initialize(main_dictionary, *custom_dictionaries, suggestions_size: 0) @suggestions_size = suggestions_size FFI::Hunspell.directories = HUNSPELL_DIRS << File.dirname(main_dictionary) @dictionary = FFI::Hunspell.dict(File.basename(main_dictionary)) [RUBY_DICT, *custom_dictionaries].flat_map { |path| File.read(path).split("\n") } .compact .map { |line| line.gsub(/\s*\#.*$/, '') } .reject(&:empty?) .map { |line| line.split(/\s*:\s*/, 2) } .each do |word, example| example ? @dictionary.add_with_affix(word, example) : @dictionary.add(word) end rescue ArgumentError puts "Unable to find dictionary #{main_dictionary}" exit(2) end |
Instance Attribute Details
#dictionary ⇒ Object (readonly)
Returns the value of attribute dictionary.
8 9 10 |
# File 'lib/forspell/speller.rb', line 8 def dictionary @dictionary end |
Instance Method Details
#correct?(word) ⇒ Boolean
31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/forspell/speller.rb', line 31 def correct?(word) parts = word.split('-') if parts.size == 1 alterations = [word] alterations << word.capitalize unless word.capitalize == word alterations << word.upcase unless word.upcase == word alterations.any?{ |w| dictionary.check?(w) } else dictionary.check?(word) || parts.all? { |part| correct?(part) } end end |
#suggest(word) ⇒ Object
44 45 46 |
# File 'lib/forspell/speller.rb', line 44 def suggest(word) @suggestions_size.positive? ? dictionary.suggest(word).first(@suggestions_size) - [word, word.capitalize] : [] end |