【问题标题】:Helpers in Rails engineRails 引擎中的助手
【发布时间】:2011-12-23 02:28:35
【问题描述】:

我正在开发一个 Rails 引擎,但我的助手有问题。

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

我有read that you could add a few lines to your init.rb,但它似乎没有任何效果。

知道让应用程序在引擎中可用的最佳方法是什么吗?

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

【问题讨论】:

  • 你能提供你在engine.rb中的代码示例吗?

标签: ruby-on-rails ruby-on-rails-3 helper rails-engines


【解决方案1】:

要从引擎的视图中访问主应用程序助手 (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

【讨论】:

  • 我不得不将 Rails 4.2 中的 .helper 行更改为:ApplicationController.helper(::ApplicationHelper) ...这甚至可能适用于您的第一个解决方案。
  • 我遵循这个解决方案并且 application_helper 工作正常,但是当我运行 rails console 时,我得到“未初始化的常量 ActionView::Helpers::ApplicationHelper (NameError)”。有人知道原因吗?
【解决方案2】:

将此代码放在engine.rb中:

config.to_prepare do
  ApplicationController.helper(MyEngineHelper)
end

【讨论】:

  • 引擎内部类
  • 对于后代:这不再是必需的 - rails 现在会自动加载所有帮助程序
  • 正在运行 rails 3.2.12... 必须将此添加到 ApplicationHelper 中的访问方法中
  • /vendor/extensions/categories/lib/refinery/categories/engine.rb:11:in 'block in &lt;class:Engine&gt;': undefined method 'helper' for Refinery::ApplicationController:Module (NoMethodError)
  • 试试 ::ApplicationController.helper(MyEngineHelper)ActionController::Base.helper(MyEngineHelper) 吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
相关资源
最近更新 更多