Skip to content

Instantly share code, notes, and snippets.

@jrust
Created October 7, 2010 21:25
Show Gist options
  • Save jrust/615914 to your computer and use it in GitHub Desktop.
Save jrust/615914 to your computer and use it in GitHub Desktop.
# Queries the Google spellcheck API to allow for determining misspelled words
# as well as providing corrective suggestions.
#
# Largely taken from the TinyMCE PHP Spellchecker plugin
module GoogleSpellchecker
require 'net/https'
require 'uri'
require 'builder'
def check_spelling(spell_check_text, lang='en')
matches = get_matches spell_check_text, lang
words = []
matches.each do |match|
words << spell_check_text[match[0].to_i, match[1].to_i]
end
words
end
def get_spelling_suggestions(word, lang='en')
matches = get_matches word, lang
if matches.length > 0
matches[0][3].split(/\s/).delete_if {|s| s.blank? }
else
[]
end
end
private
def get_matches(str, lang)
xml = Builder::XmlMarkup.new
xml.instruct!
xml.spellrequest(:textalreadyclipped => 0, :ignoredups => 0, :ignoredigits => 0, :ignoreallcaps => 1) do
xml.text str
end
http = Net::HTTP.new("www.google.com", 443)
http.use_ssl = true
http.start do |req|
@response = req.post("/tbproxy/spell?lang=#{lang}&hl=en", xml.target!)
end
if @response.code.to_i < 400
@response.body.scan %r{<c o="(.*?)" l="(.*?)" s="(.*?)">(.*?)</c>}
else
[]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment