Use the Ruby Captcha Gem for Rails User Registration

If you decide that you want to add captcha validation to the user registration of your ruby on rails application its really not that difficult. Make sure first to install the gem using gem install captcha.

After installing the gem you can use / modify the following code to add captcha protection to your user signups:

class NewCustomerController < ApplicationController

  require_gem 'captcha'
  layout "default"

  def index

      ################### CAPTCHA SETUP ###########################
      w = CAPTCHA::Web.new
      w.font = "/usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf"
      w.image_dir = "public/images/captcha"
      w.image_uri = "/images/captcha/"
      w.font_size = 23
      w.rotation = 28
      w.x_spacing = 6
      w.y_wiggle = 22
      @captcha_html = w.to_html

      ####### CAPTCHA VALIDATION ####################
      if params[:digest] && params[:key]
        if CAPTCHA::Web.is_valid(params[:key], params[:digest]) 
          session[:captcha] = 1
          redirect_to :controller => "user", :action => "signup"
          puts "### VALID CAPTCHA ###"
        else
          flash[:notice] = "We were unable to validate the code you entered, please try again."

          puts "### INVALID CAPTCHA ###"
        end
      end

  end
end