Why is my Rails mountable engine not loading helpe

2019-03-09 15:07发布

I've built a rails gem that mounts as an engine.

The engine is scoped to it's own namespace.

In the engine, there's an MyEngine::ApplicationHelper module which adds a bunch of view helper methods.

In my application layout, I refer to some of these methods.

When I first load any of the pages in development mode I get a NoMethodError, complaining that the method (defined in the gem's ApplicationHelper) doesn't exist.

Once I edit ApplicationController within my app, the problem corrects itself.

Something tells me this is down to the recent changes in Rails's auto-loading; I'm using Rails 3.2.2

I can't for the life of me work out why this isn't working properly though :/

2条回答
狗以群分
2楼-- · 2019-03-09 15:46

I think the Rails guides has the answer here.

To include that particular helper from your Engine in your app:

class ApplicationController < ActionController::Base
  helper MyEngine::ApplicationHelper
end

To include all helpers from your Engine in your app:

class ApplicationController < ActionController::Base
  helper MyEngine::Engine.helpers
end
查看更多
疯言疯语
3楼-- · 2019-03-09 15:52

To load the engine's GemName::ApplicationHelper to be used in the views of the engine itself, I added following to the engine.rb:

module GemName
  class Engine < ::Rails::Engine
    isolate_namespace GemName

    initializer 'local_helper.action_controller' do
      ActiveSupport.on_load :action_controller do
        helper GemName::ApplicationHelper
      end
    end
  end
end
查看更多
登录 后发表回答