25

我發現一些文章解決了消費(父)應用程序無法訪問的引擎中的幫助程序問題。爲了確保大家都在同一頁上,我們說,我們有這樣的:Rails 3.1:在客戶端應用程序中公開引擎的幫助程序的更好方法

module MyEngine 
    module ImportantHelper 
    def some_important_helper 
     ...do something important... 
    end 
    end 
end 

如果你看一下在「隔離發動機的助手」的rails engine文檔(L293),它說:

# 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。如果我錯過了與該問題密切相關的任何重要信息,請告知我,並提前致謝。

回答

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 
+0

你實際上可以簡化更多:helper MyEngine :: ImportantHelper with發送。我更新了我的帖子。 – JDutil 2012-04-06 16:46:16

+0

這個改變了嗎?看來,*所有*我的助手都會自動加載,而不需要上面的代碼!這是我的引擎:https:// github。com/sientia-jmu/iq_menu – 2012-09-20 07:43:07

+0

看起來好像所有助手都自動包含在每個控制器中,至少在擁有'--full'引擎時。 – 2012-09-27 13:33:03

1
module YourEngine 
    module Helpers 
    def a_helper 
    end 

    ... 
    end 
end 

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

如果你想保持在發動機的代碼,而不是每一個實現應用,使用:

module MyEngine 
    class Engine < Rails::Engine 
    isolate_namespace MyEngine 

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

    end 
end 
1

包含在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