2011-09-18 71 views

回答

9

你可以在你的lib文件夾中放置助手並將它們包含在其中。 像這樣: LIB/some_helper.rb

module SomeHelper 
    def somedef 
    #your code there 
    end 
end 
+0

應該是'module'(小寫)? –

+0

當然。固定! (15個符號) – railscard

6

如果您需要幫助的一類方法,你就需要extend它,而不是include它。

module TalkHelper 
    def woo; 'hoo' end 
end 

class MyClass 
    extend TalkHelper 

    def self.boo; woo end 
end 

MyClass.boo #=> 'hoo' 

只要小心與視圖背景之外助手,幫工可能取決於controller,或者從一個請求,該不會是你的模型可用的情況下別的東西。

41

在你的模型,你可以做類似如下:

ApplicationController.helpers.your_helper_method 

OR

YourController.helpers.your_helper_method 

最好的解決辦法是重構代碼,這樣你就不需要根據模型調用視圖幫助程序代碼。這不是RoR的方式。正如其他人指出的那樣,您可以將幫助程序代碼提取到lib文件夾。

更多信息請參閱本:

http://railscasts.com/episodes/132-helpers-outside-views

+0

我最終遵循了你的建議並對我的代碼進行了重構,這樣我就不必在模型中使用helper方法。 – LanguagesNamedAfterCofee