views:

64

answers:

3

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...

+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
I'd recommend the name `weeks_ago_in_words`, as it is more descriptive of the method's actual content.
Matchu
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
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