2010-03-28 52 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