26

我发现有几篇文章解决了引擎中的助手无法被消费(父)应用程序访问的问题。为了确保我们都在同一个页面上,假设我们有这个:

module MyEngine
  module ImportantHelper
    def some_important_helper
      ...do something important...
    end
  end
end

如果您查看“隔离引擎的助手”(L293)中的Rails 引擎文档,它会说:

  # Sometimes you may want to isolate engine, but use helpers that are defined for it.
  # If you want to share just a few specific helpers you can add them to application's
  # helpers in ApplicationController:
  #
  # class ApplicationController < ActionController::Base
  #   helper MyEngine::SharedEngineHelper
  # end
  #
  # If you want to include all of the engine's helpers, you can use #helpers method on an engine's
  # instance:
  #
  # class ApplicationController < ActionController::Base
  #   helper MyEngine::Engine.helpers
  # end

因此,如果我要求任何使用我的引擎的人将其添加到他们的 application_controller.rb 中,那么他们将可以访问我所有重要的辅助方法:

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

这就是我想要的并且它有效,但这有点痛苦,特别是如果,就像我的用例一样,引擎公开的所有内容都可以/应该在消费应用程序的任何地方使用。因此,我进行了更多研究,并找到了一个建议我执行以下操作的解决方案:

module MyEngine
  class Engine < Rails::Engine
    isolate_namespace MyEngine

    config.to_prepare do
      ApplicationController.helper(ImportantHelper)
    end
  end
end

现在这正是我想要的:将我所有的 ImportantHelper 方法添加到父应用程序的应用程序助手中。但是,它不起作用。谁能帮我弄清楚为什么这个更好的解决方案不起作用?

我正在运行带有 rails 3.1.3 的 ruby​​ 1.8.7。如果我错过了与该问题相关的任何重要信息,请告诉我,并提前致谢。

4

5 回答 5

44

您可以创建一个初始化程序来完成此操作,如下所示:

module MyEngine
  class Engine < Rails::Engine
    initializer 'my_engine.action_controller' do |app|
      ActiveSupport.on_load :action_controller do
        helper MyEngine::ImportantHelper
      end
    end
  end
end
于 2012-03-09T21:18:35.833 回答
6

If you want to keep the code in the engine, instead of every implementing application, use this:

module MyEngine
  class Engine < Rails::Engine
    isolate_namespace MyEngine

    config.to_prepare do
      MyEngine::ApplicationController.helper Rails.application.helpers
    end

  end
end
于 2013-07-31T16:23:15.253 回答
6

我已经写了两篇关于从头开始创建引擎的博客文章,并且遵循它们,一切都应该按预期工作(不需要额外的配置)。也许您仍然对以下内容感兴趣:

更新:同时是三篇文章,还有一些信息要来。请给我反馈。

于 2012-10-01T08:41:49.123 回答
1
module YourEngine
  module Helpers
    def a_helper
    end

    ...
  end
end

ActionController::Base.send(:helper, YourEngine::Helpers)
于 2012-02-23T02:57:38.447 回答
1

在engine.rb中包含这段代码也很有帮助

config.before_initialize do
  ActiveSupport.on_load :action_controller do
    helper MyEngine::Engine.helpers
  end
end

基本上你的引擎看起来像

module MyEngine
  class Engine < Rails::Engine
    isolate_namespace MyEngine

    # Here comes the code quoted above 

  end
end
于 2014-10-21T21:08:39.457 回答