Sneaky Abstractions

Subscribe to my Feed, follow me on , recommend me on Working With Rails or see my code on GitHub

ValidatesCaptcha

API SVN

ValidatesCaptcha provides CAPTCHA for your Rails application, if you really, really need it. It has two types of “challenges” built-in, the familiar image challenge and the increasingly familiar logic challenge. The latter is the better choice, because the image challenge is much more inaccessible, and it depends on RMagick. This plugin is a little outdated, but I guess it still works as well as it ever has.

Quick how-to

There’s a few different things you can customise, but you can read about that in the API reference, so I’ll keep this short and simple and only go through setting up the logic challenge.

Before starting, install the plugin with the script/plugin script in your RAILS_ROOT.

script/plugin install http://nimrod.interinter.net/plugins/trunk/validates_captcha

Prepare application

After that, the first thing you need to do is make sure there’s a writable directory where the challenges can be stored in a PStore file (no, it doesn’t scale well :-). You can create this with the built-in generator:

script/generate captcha store_directory

Then generate a captcha.yml configuration file:

script/generate captcha config

The generated config file should be pretty easy to figure out just by reading it.

Model

class Comment < ActiveRecord::Base
  validates_captcha
end

View

<% c = prepare_captcha :type => :question -%>
<%= captcha_hidden_field c, 'comment' %>
<%= captcha_question_as_label c, 'comment' %>
<%= captcha_text_field 'comment' %>

Controller

def create
  comment = Comment.new(params[:comment])

  if comment.save #Captcha passed
    flash[:notice] = 'Comment was saved'
    redirect_to comments_url
  else #Captcha not passed, or other validation error
    flash[:error] = 'Could not save comment'
    redirect_to new_comment_url
  end
end

Comments

142 comments

This is your first class ticket to high speed action and you're in the driver's seat