2010-03-28 26 views
0

我怎樣才能成爲一名助手,告訴我在幾周前(向下舍入)的導軌?它可以基於time_ago_in_words幫手但是我希望它返回:「上週」,那麼後來才two weeks agothree weeks ago,等...如何製作`weeks_ago`幫手?

回答

4

試試這個:

def my_time_ago_in_words(from_time, include_seconds = false) 
    to_time = Time.now 
    weeks_ago = ((to_time - from_time)/1.week).abs 
    [nil, "last week", "two weeks ago", "three weeks ago"][weeks_ago] || 
     distance_of_time_in_words(from_time, to_time, include_seconds) 
end 

此功能的行爲與time_ago_in_words相同。當from_time在1-3周之前,這將打印last week,two weeks ago,three weeks ago,否則它將打印通常。

+0

我建議你的名字'weeks_ago_in_words',因爲它是更具描述性方法的實際內容。 – Matchu 2010-03-29 02:09:29

+1

這個函數實際上是'time_ago_in_words'的一個補丁,因爲它保留了函數的現有功能。正確的做法是使用'alias_method_chain'修補'time_ago_in_words'。 – 2010-03-29 03:32:58