Home > captcha, image, rails, ror, validations > Captcha in Ruby on Rails - Customize the use of captcha in the plugin validates_captcha

Captcha in Ruby on Rails - Customize the use of captcha in the plugin validates_captcha

October 24th, 2006

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.

sur captcha, image, rails, ror, validations

  1. Chintan Shah
    November 14th, 2006 at 10:55 | #1

    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:

  2. Chintan Shah
    November 14th, 2006 at 10:56 | #2

    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:

  3. November 14th, 2006 at 10:59 | #3

    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 !!

  4. Chintan Shah
    November 14th, 2006 at 11:02 | #4

    thnx a lot for a giving a fast reply

  5. Chintan Shah
    November 14th, 2006 at 14:56 | #5

    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:

  6. November 14th, 2006 at 16:37 | #6

    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 ?

  7. Paddy
    November 14th, 2006 at 19:17 | #7

    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

  8. November 14th, 2006 at 19:37 | #8

    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 ?

  9. Paddy
    November 15th, 2006 at 03:40 | #9

    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

  10. November 15th, 2006 at 05:05 | #10

    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.

  11. Chintan Shah
    November 15th, 2006 at 05:14 | #11

    thnx a lot Sur

  12. Paddy
    November 15th, 2006 at 05:16 | #12

    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

  13. Paddy
    November 15th, 2006 at 18:03 | #13

    Thanks sur!

    I just created a dummy model and it works!

    Thank you
    -Paddy

  14. November 18th, 2006 at 10:19 | #14

    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

  15. November 18th, 2006 at 10:28 | #15

    On error the input field should be in a DIV with class : fieldWithErrors…
    where is this field generated ?

  16. rossnet
    November 21st, 2006 at 14:28 | #16

    hi & thanks for the nice article,

    i’ve probably a newbie question ,-) as I get a:

    undefined method `validates_captcha' for AppointmentController:Class

    while 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

  17. November 21st, 2006 at 14:35 | #17

    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?

  18. rossnet
    November 21st, 2006 at 16:19 | #18

    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

  19. November 21st, 2006 at 16:56 | #19

    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.

  20. Laurent
    November 25th, 2006 at 19:04 | #20

    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

  21. November 26th, 2006 at 19:08 | #21

    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.

  22. Laurent
    November 30th, 2006 at 07:27 | #22

    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?

  23. November 30th, 2006 at 07:30 | #23

    Yes Laurent,
    I have the idea and i already published that.
    View this post to improve the image quality and generating random string images.

  24. Martin Bilski
    December 6th, 2006 at 18:48 | #24

    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

  25. Renuka
    December 12th, 2006 at 12:27 | #25

    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.

  26. December 12th, 2006 at 16:35 | #26

    Hi Renuka !!
    Well, no idea dear… Haven’t faced such problem.

  27. December 17th, 2006 at 02:14 | #27

    Thanks Martin !!

  28. January 7th, 2007 at 01:26 | #28

    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.

  29. January 19th, 2007 at 10:47 | #29

    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.

  30. January 25th, 2007 at 00:17 | #30

    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?

  31. January 25th, 2007 at 03:50 | #31

    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

  32. vinay
    August 17th, 2008 at 23:26 | #32

    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.

  33. August 19th, 2008 at 07:07 | #33
  34. Lareb
    August 24th, 2008 at 23:46 | #34

    Hi,
    I m trying to setup captcha in my rails application I follow all the steps but finally when I use “” tag then it gave me an error -

    private method `cleanup’ called for #

    guide me.
    Thanks

  35. August 24th, 2008 at 23:56 | #35

    Hi Lareb,

    You can use Simple Captcha, its easier to implement and flawless plugin.

  36. Lareb
    August 25th, 2008 at 00:50 | #36

    Thanks sur.
    Now its working with simple_captcha

    :-)

  37. September 1st, 2008 at 23:33 | #37

    Thanx sur. it really simple according to others

  1. August 8th, 2007 at 08:41 | #1