Hello again, coders!
I’d like to talk about captcha (again). Yes, I have a bad experience with captcha for ruby on rails, especially rails 3. At first, I picked simple_captcha as my captcha plugin, but I didn’t see any good prospect from it. I should admit that the captcha image is simple and easy to read, but there always problems with it, especially in deployment. This time the simple_captcha didn’t display the image, and from every article that I had read, I couldn’t find the solution for it. I decided, I had to change the plugin and I chose reCaptcha.
It’s really easy and even easier than simple_captcha. The first step you have to do is go to reCaptcha site and register your site name with your google account to retrieve public and private key that will be used later on. After you register it, you will get the key and keep it for recaptcha configuration in rails.
Let’s get into the application
- Open your Gemfile and add this code :
gem 'recaptcha', :require => 'recaptcha/rails'
- I also install the source with
rails plugin install git://github.com/ambethia/recaptcha.git
- Create a file named
RAILS_ROO/config/initializerand fill it with these codes :
ENV['RECAPTCHA_PUBLIC_KEY'] = 'youractualpublickey' ENV['RECAPTCHA_PRIVATE_KEY'] = 'youractualprivatekey'
- Open your views file and add this code :
<%= recaptcha_tags %>
- In your controller, you can check the captcha validation with these codes
if verify_recaptcha #captcha is valid else #captcha is invalid end
Booyah! The captcha is all set in your rails app. Easy isn’t it? But don’t forget, recaptcha is case sensitive, so you have to be careful in filling in the code for validating captcha.