How can I make a helper that will tell me how many weeks ago (rounded down) with rails? It could be based of the time_ago_in_words
helper however I'd want it to return: "last week" then afterwards just two weeks ago
, three weeks ago
, etc...
views:
64answers:
3
+2
A:
Try this:
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
This function will behave the same as time_ago_in_words
. When the from_time
is between 1 - 3 week ago, this will print last week
, two weeks ago
, three weeks ago
otherwise it will print the usual.
KandadaBoggu
2010-03-29 00:24:41
I'd recommend the name `weeks_ago_in_words`, as it is more descriptive of the method's actual content.
Matchu
2010-03-29 02:09:29
This function is really a patch to `time_ago_in_words` as it preserves the existing functionality of the function. Correct approach is to patch the `time_ago_in_words` probably using `alias_method_chain`.
KandadaBoggu
2010-03-29 03:32:58
A:
Also, you can write custom time descriptions for the other levels (day, month, year).
http://robots.thoughtbot.com/post/392707640/the-more-you-know-custom-time-descriptions
Dan Croak
2010-03-29 02:21:14