Rails引擎中的辅助方法

8

我正在开发一个 Rails 引擎,并且遇到了 helpers 的问题。

显然这是一个已知的“问题”,但是并没有太多解决方案。我的问题是我有一个 AuthenticationHelper,我想全局访问它-但是它不起作用。

我已经阅读过可以将几行代码添加到 init.rb 中的说明,但似乎没有任何效果。

有什么好的方法可以使应用程序在引擎中可用吗?

编辑:已解决 - 只需将代码(来自链接)放入engine.rb中即可。


1
你能提供一下你在 engine.rb 中放置的代码示例吗? - westonplatter
3个回答

10

将此代码放入 engine.rb 文件中:

config.to_prepare do
  ApplicationController.helper(MyEngineHelper)
end

在类 Engine < Rails::Engine 内部? - linjunhalida
1
为了后人记录:这已经不再必要 - Rails现在自动加载所有的helpers。 - danielpcox
3
运行 Rails 3.2.12... 必须添加此内容才能访问 ApplicationHelper 中的方法。 - Patm
/vendor/extensions/categories/lib/refinery/categories/engine.rb:11:in 'block in <class:Engine>': undefined method 'helper' for Refinery::ApplicationController:Module (NoMethodError) - Chloe
尝试使用 ::ApplicationController.helper(MyEngineHelper) 或者 ActionController::Base.helper(MyEngineHelper),也许可以达到你想要的效果? - Brad Werth

3
要从引擎的视图中访问主应用程序助手(ApplicationHelper),我尝试包含以下内容:
app/helpers/your_engine/application_helper.rb
module YourEngine
  module ApplicationHelper
    include ActionView::Helpers::ApplicationHelper
  end
end

它可以工作,但是一次,当我重新启动开发服务器时,它抛出了一个异常uninitialized constant ActionView::Helpers::ApplicationHelper,但是我无法重现这个异常。

编辑

移除了这个 include 并使用了下面的这个:

lib/my_engine/engine.rb (它在引擎内部)

module MyEngine
  class Engine < ::Rails::Engine
    isolate_namespace MyEngine
    config.to_prepare do
      ApplicationController.helper(ActionView::Helpers::ApplicationHelper)
    end
  end
end

1
我不得不在Rails 4.2中更改.helper行为:ApplicationController.helper(::ApplicationHelper)……这甚至可能适用于您的第一个解决方案。 - Allen
我按照这个解决方案操作,application_helper正常工作,但是当我运行rails console时,出现了"uninitialized constant ActionView::Helpers::ApplicationHelper (NameError)"的错误。有人知道原因吗? - Bater Chen

0

为了以防万一,我在这里添加一下:

我在使用 Rails 7 时遇到了与 Administrate gem 相关的同样问题。我想要访问我的主应用程序帮助器模块。

只需在 Admin::ApplicationController 中添加 helper all_helpers_from_path 'app/helpers' 即可解决此问题。您可以在这里找到官方文档。

现在我的文件看起来像这样:

module Admin
  class ApplicationController < Administrate::ApplicationController
    before_action :authenticate_admin_user!
    helper all_helpers_from_path "app/helpers"
  end
end

我在这里找到了答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接