Recaptchaed is a project mainly written in Ruby, based on the MIT license.
rails plugin gem that makes it easy to add recaptcha to forms
Rails Plugin for adding "recaptcha(recaptcha)":http://www.google.com/recaptcha to a form.
@gem install recaptchaed@
Open config/environment.rb and enter the following:
@config.gem "recaptchaed"@
@script/generate recaptchaed@
If it runs successfully, you should see the following:
@ create config/recaptchaed.yml create config/initializers/recaptchaed.rb added recaptcha i18n error message to config/locales/en.yml @
This example shows how to protect a comment model with a recaptcha
@<%=javascript_include_tag 'http://www.google.com/recaptcha/api/js/recaptcha_ajax.js' %>@
@
<% form_for(@comment) do |f| %> <%= f.error_messages %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :body %>
<%= f.text_area :body %>
<%= recaptcha_tag (RECAPTCHAED["RECAPTCHA_PUBLIC_KEY"], "recaptcha_div", "blackglass") %>
<%= f.submit 'Create' %>
<% end %>
<%= link_to 'Back', comments_path %> @
The "recaptcha site(recaptcha)":http://code.google.com/apis/recaptcha/docs/customization.html has several options for different themes/styles. For example, you can change the theme of the recaptcha to 'white' by passing a different theme string.
@ <%= recaptcha_tag (RECAPTCHAED["RECAPTCHA_PUBLIC_KEY"], "recaptcha_div", "white") %> @
First, include the library in the comments controller:
@ class CommentsController < ApplicationController include Recaptchaed ...rest of controller... end @
Then, protect the create method using the 'validate_captcha(..)' method
@
def create @comment = Comment.new(params[:comment])
@recaptcha = validate_captcha(RECAPTCHAED["RECAPTCHA_PRIVATE_KEY"], request.remote_ip, params['recaptcha_challenge_field'], params['recaptcha_response_field'])
respond_to do |format|
if @recaptcha && @recaptcha['success'] && @comment.save
flash[:notice] = 'Comment was successfully created.'
format.html { redirect_to(@comment) }
format.xml { render :xml => @comment, :status => :created, :location => @comment }
else
if(!@recaptcha['success'])
@comment.errors.add('recaptcha_response_field', :"recaptcha.invalid")
end
format.html { render :action => "new" }
format.xml { render :xml => @comment.errors, :status => :unprocessable_entity }
end
end
end @
When a user fails to enter the correct captcha, the error message that is displayed is defined inside 'config/locales/en.yml'. Feel free to update that to whatever you like. And, it can also be internationalized, if needed.
Enjoy!
http://upgradingdave.com Copyright (c) 2010 Dave Paroulek, released under the MIT license