I need a captcha in a form, whose associated model is a Validatable. After googling, I decided to go with Simple Captcha. The Simple captcha is extremely easy to use, see its documentation, you'll know. But it works fine with a ActiveRecord::Base, not a Validatable. There has to be some hack to make it work. I could use "Controller mode" of it. But it will be nice to put it into model, make it part of validation process. and here's my code:
First, include SimpleCaptcha into your Validatable model:
YourValidatable.module_eval do
class << self; include SimpleCaptcha::ModelHelpers; end
end
And overwrite apply_simple_captcha
def self.apply_simple_captcha(options = {})
module_eval do
require 'pstore'
include SimpleCaptcha::ConfigTasks
attr_accessor :captcha, :captcha_code,
:authenticate_with_captcha
alias_method :valid_without_captcha?, :valid?
end
@captcha_invalid_message =
(options[:message].nil? || options[:message].empty?) ?
" image did not match with text" : options[:message]
module_eval(turing_valid_method)
module_eval(turing_save_method)
end
Finally, call
apply_simple_captchaThat's it.
In the controller, instead of calling
valid? to decide if the object is valid, you call valid_with_captcha?BTW: Follow this link to see how to install RMagick on Ubuntu