How to incorporate Rails Engine ApplicationController methods in a main app?

强颜欢笑 提交于 2019-12-30 07:27:08

问题


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.



来源:https://stackoverflow.com/questions/11124447/how-to-incorporate-rails-engine-applicationcontroller-methods-in-a-main-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!