Garbage Burrito!

An internet web blog by Ben Kittrell

YUI Editor Spell Checker with Rails

YUI Editor Spell Checker with Rails
Ben Kittrell - 06/01/2010 15:34:00
Comments: 1
Dav Glass has a great spell checker example on his blog, and it's pretty easy to get it working with Ruby on Rails and Aspell.

Rails

First you'll need to install Raspell and it's dependencies.  

Next you'll need an action to call this.  I already had an Editor controller for other stuff like image browsing, so I just added this action.

def spellcheck
  spell = Aspell.new
  spell.set_option("mode", "html")
  words = spell.list_misspelled([params[:text]])

  checked = { :check => :spelling,
    :data => words.map { |word|
      {
        :word => word,
        :suggestions => spell.suggest(word)
      }
    }
  }
  render :json => checked.to_json
end


Fairly straightforward.  It looks for misspelled words and returns a JSON object with the results.  The set_option("mode", "html") is important because it makes Aspell ignore text that's part of an HTML tag.

JavaScript

I modified Dav's script slightly, you can grab my version here.  There are three main differences.  First I made the script a function of the Editor object, so that it could be initialized on command.  I'll show how to do that later.

Then I changed the Ajax request to POST the HTML back to the action for checking.

this._conn = YAHOO.util.Connect.asyncRequest('POST', '/editor/spellcheck', {
    success: this._checkSpelling,
    failure: function() {},
    scope: this
}, 'text=' + escape(this.getEditorHTML()));


Finally I changed the replacement regular expression to ingore text inside HTML tags and to look for word boundaries.  

html = html.replace(new RegExp('\\b' + data.data[i].word + '(?![^<]*>)\\b', 'g'), '<span class="yui-spellcheck">' + data.data[i].word + '</span>');

So to get the Javascript side working just copy my script into a .js file and load that in the HTML.  Some time after the editor is initialized call...

editor.initSpellChecker();

Make sure to add a button...

{ type: 'push', label: 'Check Spelling', value: 'spellcheck' }
 
... and add the Highlight CSS to your main editor config ....

extracss: '.yui-spellcheck { background-color: yellow; }'
 
Comments: 1

Comments

1. Emmanuel  |  my website   |   07/16/2010 02:32:54

Thank you this will surely be very handy for my Ruby projects :)

Post a Comment


Please enter the word below.


powered by Doodlekit™ Free Website Builder by Doodlebit™ Website Company