How can I extend ApplicationController in a gem?

后端 未结 4 972
小鲜肉
小鲜肉 2020-12-15 20:32

I thought I\'d come up with a slick way to extend ApplicationController in a Rails 3.x gem.

In my gem\'s lib/my_namespace/my_controller.rb, I had:

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 21:08

    I was able to reference ApplicationController with an initializer callback.

    gem code that subclasses/references ApplicationController:

    class GemApplicationController < ApplicationController
      before_filter :method_to_call
    
      def method_to_call
        #your code here
      end
    end
    

    gem code callback to create subclassed controller:

    module GemName
      def self.load_gem_application_controller
        require "path/to/gem_application_controller"
      end
    end
    

    rails_app/config/initializers/gem_name.rb

    GemName.load_gem_application_controller
    

    Then have controllers that use this functionality subclass GemApplicationController

    class SpecialCaseController < GemApplicationController
      # this will inherit from the gem's controller, 
      # which inherits from the rails_app ApplicationController
    end
    

提交回复
热议问题