2012-06-15 42 views
6

我是Rails的新手,我嘗試設置要在視圖中使用的模塊文件。所以我相信正確的行爲是將模塊定義爲控制器內的幫助器,並且應該可以工作。但是,我不是這種情況。這是結構。Rails - 將模塊包含到控制器中,在視圖中使用

lib 
    functions 
    -- form_manager.rb 

form_manager.rb:

Module Functions 
    Module FormManager 
    def error_message() ... 
    end 
    end 
end 

users_controller.rb

class UsersController < ApplicationController 

    helper FormManager 

    def new ... 

好,結構類似於上述,當我打電話ERROR_MESSAGE從new.html.erb它給我的錯誤: uninitialized constant UsersController::FormManager

所以,首先,我知道在軌道3 lib不會自動加載。假設它不是強制性的自動加載lib文件夾,我該如何做這項工作,我錯過了什麼?

順便說一句,請不要說這個問題是重複的。我告訴你我一直在尋找這個廢話近2天。

回答

14

你的模塊沒有自動加載的(至少在3.2.6)。你必須明確加載它。你可以用下面的代碼行

# in application.rb 
config.autoload_paths += %W(#{config.root}/lib) 

您可以Rails.application.config.autoload_paths檢查你的自動加載路徑實現這一目標。也許它的確是爲你定義的?

現在你已經確定你的模塊被加載時,你可以通過調用

> Functions::FormHelper 

現在你不能使用該模塊作爲默認視圖助手簽入rails console。使用#included來定義當你的模塊被包含時的助手。你通過這種方式實現了「懶惰評估」。我認爲你的代碼的問題是在模塊被包含之前調用helper方法。 (應該有人糾正我,如果我錯了)

下面的代碼:

Module Functions 
    Module FormManager 
    def error_message() ... 
    end 

    def self.included m 
     return unless m < ActionController::Base 
     m.helper_method :error_message 
    end 

    end 
end 

你也應該從你的控制器中刪除helper線。

編輯:

你可以實現這個沒有自動加載。只需使用require "functions/form_manager"即可。您爲每種方法定義一個helper_method。如果你想作爲助手使用

def self.included m 
    return unless m < ActionController::Base 
    m.helper_method self.instance_methods 
end 

EDIT2使用所有的模塊方法:

看來,你不需要使用self.included。這實現了相同的功能:

class ApplicationController < ActionController::Base 

    include Functions::FormManager 
    helper_method Functions::FormManager.instance_methods 

end 
+1

這工作,非常感謝! :)但是,如果我刪除幫手它不起作用,所以最好保持原樣:)順便說一下,除了自動加載外,沒有其他方法嗎?因爲我相信,當你自動加載時,即使你沒有使用模塊,它仍然會被加載。第二個問題:我是否應該像在包含的方法中一樣列出模塊中的每個方法? (我的意思是,像m.helper_method:create_form,m.helper_method:destroy_form等...) –

+0

嗯,不工作沒有'helper'?奇怪的。用答案更新了帖子。你應該早些時候問過這個問題,對不起,你已經浪費了2天時間( – shime

+0

),如果沒有自動加載功能,它也不能工作,我想我必須堅持自動加載,再次感謝! –

0

您似乎在命名空間FormManagerFunctions內,這意味着你會說它是由helper Functions::FormManager

試一下

相關問題