安装:
ruby script/plugin install git://github.com/kares/simple_captcha.git
安装之后,跟随下面的步骤配置插件:
#### STEP 1
rails generate simple_captcha
#### STEP 2
rake db:migrate
#### STEP 3
将下面的代码添加到 config/routes.rb :
Keditor::Application.routes.draw do match '/simple_captcha/:action', :controller => 'simple_captcha', :as => :simple_captcha end
#### STEP 4
配置simple_captcha e.g. in `app/config/initializers/simple_captcha.rb`
前提条件是系统安装了rmagick和相关的gem 安装rmagick
SimpleCaptcha.backend = :RMagick SimpleCaptcha.image_options = { :image_color => 'white', :image_size => '110x30', :text_color => 'black', :text_font => 'arial', :text_size => 22 } # these are the defaults
添加代码到app/controllers/application.rb
ApplicationController < ActionController::Base include SimpleCaptcha::ControllerValidation end
添加代码到model,以user为例子,注册时要求验证码
class User < ActiveRecord::Base include SimpleCaptcha::ModelValidation validates_captcha :on => :create, :message => 'invalid captcha' end
singup.html.erb注册页面加入show_simple_captcha:
<%=form_for @user,:as=>:user, :url=>users_path, :method=>"put",:html=>{:name=>"regform",:id=>"regform"} do%> <li style="display:block;" class="captchadiv"> <div class="reg_formlabel">验 证 码:</div> <div class="reg_element "> <span class="inp_box"> <div class="field" id="div_simple_captcha"> <%= show_simple_captcha :object=>"user",:label=>"请输入图片中的文字",:distortion=>:high%></div> </span> <%if @user.errors.on(:captcha)%> <div style="display:block" class="reg_tips form-valid-tip-err"> <div style="display:block;" class="error l"> <span class="form-valid-err-content"><%[email protected](:captcha)%></span> </div> </div> <%end%> </div> </li> <%end%>
默认插件不支持切换验证码,需手动添加
config/routes.rb :
resources :users do collection do get 'update_captcha' end end
users controller:
def update_captcha respond_to do |format| format.js end end
users view:update_captcha.rjs
page.replace_html "div_simple_captcha",show_simple_captcha(:object=>"user",:label=>"请输入图片中的文字",:distortion=>:high)
修改插件view的代码,加入一个链接:#{Rails.root.to_s}/vendor/plugins/simple_captcha/app/views/simple_captcha/_simple_captcha,前提要载入jquery
<div id='simple_captcha'> <div class='simple_captcha_image'> <%= @simple_captcha_options[:image] %> </div> <div class='simple_captcha_field'> <%= @simple_captcha_options[:field] %> </div> <div class='simple_captcha_label'> <%= @simple_captcha_options[:label] %> <a onclick="jQuery.ajax({data:'', dataType:'script', type:'post', url:'/users/update_captcha'}); return false;" href="#">换一张</a> </div> </div>