check spelling on rails

09月 11, 2008 · Posted in Agile, Promgramming · Comment 

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:

  1. # app/controllers/spelling_controller.rb
  2. class SpellingController << ApplicationController
  3.   def check
  4.     render :update do |page|
  5.       page.replace_html 'check-result', SpellingChecker.check_spell(params[:text])
  6.     end
  7.   end
  8. end

Add a SpellingChecker Class to Lib

  1. # lib/spelling_checker.rb
  2. class SpellingChecker
  3.  
  4.   def self.check_spell text
  5.     speller = Aspell.new("en_US")
  6.     speller.suggestion_mode = Aspell::NORMAL
  7.     wrongs = []
  8.     text.gsub(/[\w\']+/) do |word|
  9.       wrongs << word unless speller.check(word)
  10.     end
  11.     wrongs.uniq.each do |wrong|
  12.       text.sub!(wrong, "<span class='wrong'>#{wrong}</span>")
  13.     end
  14.     return text
  15.   end
  16.  
  17. end

in the view:

  1. <label for="description">Description: </label>
  2.   <div id="check-desc" style="display:none;">
  3.     <%=link_to_function 'Resume editing', "ttoggleChecking()" %>
  4.     <br />
  5.     <div id="check-result">Checking...</div>
  6.   </div>
  7.   <div id="edit-desc">
  8.     <%=link_to_function 'Check spelling', "new Ajax.Updater({ success:toggleChecking()},
  9.                                                             '/spelling/check',
  10.                                                             {method:'get', parameters:{text:$F('ticket_description')}});" %>
  11.     <br />
  12.     <%= f.text_area :description, :cols => 84, :rows => 10 %>
  13.   </div>
  14.   <script type='text/javascript'>
  15.     function toggleChecking() {
  16.       $('edit-desc', 'check-desc').invoke('toggle');
  17.     }
  18.   </script>

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.