Hello Everyone !!
I have released a captcha plugin Simple Captcha. It is really simple to implement, and provides a cool feature of multiple styles of images. Visit here for more explanation.
Previous post on validates_captcha
———————————————————
To implement captcha in RubyonRails, validates_captcha plugin can be a good option but a small customization i need with this plugin was to use it on some specific action and not to be validated the captcha field every time an instance of the model is saved or updated.
Here is a small work-around for its customization…
How to use customized captcha in RoR ?
Install the plugin validates_captcha in your rails application by running this command from the root of your application
ruby script/plugin install http://svn.2750flesk.com/validates_captcha
Make sure that you can now see the directory vedor/plugins/validates_captcha.
Now run these commands from your application root to make the image and data directories
ruby script/generate captcha store_directory ruby script/generate captcha image_directory
Here is the complete API for the usage of this plugin. I am describing the same idea as given in this API but in a bit more specific means.
Lets consider a model User in which we will implement the captcha.
Add the following code in the file app/models/user.rb
class User < ActiveRecord::Base
validates_captcha :if => :request_captcha_validation?
attr_accessor :request_captcha_validation
def request_captcha_validation?
(self.request_captcha_validation==true)? true : false
end
end
Handle View and Controller
Add the code in the view inside your existing form.
<% c = prepare_captcha :type => :image -%> <%= captcha_hidden_field c, 'user' %> <%= captcha_image_tag c %> <%= captcha_label 'user', 'Type in the text from the image above' %> <%= captcha_text_field 'user' %>
Your controller will look like
def save
# the line in bold represents that you need captcha validation.
# if captcha validation is not required then remove this line from your controller.
@user = User.new(params[:user])
@user.request_captcha_validation = true
@user.save
end
However image is too noisy and it contains repeated strings.
To improve the quality of images generated by the plugin validates_captcha visit Here.
34 Comments to "Captcha in Ruby on Rails - Customize the use of captcha in the plugin validates_captcha"
Please share your thoughts
Filed in: captcha, image, rails, ror, validations


