The Kai Way

Pragmaticly hacking

Check Spelling on Rails

| Comments

A few days ago I need to do spell checking for a rails project, but can’t find a ready-to-use plugin, so I implemented one.

I use the Aspell Lib to do the checking work, and ajax for editing.

First you need to install the Aspell and at lease one dictionary.

Mac: sudo port install aspell aspell-dict-en

Ubuntu: sudo apt-get install aspell libaspell-dev aspell-en

Arch: sudo pacman -S aspell aspell-en

And install the Aspell Ruby binding: raspell

sudo gem install raspell

Add a controller:

# app/controllers/spelling_controller.rb
class SpellingController << ApplicationController
  def check
    render :update do |page|
      page.replace_html 'check-result', SpellingChecker.check_spell(params[:text])

Add a SpellingChecker Class to Lib # lib/spelling_checker.rb class SpellingChecker

  def self.check_spell text
    speller ="en_US")
    speller.suggestion_mode = Aspell::NORMAL
    wrongs = []
    text.gsub(/[\w\']+/) do |word|
      wrongs << word unless speller.check(word)
    wrongs.uniq.each do |wrong|
      text.sub!(wrong, "<span class='wrong'>#{wrong}</span>")
    return text


in the view:

<%=link_to_function ‘Check spelling’, “new Ajax.Updater({ success:toggleChecking()}, ‘/spelling/check’, {method:‘get’, parameters:{text:$F(‘ticket_description’)}});” %>
<%= f.text_area :description, :cols => 84, :rows => 10 %>

This is what it looks like:

That is it, quite sample, isn’t it? I would like to make a plugin for it, but no much time recently.

Thank yawl for pointing out my grammar misstake.