Search code examples
ruby-on-rails-3extendactioncontroller

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


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?