Monday, July 26, 2010

TinyMCE:Plugins - spellchecker on rails using aspell

TinyMCE:Plugins - spellchecker right now available on PHP Spellchecker. You can check latest TinyMCE Editor on http://tinymce.moxiecode.com/download.php.

Today I'll try to share about how to make spellchecker work on rails environment.

What we need are :
  • aspell
  • json gem
  • TinyMCE editor
  • spellchecker plugin

First we need aspell installed.

We can check it using terminal. Open terminal and type aspell.
aspell


How to install aspell
sudo apt-get install aspell


How to install json gem
sudo gem install json


Now we modify tiny_mce/plugins/spellchecker/editor_plugin.js
on init funtion search
g.url=f;


then replace it with
var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
g.url='http://' + f.match(re)[1].toString();


then search
g.rpcUrl=e.getParam("spellchecker_rpc_url",this.url+'/rpc.php');


then replace it with
g.rpcUrl=e.getParam("spellchecker_rpc_url",this.url+'/spellcheck');


preview before edited

init:function(e,f){
var g=this,d;
g.url=f;
g.editor=e;
g.rpcUrl=e.getParam("spellchecker_rpc_url",this.url+'/rpc.php');
if(g.rpcUrl=="{backend}"){


after edited

init:function(e,f){
var g=this,d;
var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
g.url='http://' + f.match(re)[1].toString();
g.editor=e;
g.rpcUrl=e.getParam("spellchecker_rpc_url",this.url+'/spellcheck');


Now we must add rails script for run aspell and return the value on json back to web. On this example I add it on HomeController.


class HomeController < ApplicationController

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

private
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

end


Last action is add this to config/routes.rb
map.connect '/spellcheck', :controller => 'home', :action => 'spellcheck'

1 comment: