Class: Spellchecker

Inherits:
Object
  • Object
show all
Defined in:
lib/middleman-spellcheck/spellchecker.rb

Constant Summary collapse

ASPELL_WORD_DATA_REGEX =
Regexp.new(/\&\s\w+\s\d+\s\d+(.*)$/)
@@aspell_path =
"aspell"

Class Method Summary collapse

Class Method Details

.aspell_pathObject



14
15
16
# File 'lib/middleman-spellcheck/spellchecker.rb', line 14

def self.aspell_path
  @@aspell_path
end

.aspell_path=(path) ⇒ Object



10
11
12
# File 'lib/middleman-spellcheck/spellchecker.rb', line 10

def self.aspell_path=(path)
  @@aspell_path = path
end

.check(text, lang = 'en') ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/middleman-spellcheck/spellchecker.rb', line 18

def self.check(text, lang='en')
  tmp = Tempfile.new('spellchecker-tmp')
  tmp << text
  tmp.flush
  tmp.close
  spell_check_response = `cat "#{tmp.path}" | #{@@aspell_path} -a -l #{lang}`
  if spell_check_response == ''
    raise 'Aspell command not found'
  elsif text == ''
    return []
  else
    response = text.split(' ').collect { |original| {:original => original} }
    results = spell_check_response.split("\n").slice(1..-1)
    result_index = 0
    response.each_with_index do |word_hash, index|
      if word_hash[:original] =~ /[a-zA-z\[\]\?]/
        if results[result_index] =~ ASPELL_WORD_DATA_REGEX
          response[index].merge!(:correct => false, :suggestions => results[result_index].split(':')[1].strip.split(',').map(&:strip))
        else
          response[index].merge!(:correct => true)
        end
        result_index += 1
      else
        response[index].merge!(:correct => true)
      end
    end
    return response
  end
end