2009-06-03 30 views
3

我有一些代碼可能只需要在控制器和模型的很多地方調用,我在哪裏放置這些代碼?那麼如何調用這些方法呢?將這些代碼放在Rails Web應用程序中的位置?

感謝

def self.number_of_months(start_date,to_date) 
    # Get how many months you want to view from the start months 
    (to_date.month - start_date.month) + (to_date.year - start_date.year) * 12 + 1 
end 

回答

2

如果總是用一個模型中我把它放在模型。你的方法名前self.意味着它是一個類的方法,所以如果你這樣定義方法:

class Milestone < ActiveRecord::Base 
    def self.number_of_months(start_date,to_date) 
     # Get how many months you want to view from the start months 
     (to_date.month - start_date.month) + (to_date.year - start_date.year) * 12 + 1 
    end 
end 

你會做這樣使用它:

Milestone.number_of_months(date1,date2) 

或者你可能想把它放在config/initializers目錄中。例如,在包含目錄下創建一個名爲date.rb文件:

class Date 
    def self.number_of_months(start_date,to_date) 
     # Get how many months you want to view from the start months 
     (to_date.month - start_date.month) + (to_date.year - start_date.year) * 12 + 1 
    end 
end 

這將作爲一類方法Date類。

我注意到你提到的方法需要在控制器和模型中使用的第一個答案。助手用於觀點,這可能不會對你有所幫助。

這應該是一個輔助方法。每個控制器都有一個輔助模塊,但也有一個應用範圍的模塊。該方法很好放在那裏,只要確保它不是一個類方法(刪除self.)。如果您不想將該方法添加到應用程序幫助程序中,則可以在控制器中使用helper聲明以及它所屬的幫助程序模塊,即如果方法在date_range_helper.rb中,則使用helper :date_range

2

我把它放在Date類

class Date 
    def months_between(other) 
    (month - other.month).abs + 12 * (year - other.year).abs + 1 
    end 
end 
相關問題