it’s givng me an error like
d Showing app/views/comment/_comment_template.rhtml where line #75 raised:
directory script/../config/../var/data does not exist
Extracted source (around line #75):
72:
73:
74:
75: :image -%>
76:
77:
78:
Showing app/views/comment/_comment_template.rhtml where line #75 raised:
directory script/../config/../var/data does not exist
Extracted source (around line #75):
72:
73:
74:
75: :image -%>
76:
77:
78:
Hi Chintan,
sorry for that !!
I havent given the information to generate the image and data directory…
please run these commands from the root of your application.
ruby script/generate captcha store_directory
ruby script/generate captcha image_directory
Restart the server and test if it is working !!
thnx a lot for a giving a fast reply
i got an error when i upload the project on the production server like,
Postscript delegate failed Extracted source (around line #6):
3:
4: :image -%>
5:
6:
7:
8:
9:
Make sure u have installed RMagick, ImageMagick etc… properly on the linux server…
Whats you local machine… is it windows ? Is it running fine on your local machine ?
I am trying to validate the captcha in the controller and getting the following error
undefined method `captcha_valid?’ for #
After taking a deep look in the API, I see that the following file is missing and I have even updated the plugin and in fact I even uninstalled it and reinstalled the plugin and still couldn’t find the file.
lib/add_captcha_to_action_controller.rb
Can some body please email me the file to the following email address:
paddy[dot]in[at]gmail[dot]com.
or can tell me where to download this file.
Many Thanks!
-Paddy
Hi Paddy,
there is no such file in the plugin validates_captcha.
How did u find that we need it ?
Are you getting any error regarding the missing file ?
Thank you for your response Sur!
I am getting “undefined method `captcha_valid?’ for #HomeController”
I am trying to validate the captcha in the controller and so there is a method named “captcha_valid?” and it resides in the file ” lib/add_captcha_to_action_controller.rb ”
Here is the API and you can access it:
http://dev.2750flesk.com/validates_captcha/classes/FleskPlugins/Captcha/Verifications/InstanceMethods.html
Thank you
-Paddy
Hi Paddy,
If you only need to check valid , you can do it by checking @user.valid? (@user or an instance of your model class).
could you send me the code that how you are using the plugin, i havent tried it as controller centric way yet.
thnx a lot Sur
Thank you for your response Sur!
I don’t use any model for this as its just plain contact me form and I’ll be just accessing it via params only and its a Action Mailer.
I don’t have the code right now and will paste in few hours of time.
Thank you
-Paddy
Thanks sur!
I just created a dummy model and it works!
Thank you
-Paddy
Thanks a lot.. running fine…
A small problem I don’t know yet how to solve it :
on error, my input text field got a colored background, using a CSS class
.fieldWithErrors input, .fieldWithErrors select {
background-color: #ffdfdf;
}
It’s working fine for all my form fileds except the captcha one :
mine..
td class=”label” Email address: /td
td class=”label” %= f.text_field :email_address, { :maxlength => “60″, :size => “30″, :tabindex => “4″ } % /td
captcha
td class=”label” %= captcha_label “user”, “Tapez le texte de l’image” % /td
td class=”label” %= captcha_text_field “user” % /td
any clue ?
Erwin
On error the input field should be in a DIV with class : fieldWithErrors…
where is this field generated ?
hi & thanks for the nice article,
i’ve probably a newbie question ,-) as I get a:
undefined method `validates_captcha' for AppointmentController:Classwhile using the captcha in a littlebit different approach
validates_captcha :only => [ :sendemails ](so i don’t define the additional method and the accessor)
the necessary directories have been generated and i’ve restarted the server. still it seems my rails environment doesn’t really know about this validation? do i need to add some sort of ‘require’ somewhere
thanks,
rossnet
Hi rossnet,
I think u are implementing the captcha in controller… i am not sure if u want in that way or not but make it confirm that if u want captcha as controller centric then what to define exactly.
However we put validates_captcha in the model class.
What say?
D’oh! Stupid me…
Thanks for the quick reply - of course you’re absolutly right. There doesn’t seem to be a “:only” clause like on filters on the validations, so I implemented it the way you described above
I think I still was confused after I learned in a couple of hours of slight frustration that you need to be very careful what’s stored in a session when you change something in the model definition, as this change isn’t reflected until you restart the session (or maybe put the derived object again into the session).
Cheers again,
rossnet
Thanks Rossnet…
======================================
Hi Erwin K..
sorry, i dont know how i skipped your comment !!
Well, i havnt got the time to to go through this stylesheet issue, however i will try it and hope to get some work-around.
I have a problem when testing the Captcha :
You have a nil object when you didn’t expect it!
The error occured while evaluating nil.new
Extracted source (around line #23):
23: :image -%>
vendor/plugins/validates_captcha/lib/add_captcha_to_action_view.rb:34:in `prepare_captcha’
#{RAILS_ROOT}/app/views/user/signup.rhtml:23:in `_run_rhtml_user_signup’
Any idea ..I’m on Mac OS X, installed ImageMagick and rmagick
Hi Laurent,
could you show me the code which you are using to implement the captcha and so i try to figure out that whether the problem is with the code or installation of any of gems or libraries per se.
It’s OK in fact i had problems with installation of RMagick using Ruby (1.8.2) preinstalled on Mac OS X
I reinstalled Ruby 1.8.5 , RMagick now it works
But i have a problem with the captcha : the image generated includes a lot of noise and i do not see any word inside !! Any idea?
Yes Laurent,
I have the idea and i already published that.
View this post to improve the image quality and generating random string images.
With regard with a “fieldWithErrors” DIV. Here’s what worked for me:
1. Open vendor/plugins/trunk/lib/add_captcha_to_active_record.rb
2. For every “errors.add” method call, replace ‘captcha’ with ‘captcha_validation’, e.g.
errors.add(’captcha’, options[:message])
becomes:
errors.add(’captcha_validation’, options[:message])
(There are 3 such places in the version of the plugin I have).
Note: I’m also using the “error_messages_for” plugin to replace the default error message:
{ ‘captcha_validation’ => “Verification failed; please try again.” }, :defaults=> false } %>
You need to install the other plugin first if you want to use the code above in your view (remember to restart the server).
Just my $0.0001
Best,
MB
Hi,
I have done all steps correctly to setup the captcha plugin, and everytime I start the web server (mongrel, webrick, lighttpd)… It comes up with the following error.
/usr/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:1129:in `method_missing’: undefined local variable or method `validates_captcha’ for User:Class (NameError)
from /sites/pv/config/../app/models/user.rb:21
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:140:in `load’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:56:in `require_or_load’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:30:in `depend_on’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:85:in `require_dependency’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:98:in `const_missing’
from /usr/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:131:in `const_missing’
from /usr/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/observer.rb:131:in `observed_class’
… 17 levels…
from /usr/lib/ruby/gems/1.8/gems/mongrel-0.3.13.4/bin/mongrel_rails:85:in `run’
from /usr/lib/ruby/gems/1.8/gems/mongrel-0.3.13.4/lib/mongrel/command.rb:211:in `run’
from /usr/lib/ruby/gems/1.8/gems/mongrel-0.3.13.4/bin/mongrel_rails:231
from /usr/bin/mongrel_rails:18
—-
But, if I comment the validates_captcha line in my user.rb model, the server starts successfully. And, then I can uncomment and it will generate the captcha successfully.
I would like to have a permanent solution, so that I don’t have to comment/uncomment validates_captcha line everytime I restart server.
I am so stuck, that a quick answer will get me going. Waiting for your reply.
Hi Renuka !!
Well, no idea dear… Haven’t faced such problem.
Thanks Martin !!
I keep getting this error: “Can’t measure text. Are the fonts installed? Is the FreeType library installed?”
I installed RMagick using this tutorial but I’m still getting the same message.
Any ideas? Thanks.
HI! I just wanted to tell you that i really liked your site and you did a great job with it. Just for your notehttp://mp3-safe-download.org
has great music there.
From the code in the view inside the existing form…
When I use:
:image -%>
I get the error (even though RMagick is correctly installed):
uninitialized constant Magick
When I use:
I get the error:
undefined method `prepare_captcha’ for #:0×4b62da4>
What’s Up?
Hi Liana !!
Just wait till the next week, i m going to launch my own captcha
plugin which is much more simpler.
Also give me ur genuine mail so that i can inform u there also…
mail me at sur.max(at)gmail.com
Ephedra attorneys california.
Ephedra based. Ephedra yellow swarm. Ephedra fat burner. Buy online yellow jackets with ephedra. Ephedra liquid gel products. Ephedra.
Hi,
i m not able to install this plugin. i m getting
“Plugin not found [http://svn.2750flesk.com/validates_captcha]”
can anybody please help me in this.
@vinay,
read here http://expressica.com/simple_captcha