Question

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 = "hello!"
      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.

Was it helpful?

Solution

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?

OTHER TIPS

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top