我正在开发一个 Rails 引擎,并且遇到了 helpers 的问题。
显然这是一个已知的“问题”,但是并没有太多解决方案。我的问题是我有一个 AuthenticationHelper,我想全局访问它-但是它不起作用。
我已经阅读过可以将几行代码添加到 init.rb
中的说明,但似乎没有任何效果。
有什么好的方法可以使应用程序在引擎中可用吗?
编辑:已解决 - 只需将代码(来自链接)放入engine.rb
中即可。
我正在开发一个 Rails 引擎,并且遇到了 helpers 的问题。
显然这是一个已知的“问题”,但是并没有太多解决方案。我的问题是我有一个 AuthenticationHelper,我想全局访问它-但是它不起作用。
我已经阅读过可以将几行代码添加到 init.rb
中的说明,但似乎没有任何效果。
有什么好的方法可以使应用程序在引擎中可用吗?
编辑:已解决 - 只需将代码(来自链接)放入engine.rb
中即可。
将此代码放入 engine.rb 文件中:
config.to_prepare do
ApplicationController.helper(MyEngineHelper)
end
/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 Werthmodule 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
rails console
时,出现了"uninitialized constant ActionView::Helpers::ApplicationHelper (NameError)"的错误。有人知道原因吗? - Bater Chen为了以防万一,我在这里添加一下:
我在使用 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
我在这里找到了答案。