Avoid time_ago_in_words in Rails
ActiveSupport’s time_ago_in_words
makes it really easy
to display time as
“x minutes/hours/months ago” format.
However,
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.
Let’s add a line of Javascript to convert all spans having the class timeago to the time ago in words format:
Now we can use this in the view, in place of
time_ago_in_words
:
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.