I am going to show you a basic example on how to stick ReCaptcha in your Rails application.
First of all, we are gonna need the tools,
Go ahead and register an API key at
Recaptcha. Then go ahead and install the plugin/gem at
Ambethia's Recaptcha on GitHub.
Once we got those installed and done, first thing first is to setup the API keys.
/config/environment.rb
require File.expand_path('../application', __FILE__)
ENV['RECAPTCHA_PUBLIC_KEY'] = '6LetRwwAAAAAAHYInUoOSj2mN_2dafLelpON4VzV'
ENV['RECAPTCHA_PRIVATE_KEY'] = '6LetRwwAAAAAAHYInUoOSj2mN_2dafLelpON4VzV'
RecapApp::Application.initialize!
Then we are generally gonna use Recaptcha in a form submission. Let's stick it there.
/views/posts/_form.html.erb
<%=raw recaptcha_tags %>
Then we will have to take care of the backbone in the controller. So we want Recaptcha to kick in when a user sends a POST request or submit a post.
/controllers/posts_controller.rb
def create
@post = Post.new(params[:post])
respond_to do |format|
if (verify_recaptcha(:model => @post, :message => "The captcha does not match!") && @post.save)
format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
format.xml { render :xml => @post, :status => :created, :location => @post }
format.js
else
format.html { render :action => "new" }
format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
format.js
end
end
end
The :message option will deal with the error message in the form if the captcha doesn't match.
And there you have it!