Code and Coffee


Implementing a Captcha with Ruby on Rails in 10 Minutes or Less

Posted on June 20, 2007, under Code Snippets, Development.

I needed to put together a captcha fifteen minutes before a demo the other day, so I scrambled a researched for five minutes and settled on Simple Captcha. It had the features I needed, and looked like it could be implemented fast. So how did I accomplish this, well simple:

Install ImageMagick:

You can get your hands on the binary releases here, and install them appropriately for your Operating System.

Install RMagick:

On Linux, it was actually as simple as this:

sudo gem install rmagick

Here are the install instructions for OSX and for Windows you will need to get the rmagick-win32 gem.

Install the Simple Captcha Plugin:

From your application root, you can run:

ruby script\plugin install svn://rubyforge.org/var/svn/expressica/plugins/simple_captcha

Done!

In Your Code:

To show a captcha in your view, just use the following tag:

<%= show_simple_captcha %>

There are further formatting options that you can use to configure the captcha image.

In your controller to validate:

—-
if simple_captcha_valid?
end

—-The site has further examples on how to implement a model based approach, but my quick needs this was good. Later on I went back and cleaned it up some, and attached it to a model with further conditions.

If you already have ImageMagick install, getting up and running with Simple Captch will be even quicker. For some Linux distributions, you might have to install ImageMagick from source which might cause some problems for those not too familiar on how to do this.

Simple Captcha Features:

  • Provides eight different style of images
  • Can be implemented as controller based or model based
  • Automated removal of old images(one hour old)
  • Now, we can add customized CSS to the image, lable and the text field
  • Simple Captcha will bypass the functional/unit tests, so the there will not be any mess in our test cases.
  • Provides three levels of distortion of images as low, medium or high… so now, we have three levels for complexities of images.

Popularity: 17% [?]



3 Replies to "Implementing a Captcha with Ruby on Rails in 10 Minutes or Less"

gravatar

Benjamin Miller  on June 21, 2007

The Flash code source doesn’t load in the page in either of my browers.

MacOS X 10.4.10
Safari 2.0.4 (419.3)
Firefox 2.0.0.4
Flash 9.0.28.0

gravatar

monozub  on June 21, 2007

I can not see any flash either.

firefox 2.0.0.4
winxp (unfortunately :))

gravatar

Matthew R. Miller  on June 21, 2007

I removed the flash text formatter until I have time later tonight to see what was wrong. Sorry guys!