Avoid time_ago_in_words in Rails
makes it really easy
to display time as
“x minutes/hours/months ago” format.
it has one big disadvantage:
it makes it harder to use fragment caching.
Let’s say we’re displaying posts within a partial:
Here the second line might show “posted 2 minutes ago” right now, but in a minute, it needs to change to “posted 3 minutes ago”, but it will keep showing the older time until the cache expires.
My preferred solution for this is to use the timeago jquery plugin. Timeago plugin requires time in ISO 8601 format, so we’ll add a helper method that renders a span containing time in the correct format.
Now we can use this in the view, in place of
Not only does this allow you to use fragment caching correctly, but it also updates the time if you keep the page open for a while.