I am looking for a helper class/method/gem that’s out there that will help me format a time helper. The output I’m looking after passing in an instance of Time.now is something like the following:
"1 minute ago"
"2 minutes ago"
"1 hour ago"
"2 hours ago"
"1 day ago"
"2 days ago"
"over a year ago"
I started writing something like this but it’s going to be long and painful and I feel like something like this has to exist. The only catch is I need it to use my own wording, so something with a formatter is required..
def time_ago_to_str(timestamp)
minutes = (((Time.now.to_i - timestamp).abs)/60).round
return nil if minutes < 0
Rails.logger.debug("minutes #{minutes}")
return "#{minutes} minute ago" if minutes == 1
return "#{minutes} minutes ago" if minutes < 60
# crap load more return statements to follow?
end
Such a helper already exists and is built-in to Rails:
http://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words
EDIT:
If you’d like to customize the wording you can create a custom
I18nlocale, for example, I created one called time_ago inconfig/locales/time_ago.yml:Now, you can use the locale with
distance_of_time_in_words:You could of course add this to
config/locales/en.ymland completely override them application wide, which would you allow you to calltime_ago_in_wordsas mentioned above!