Plugin: Simple Captcha - captcha for rubyonrails
February 6th, 2007
If you are using an older revision of SimpleCaptcha then it is strongly recommended that update it to the Simple Captcha version 1.0, coz there were certain bugs in the previous release viz. update_attribute, which has been fixed in this release.
Bugs Fixed and Features
- update_attribute and update_attributes are now working
- Automated removal of old simple captcha images
- can be implemented as controller or model based captcha
- implementation requires a single line of code in view and a single line of code in controller/model
- customized CSS can be implemented
- Distortion of images can be selected from three different levels as low, medium or high…
so that now we can handle the complexities of images - Eight different styles of images are available to be selected as your captcha image
check out more details here
captcha, plugin, rails, ror, rubyonrails

It appears that part of article is missing. After “In the view file within the form tags write this code” it is blank. What is to be added to the form? Also it appears that all of the captchas have the exactly the same wave distortion applied. Is it possible to perturb the variables so that the captchas look more dissimilar?
Heyi Andrej !!
After ur comment i just viewd the page in IE…
Its truely blank there…
I think its some CSS problem, that is not compatible with IE i suppose… i will figure it out soon.
Please view it in FireFox probably..it is fine there.
Anyways in the form tags we have to write this…
< %= show_simple_captcha %>
well, i have some points in mind which i will incorporate in the coming revision soon
as…
1.) the different wave amplitude and frequencies
2.) the customized backgrounds
3.) customized image size
It will be upgraded very soon.
I copied simple_captcha folder to vendor/plugins. And then I get Application error Application error Rails application failed to start properly.
/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require’: no such file to load — PStore (MissingSourceFile)
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require’
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:147:in `require’
from ./script/../config/../config/../vendor/plugins/simple_captcha/lib/simple_captcha_image.rb:1
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require’
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require’
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:147:in `require’
from script/../config/../config/../vendor/plugins/simple_captcha/init.rb:3:in `load_plugin’
from /usr/local/lib/ruby/gems/1.8/gems/rails-1.1.6/lib/initializer.rb:348:in `load_plugin’
… 12 levels…
from /usr/local/lib/ruby/1.8/irb/init.rb:250:in `load_modules’
from /usr/local/lib/ruby/1.8/irb/init.rb:21:in `setup’
from /usr/local/lib/ruby/1.8/irb.rb:54:in `start’
from /usr/local/bin/irb:13
I Hvae fixed the PStore bug and updated the repository.
It’s works now! Great plugin! Thank you.
really worked well, thanks
Hi I might be going about this all wrong, I’ve installed the plugin and I’ve gone to my Model code and added the line
apply_simple_captcha
within my model but I keep getting an error:
undefined method `show_simple_captcha’ for #:0×67aff20>
in my comments view page..please tell me where I’m going wrong…?
Hi John,
so you are applying the model based captcha,
please show the code of the view for the method show_simple_captch…
works great… looking forward to the update. How would this scale out across multiple webservers (ie. with a load balancer involved and a user not hitting the same webserver across requests)?
THANK YOU SO MUCH!
THIS IS THE ONLY CAPTCHA THAT I GOT WORKING IN LESS THAN 2 MINUTES.
GREAT GREAT WORK
plz mind the capslock. i mean it because i’ve been struggling with all other captcha solutions for the past month.
this is an awesome work!
Thanks Yari123 !!
Hi hamburgler !!
I have written the plugin in the manner that it will be concurrent with session.
If sessions are properly maintained in the clusters(that can be easily done by use db-session-store) then the Simple Captcha should also work fine.
I have tried it on multiple mongrel clusters and it is working absolutely fine.
Thanks.
I am getting an odd error when trying the captcha on a linux box:
ActionView::TemplateError (unable to read font `(null)’) on line #49 of app/views/xxxxxxx/xxxxx.rhtml:
On this line, there is the call to the captcha:
It works normally on my local dev machine, though…
Hi Herval !!
Make sure that you have installed the RMagick with all the dependencies properly on the linux machine. That is the only possible problem.
Hi Sur,
This plug-in is really great and easy to use.
I wish to change the message displayed after validation failure of captcha.
Currently it says:
“Captcha did not match”
I wish to change it to something that non tech users can easily understand.
Thanks in advance
-Aditya Raj
Hi Aditya !!
You can provide the customized message as
apply_simple_captcha :message => “my custom message”
for more details read the README.
Thanks.
hello sir
I have installed your simple captch but after installation WebRick server is not geting started please suggest me the reason
regards
Uday
Probably u have not installed RMagick and ImageMagick properly.
BTW what error messages you are getting while running the server ?
simple and great plugin! simply outstanding!
thanks.
hello sur just a quick question. Is there a way to make the image bigger, and sometimes the image is darn hard to make out the letters!
Hi Yari123 !!
Yeah that will be included in the next revision which will be completed very soon.
I will publish the post here for the new revision information with tha added features.
Thanks.
Nice work on captcha plugin, Sur. Keep up the good work.
Thanks Chetan !!
Hi Uday,
Seems like you have not installed RMagick gem.
I’m not having the same success. Installation was straight forward. I’m getting an internal 500 error. Following my log file, when it reaches in my page, it dies with the error. I’m not associating it with a model. I have RMagick installed. I call require ‘RMagick’ at the top of the controller. RMagick is working fine in other places I use it. Any ideas?
Comment: (Required)
Hi Aaron,
u restarted the server also after installing the plugin ?
Sur,
I restarted a couple of times but still getting the same error.
Sur,
I don’t know if this would help but I began poking around and discovered that none of the capthca images were created. Could that be the cause? If so, how can I get them because I’ve reinstalled the plug-in and the images are not there.
Aaron,
No, the images will be produced on the fly… i.e. while running the application. Whenever the page will be refreshed, a new image will be generated using RMagick. I have tested the plugin on win32, linux and Mac also… it is running fine on these platforms.
Can you tell me whats there in the log file when there is error. And what is the version of Ruby you are using ?
hey sur, just installed the gem and applied to my code. i’m getting an empty image. even the saved jpg file in public/images/simple_captcha is just a blank white jpg file. any ideas?
Hi Jesse,
i have added the default Courier font for images and updated the plugin at the repository. I hope it will work for you.
Hi Sur,
I’m encountering the following err mssg “unable to read font `n022003l.pfb’”
I’m Win XP with the rmagick gem as shown below
rmagick (1.14.1)
RMagick is an interface between the Ruby programming language and
the ImageMagick and GraphicsMagick image processing libraries.
here’s the RAILS trace:
#{RAILS_ROOT}/vendor/plugins/simple_captcha/lib/simple_captcha_image.rb:36:in `annotate’
#{RAILS_ROOT}/vendor/plugins/simple_captcha/lib/simple_captcha_image.rb:36:in `add_text’
#{RAILS_ROOT}/vendor/plugins/simple_captcha/lib/simple_captcha_image.rb:77:in `add_text_and_effects’
#{RAILS_ROOT}/vendor/plugins/simple_captcha/lib/simple_captcha_image.rb:90:in `create_image’
#{RAILS_ROOT}/vendor/plugins/simple_captcha/lib/simple_captcha_action_view.rb:72:in `show_simple_captcha’
#{RAILS_ROOT}/app/views/messages/new.rhtml:7:in `_run_rhtml_47app47views47messages47new46rhtml’
Any idea where I’m going wrong?
Thanks.
Sur,
I’m running Rails 1.1.6 and Ruby 1.8.4. I can’t give you anything as far as a log report because the page just does not display. It appears to be in an infinite loop. What I can tell you from the log is that it is executing code properly until it gets to the line to display the captcha. At that point it hangs. There are no error messages.
Sur,
I deleted simple captcha and did a SVN checkout and re-tried the plugin and now it works ?? - must have been a newbie faux pas on my part - sorry to have bothered you.
Dennis
Sur,
I’m getting warmer. Did a reinstall and got the following error.
unable to read font `Courier’
That’s line 37 in simple_captcha_image.rb. If it’s looking locally for Courier, it’s installed on my machine.
Sur,
simple_chaptcha works fine in model mode with this exception - I can’t get any other model field validations to work only simple_chaptcha. Is there a way to combine simple_chaptcha with other model level validations?
Here’s the controller call:
if @message.save_with_captcha
redirect_to :controller => ‘messages’, :action => ‘confirmation’
else
render :action => ‘new’
end
Here’s the model:
apply_simple_captcha :message => “Image text does not match - please re-enter.”
validates_presence_of :name => “Please enter name.”, :on => :create
validates_presence_of :client_email => “Please enter email address.”, :on => :create
Even though the validates_ are :on :create and simple_chaptcha is save the validates_ don’t kick in
I’m new at this so perhaps there is some basic model validation concept I’m overlooking.
Hi Dennis,
Are you sure that the variable @message is not trying to save an existing record ?
As you have specified in model as
validates_presence_of :name => “Please enter name.”, :on => :create
validates_presence_of :client_email => “Please enter email address.”, :on => :create
Here you are validating specifically on create action which means only for the new records and it will not be validated if @message.new_record == false.
So, just make sure that @message shows a new record to be added or other thing you can do is just remove the directives :on => :create from the validations so that it will be called even on the existing record while saving.
so your model should then look like
apply_simple_captcha :message => “Image text does not match - please re-enter.”
validates_presence_of :name => “Please enter name.”
validates_presence_of :client_email => “Please enter email address.”
I hope it will work.
Thanks
Hi Sur,
Thanks for the quick reply and suggestions.
I added puts @message.new_record? to my controller to check new_record state and it comes back as true so it looks like that is not an issue.
Just to be safe, I removed the validation option :on => :create and then I re-did my test in which I left the form’s name field blank and as well input an incorrect image text entry.
Simple_Chaptcha did it’s validation as expected when I tried to submit the form. Next, I input the correct text for chaptcha but still left the name field blank - when I clicked submit the form record was saved rather than the RAILS validates_presence_of helper objecting to the blank name field.
Hope this isn’t a double post - thought I had posted this msg earlier - but I received one of XP’s update/reboot notices and likely cleared the earlier post by accident.
What seems to be happening is that simple_chaptcha is doing its thing and then somehow overrides the pending RAILS validation helpers and saves the record immediately upon its completion
Here’s the code:
Controller
puts @message.new_record?
if @message.save_with_captcha
redirect_to :controller => ‘messages’, :action => ‘confirmation’
else
render :action => ‘new’
end
Model
validates_presence_of :name => “Please enter name.”
apply_simple_captcha :message => “Image text does not match - please re-enter.”
Hi Denis,
I have tried the same way u mention the problem, but all is running fine at my end.
Just for a try can you do it the way like… just remove the captcha implementation(just from your model) and test the validations by saving the object(just on console itself) by the method @message.save so as to see whether these validations actually working without captcha !
Hi Sur,
I did what you suggest prior to addind any posts here - that is I pulled out all references to simple_captcha - and the RAILS model helper validations all worked OK.
I now have all validations working including simple_captcha. To do so, I set up a method to manually do the form field validations and after calling it I then call simple_captcha as you outline in your instructions - so the method checks all non-captcha fields first and if all validate then I go on to run the simple_captcha validation.
One thing I wondered about - I’m running the latest version of RAILS 1.22 and the Ruby version is 1.85 - could this be a factor if there is a version difference under which the plug-in was developed?
At any rate, I now have it working - thanks for your help - but especially thanks for developing this plug-in!!!
Hi Denis,
Thanks for the info and all efforts you did to make it running. I will look at these issues. Probably the version of the ruby/rails might be the case. I will test and update it in accordance with the latest versions of rails(1.2.2) and ruby(1.8.6) and will submit the info here.
Thanks.
With Jeremy Kemper’s addition of cookie-based session handling (edge), you can no longer rely on session_id for a unique hash seed. A hack is:
def create_code #:nodoc
captcha_hash_string = “simple captcha by sur http://expressica.com”
session[:cap_id] = rand(Time.now.to_i) unless session[:cap_id]
Digest::SHA1.hexdigest(captcha_hash_string +
session[:cap_id] +
captcha_hash_string)
end
A better way to do it is to smell out the kind of session handling and use pstore unless cookie-based sessions are being used, else store that captcha key in the session.
Thoughts?
Hello,
Very nice plugin, thanks! I have a question tho. Our users can ‘refresh’ our captcha link to get a new image via an ajax call. Our form looks like so:
” class=”form”>
true %>
@account, :submit => false %>
false %>
‘captcha’ %>
In our account controller, I just have the following method:
def captcha
render :partial => ‘captcha’
end
When I do an entire reload of the page, I get an image and I can then click my Ajax button and a new image appears. However, every click after that doesn’t result in a new image.
Is there any way to get this working? Thx again!
Sorry, forgot to escape the form (argh). Here’s the relevant portion of the form w/the ajax call:
‘captcha’ %>
(obv, u’ll have to fix the quotes for the ajax link).
The partial is:
’simply_green’) %>
Thx!
3rd times a charm.
Sorry. (removed the gt/lt signs)
div style=margin:10px
div id=captcha
%=render :partial => captcha %
/div
input type=button value=Refresh onclick=new Ajax.Updater(captcha,/account/captcha,{ asynchronous:true, evalScripts:true});
/div
The partial is:
%= show_simple_captcha( :image_style => ’simply_green’) %
Thx!
Hi Steve,
Sounds great that u have hacked the plugin and suggested the work around for the probable problem. I will try your hack in rails 1.2.2 asap.
Thanks a lot.
Hi Jason,
Definitely its a good feature to include the ajax based refreshing of image. I will try to include this feature for the version 1.0 (soon coming) of Simple Captcha.
I will be posting the list of features that will be coming
soon. One of that is providing level of wave and distortion of image to be simple, moderate or complex.
Thanks.
Correction to my earlier hack:
def create_code #:nodoc
captcha_hash_string = “simple captcha by sur http://expressica.com”
session[:cap_id] = rand(Time.now.to_i).to_s unless session[:cap_id]
Digest::SHA1.hexdigest(captcha_hash_string +
session[:cap_id] +
captcha_hash_string)
end
Hello,
Great plugin. I am getting a strange error. I have implemented the plugin using the model version.
In view:
“person”, :label => “Please type the text from the image.” %>
In model:
apply_simple_captcha :message => “Type in the correct text from the image!”
In controller:
if @person.save_with_captcha
# - here is where I get an error
@person.update_attribute(:name, “Mr.”)
redirect_to :action => “login”
end
Everything works fine, except when it gets to the line after @person.save_with_captcha. The error that I am getting is:
wrong number of arguments (1 for 0)
for the update_attribute method. This method works when I use the @person.save method.
Please let me know what is causing this and how to fix it. Thanks,
I just hacked the plugin again. At this point, I’ve added code to store a list of active captcha images in the session and then delete them at the validation step. That keeps the filesystem clear of nuisance files. Have you thought through the issue of tracking and deleting old captcha images?
Here’s my hack:
# simple_captcha_image.rb
def create_image(image_style=”simply_blue”) #:nodoc
image_style = IMAGE_STYLES[rand(IMAGE_STYLES.length)] if image_style==”random”
string, name = image_details
options = {
:image_style => image_style,
:string => string
}
image = add_text_and_effects(options)
image.implode(0.2).write(CAPTCHA_IMAGE_PATH + name)
session[:captchas] = [] unless session[:captchas]
session[:captchas]
Hmmmm. not all of the code wound up being posted. I’d be happy to send the rest along if you want it.
First of all HUGE thanks for the plugin, it’s the first one I could set up in minutes !
Did anyone notice that it’s almost impossible to guess the word written on the image? :PPP
I can’t wait for the version where I can adjust the amount of distortion.
But for now I just tweak the plugin for my needs
Anyway, thanx again. You saved me a lot of struggle.
Hi Everyone,
Just wait for one more day.
The stable version SimpleCaptcha 1.0 will be released tomorrow.
oh boy oh boy can’t wait for new release!
Hi!
I am newbie in ruby on rails developments and it seems I miss something in plugin usage. All the needed installations for captcha passed well, but show_simple_captcha, apply_simple_captcha etc. are not recognized. Should I use “require” anywhere or may it be plugins configuration problem?
Thanks
Newbie: have you tried restarting the server?
Thanks, Giotto. It is working now!
Thanks Giotto, Newbie!!
Hi Everyone,
Sorry to say guys, it will take some more to release the Simple Captcha 1.0 stable release. I am really very busy with clients projects so not getting time to focus on it. But now its a promise, i will release it on 22nd March 2007.
Thanks.
It’s guys like you that make bring reality to the claim that rails is an accelerated development environment.
THANKS. I had 10 minutes this afternoon and thought I’d start looking at captcha options.. and in that 10 minutes I go the whole job done! Like Holy Crap!
Kodus for the great code, and thanks for sharing it. It is guys like you that make Rails the phenominal framework that it is.
FYI. typos in previous entry reflect alcohol consumption levels - not IQ.
Thanks Keith!!
To fix the “update_attribute” error you’ll need to replace the SimpleCaptcha::ModelHelper#turing_save_method with:
def turing_save_method #:nodoc
ret =
Attempting to fix my previous comment on the “update_attribute” error.
def turing_save_method #:nodoc
ret =
errr. just use this link http://pastie.caboo.se/49104
Hi Blake,
Thanks … but i have already fixed all the bugs…. and added some new fearures too, which were supposed to be there in SimpleCaptcha 1.0…
I am modfying the documentation accordingly…
And will publish 1.0 within a few hours
Thanks
Hi Everyone,
after long delay Simple Captcha 1.0 released.
Bugs fixed and features added, update_attribute and update_attributes are now working properly
check out more featureshere
yay 1.0 !!!!!!!
keep up the awesome work man.
Thanks yari123!!
I get unable to read font `(null)’
running on os x classic, using following instructions: http://rmagick.rubyforge.org/install-osx.html
Did we ever find a solution to this?
Hi Jon,
have u tried it with the new version of simple captcha 1.0?
I got the same error as Dennis, I also delete the plugin and check out again. but I still got the error.
unable to read font `n022003l.pfb’
I use ruby ruby 1.8.5, rails 1.2.3 on Vista.
Any ideas?
I change self.font_family to other fonts, it works now.
self.font_family = ‘Gisha’
self.font_family = ‘Courier New’ also works. I check the windows/fonts directory, there’s no font named ‘courier’ (I cannot find this font name in Word).
If someone got this error(unable to read font `n022003l.pfb’), Just change the self.font_family , I think it works.
Hi Devon,
can you try one thing….
Just remove/comment the line self.font_family at all from the code, i wanna see whether it will take the default font in Vista too or not.
Thanks.
Great little plugin! I was so pleased to find something like this and even further pleased at the ease of use. I got this up and running amazingly quickly. Didn’t have rmagick installed (or any of its dependencies) and that took only a few minutes to get going by using the binary download available for win-32 platform. I did have to change the font as referenced in preceding posts.
I do have one question and am not sure if it is because I’m doing something incorrectly or if it is just a limitation of the plugin but…
I have a form. If I fill it out, leave some of the fields blank that have validates_presence_of on them then the form will repost with the error message and fields that were already populated with the data still in them. However, if I fill some fields out, DO NOT put a value for the captcha and do the same thing then the form is redisplayed and all the fields are cleared. I really just want my user to try the captcha again w/o having to retype everything else. Any suggestions?
Thanks,
Michael
Hi Michael,
The auto-filling on form has nothing to do with the plugin simple_captcha per se.
The reason for this is might be that in controller you are not using model’s instance variables with “@” viz. @user so that it will be available in the view, or if you are redirecting on the form page… so try to use model’s classes’ instance variables with “@” and do render :action instead of redirect. I hope it should work
If you want to comment further regarding simple_captcha… do on this post only.
Thanks
Hi Everybody,
If there is anything you want to comment for the plugin simple_captcha, do comment it here
Thanks