ynk*_*nkr 25 ruby-on-rails view-helpers helpers rails-engines ruby-on-rails-3.1
我发现了一些文章解决了引擎内的助手问题,这些问题不适用于消费(父)应用程序.为了确保我们都在同一页上,让我们说我们有这个:
module MyEngine
module ImportantHelper
def some_important_helper
...do something important...
end
end
end
Run Code Online (Sandbox Code Playgroud)
如果您查看"隔离引擎的助手"(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
Run Code Online (Sandbox Code Playgroud)
因此,如果我要求任何使用我的引擎的人将其添加到他们的application_controller.rb中,那么他们将可以访问我所有重要的帮助方法:
class ApplicationController < ActionController::Base
helper MyEngine::ImportantHelper
end
Run Code Online (Sandbox Code Playgroud)
这就是我想要的并且它可以工作,但这是一种痛苦,特别是如果,就我的用例而言,引擎公开的所有内容都可以/应该在消费应用中的任何地方使用.所以我挖了一点,找到了一个解决方案,建议我做以下事情:
module MyEngine
class Engine < Rails::Engine
isolate_namespace MyEngine
config.to_prepare do
ApplicationController.helper(ImportantHelper)
end
end
end
Run Code Online (Sandbox Code Playgroud)
现在这正是我想要的:将我的所有ImportantHelper方法添加到父应用程序的应用程序助手中.但是,它不起作用.任何人都可以帮我弄清楚为什么这个更好的解决方案不起作用?
我用rails 3.1.3运行ruby 1.8.7.如果我错过了与该问题密切相关的任何重要信息,请告诉我,并提前感谢.
JDu*_*til 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
Run Code Online (Sandbox Code Playgroud)
我写过两篇关于从头开始创建引擎的博客文章,关注它们一切都应该按预期工作(无需额外配置).也许你仍然对以下内容感兴趣:
更新:在此期间有三篇文章,还有一些信息要提出来.请给我反馈.
如果要将代码保留在引擎中,而不是每个实现的应用程序,请使用:
module MyEngine
class Engine < Rails::Engine
isolate_namespace MyEngine
config.to_prepare do
MyEngine::ApplicationController.helper Rails.application.helpers
end
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9387 次 |
最近记录: |