10 Feb 2012
Rails provides a helper method time_ago_in_words to display the distance between one time and now, like "5 minute ago", it's very useful.
<%= times_ago_in_words(comment.created_at) %>
It looks fine, but we have some room to improve.
- Your servers have to calculate the time ago for each request, it wastes the cpu capability on server side, why not move the calculation to client side.
- If we calculate the time ago on server side, it gets difficult to cache the page. e.g. after you create a comment, the time ago of the comment shows "5 seconds ago", if you cache the page, the time ago still show "5 second ago" after 3 minute (depends on your cache strategy).
<abbr class="timeago" title="<%= comment.created_at.getutc.iso8601 %>"> <%= comment.created_at.to_s %> </abbr>
Now, you save the server cpu capability and make your page easier to cache.