Here I will show you how to add captcha in rails 3 application:
Download Simple captcha plugin from the git : click here
1 | rails plugin install https://github.com/galetahub/simple-captcha.git |
Generate Simple Captcha
1 2 | rails generate simple_captcharake db:migrate |
Generate scaffold of MODEL
1 | rails g scaffold Model |
Captcha code can be added two way . 1. Controller based 2. Model based
Controller Based
Include simple captcha in app/controllers/application.rb
1 2 3 | ApplicationController < ActionController::Base include SimpleCaptcha::ControllerHelpersend |
Add captcha code in form page
1 | <%=show_simple_captcha%> |
Check captcha authentication in controller
1 2 3 4 5 6 7 | def create if simple_captcha_valid? do something.... else do something.... endend |
Model Based
Add captcha in model
Add captcha in model
1 2 3 | class Model < ActiveRecord::Base apply_simple_captchaend |
In Form page
1 | <%= show_simple_captcha( :label => "human authentication",:object => "object") %> |
In controller
1 2 3 | @object.valid_with_captcha?or@object.save_with_captcha |
ADD I18n
1 2 3 4 5 6 7 | simple_captcha: message: default: "Secret Code did not match with the Image" user: "The secret Image and code were different" |
If application is in ruby 1.9.* then you need to require some changes in plugins otherwise you will not able to see captcha image and get following error
1 | "TypeError (can't convert nil into Integer):" |
Changes in /simple-captcha/lib/simple_captcha/image.rb
At line number 47: Comment class Tempfile
At line number 47: Comment class Tempfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #class Tempfile < ::Tempfile# Replaces Tempfile's +make_tmpname+ with one that honors file extensions.# def make_tmpname(basename, n = 0)# puts "**********************Base name: #{basename}"# extension = File.extname(basename)# puts "**********************Extension: #{extension}"# puts "********************** SPRINFG #{File.basename(basename, extension)},#{$$},#{n.to_i}#{extension}"## # sprintf("%s,%d,%d%s", File.basename(basename, extension), $$, n, extension)# sprintf("%s%d-%d%s", File.basename(basename, extension), $$, n, extension)# #"%s,%d,%d%s", File.basename(basename, extension), $$, n, extension# puts "**********************Base name: #{basename}"# end# end |
At line number 68: replace with below code
1 | dst = Tempfile.new(['simple_captcha','.jpg']) |
No comments:
Post a Comment