Tuesday, February 26, 2008

Getting TinyMCE 3.0 Spellchecker to work with Rails

In new version of TinyMCE editor there are many changes in plug ins. The Plug in code is changed. The popular spell checker plug in now uses JSON as transport mechanism instead of XML. In my example we are using Aspell to check spellings, so you must have Aspell installed on your system for this example to work

Issue this command on CLI to check if Aspell is installed:

% aspell


You should see help output related to command

First of all you need to install JSON gem to parse JSON requests

% sudo gem install json


Then write this action in a controller:

require json

def spellcheck
raw = request.env['RAW_POST_DATA']
req = JSON.parse(raw)
lang = req["params"][0]
if req["method"] == 'checkWords'
text_to_check = req["params"][1].join(" ")
else
text_to_check = req["params"][1]
end
suggestions = check_spelling_new(text_to_check, req["method"], lang)
render :json => {"id" => nil, "result" => suggestions, "error" => nil}.to_json
return
end


Now also write this method in private section of controller:

def check_spelling_new(spell_check_text, command, lang)
json_response_values = Array.new
spell_check_response = `echo "#{spell_check_text}" | aspell -a -l #{lang}`
if (spell_check_response != '')
spelling_errors = spell_check_response.split(' ').slice(1..-1)
if (command == 'checkWords')
i = 0
while i < spelling_errors.length
spelling_errors[i].strip!
if (spelling_errors[i].to_s.index('&') == 0)
match_data = spelling_errors[i + 1]
json_response_values << match_data
end
i += 1
end
elsif (command == 'getSuggestions')
arr = spell_check_response.split(':')
suggestion_string = arr[1]
suggestions = suggestion_string.split(',')
for suggestion in suggestions
suggestion.strip!
json_response_values << suggestion
end
end
end
return json_response_values
end


now you need to open /plugins/spellchecker/editor_plugin.js file under your Tiny MCE directory. Search for this line;

t.url = url;


and change it to:

t.url = 'http://www.yourhostname.com';


then search for this line:

var t = this, url = t.editor.getParam("spellchecker_rpc_url", this.url+'/rpc.php');


and change it to:

var t = this, url = t.editor.getParam("spellchecker_rpc_url", this.url+'/spellcheck');


and to make this work just add this route to routes.rb under config folder

map.connect '/spellcheck', :controller => 'your_controller_name', :action => 'spellcheck'
#replace your_controller_name with name of our controller in which the spellcheck action is written