How to incorporate Rails Engine ApplicationControl

2020-03-07 06:54发布

问题:

How do I incorporate a Rails engine ApplicationController (it's methods) into a main app? I need to access these engine controller methods, and I'd like to do it without using an 'Include' in my main app's ApplicationController.

module MyEngine
  class Engine < Rails::Engine
    initializer  "myengine.load_helpers" do
      ActiveSupport.on_load(:action_controller) do
        include MyEngine::Helpers
      end
    end
  end
end

The above was posted on A way to add before_filter from engine to application, but my understanding was that helpers are only view-usable, while I need need to access them in my controllers.

回答1:

I did this before for a rails gem called dynamic_menu

basically it looks like

require 'dynamic_menu'

module DynamicMenu
  class Engine < Rails::Engine
    initializer "dynamic_menu.menu_items" do |app|
      ActionController::Base.send :include, DynamicMenu::MenuItems
    end
  end
end

So I would assume the one you would want would be

require 'myEngine'
class Engine < Rails::Engine
  initializer "myengine.load_helpers" do |app|
    ActionController::Base.send :include, MyEngine::Helpers
  end
end

You want to add the require of the .rb file you are using found in lib, then it just involves sending the module to the ActionController::Base

See my gem on github it is pretty simple in nature and may be able to give some guidance. Comment and I can explain it more.