How can I make a `weeks_ago` helper?
How can I make a helper that will tell me h开发者_C百科ow 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...
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.
That would be a nice patch to distance_of_time_in_words:
http://github.com/rails/rails/blob/4cbb9db0a5ff65b0a626a5b043331abefd89e717/actionpack/lib/action_view/helpers/date_helper.rb#L68-103
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
精彩评论