Rails 3 - extend ActionController
I am trying to implement logic captcha in my app. I have scaffolded simple TextCaptcha to store question and answer in DB.
Currently I have this in initializers/text_captcha.rb
require 'text_captcha'
ActionController::Base.send(:include, TextCaptcha)
This in "lib/text_captcha.rb":
module TextCaptcha
def self.included(base)
base.send(:include, InstanceMethods)
end
module InstanceMethods
def require_text_captcha
@captcha = "he开发者_运维问答llo!"
end
end
end
So in comments controller I have this to have access to @captcha in view
before_filter :require_text_captcha
The bad thing is I have to restart webrick every time I make changes - so I think I'm doing this in a wrong way? I could get rid of initializer and just require "text_captcha" where I need... Or is there a way to do this in "models/text_capctha.rb" which I was trying to do in the beginning but could figure out.
Since ApplicationController
in a Rails app extends from ActionController::Base
, can you do:
require 'text_captcha'
class ApplicationController < ActionController::Base
include TextCaptcha
end
in app/controllers/application_controller.rb
?
If TextCaptcha is getting blown away when Rails reloads your models the fix is to use to_prepare
instead of an initializer to load it. See the following resources for more information:
Official Docs: http://api.rubyonrails.org/classes/ActionDispatch/Callbacks.html#method-c-to_prepare Short Blog Post: http://www.cowboycoded.com/2011/01/28/reloading-rails-3-engine-initializers-in-development/
精彩评论