Chris Hart
Chris Hart

Reputation: 2153

Can't access model from inside ActionController method added by a Rails engine

I am developing a Rails engine to be packaged as a gem. In my engine's main module file, I have:

module Auditor
  require 'engine' if defined?(Rails) && Rails::VERSION::MAJOR == 3
  require 'application_controller'
end

module ActionController
  module Auditor
    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods
      def is_audited
        include ActionController::Auditor::InstanceMethods
        before_filter :audit_request
      end   
    end 

    module InstanceMethods
      def audit_request
        a = AuditorLog.new
        a.save! 
      end   
    end 
  end
end

ActionController::Base.send(:include, ActionController::Auditor)

where AuditorLog is a model also provided by the engine. (My intent is to have "is_audited" added to the controllers in an application using this engine which will cause audit logging of the details of the request.)

The problem I have is that when this code gets called from an application where the engine is being used, the AuditorLog model isn't accessible. It looks like Ruby thinks it should be a class in ActionController:

NameError (uninitialized constant ActionController::Auditor::InstanceMethods::AuditorLog)

rather than a model from my engine.

Can anyone point me in the right direction? This is my first time creating an engine and attempting to package it as a gem; I've searched for examples of this and haven't had much luck. My approach to adding this capability to the ActionController class was based on what mobile_fu does, so please let me know if I'm going about this all wrong.

Upvotes: 0

Views: 628

Answers (1)

Jeremy Weathers
Jeremy Weathers

Reputation: 2554

Use ::AuditorLog to access the ActiveRecord class (unless you have it in a module or namespace, in which case you'll need to include the module name).

Upvotes: 1

Related Questions