繁体   English   中英

Rails 3.1:在客户端应用程序中公开引擎助手的更好方法

[英]Rails 3.1: Better way to expose an engine's helper within the client app

我发现了一些文章解决了引擎内的助手问题,这些问题不适用于消费(父)应用程序。 为了确保我们都在同一页上,让我们说我们有这个:

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。 如果我错过了与该问题密切相关的任何重要信息,请告诉我,并提前感谢。

您可以创建一个初始化程序来完成此操作:

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

我写过两篇关于从头开始创建引擎的博客文章,关注它们一切都应该按预期工作(无需额外配置)。 也许你仍然对以下内容感兴趣:

更新:在此期间有三篇文章,还有一些信息要提出来。 请给我反馈。

如果要将代码保留在引擎中,而不是每个实现的应用程序,请使用:

module MyEngine
  class Engine < Rails::Engine
    isolate_namespace MyEngine

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

  end
end

在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
module YourEngine
  module Helpers
    def a_helper
    end

    ...
  end
end

ActionController::Base.send(:helper, YourEngine::Helpers)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM