Skip to content

Instantly share code, notes, and snippets.

@acuppy
Last active December 20, 2015 01:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acuppy/6047543 to your computer and use it in GitHub Desktop.
Save acuppy/6047543 to your computer and use it in GitHub Desktop.
Simple abstraction layer to interact with the UNIX aspell library via Ruby
module Spelling
require 'net/https'
require 'uri'
require 'rexml/document'
ASPELL_WORD_DATA_REGEX = Regexp.new(/\&\s\w+\s\d+\s\d+(.*)$/)
ASPELL_PATH = "aspell"
#
# @param String: spell_check_text - represents the source string
# @param String: command - "checkWords" or "getSuggestions"
# @param String: lang - Languages to check against. Must match installed aspell dictionaries
# @return String: XML list of suggestions based on the provides spell_check_text
#
def check_spelling(spell_check_text, command, lang)
xml_response_values = Array.new
spell_check_text = spell_check_text.join(' ') if command == 'checkWords'
tf = Tempfile.new("aspell_buf") # adds pid
tf.write(spell_check_text)
tf.seek 0
spell_check_response = `cat #{tf.path} | aspell -a -l #{lang}`
tf.close!
# spell_check_response = `echo "#{spell_check_text}" | #{ASPELL_PATH} -a -l #{lang}`
if (spell_check_response != '')
spelling_errors = spell_check_response.split("\n").slice(1..-1)
if (command == 'checkWords')
for error in spelling_errors
error.strip!
if (match_data = error.match(ASPELL_WORD_DATA_REGEX))
arr = match_data[0].split(' ')
xml_response_values << arr[1]
end
end
elsif (command == 'getSuggestions')
for error in spelling_errors
error.strip!
if (match_data = error.match(ASPELL_WORD_DATA_REGEX))
error.slice!(/\A.*\:/)
xml_response_values << error.split(',').collect(&:strip!)
xml_response_values = xml_response_values.first
end
end
end
end
return xml_response_values
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment