<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users547</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/547" rel="self"/>
  <title>makenai</title>
  <updated>Thu Apr 10 21:54:08 -0700 2008</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor4820</id>
    <published>2008-04-10T21:54:08-07:00</published>
    <title>[Ruby] On How to make time_ago_in_words cachable ?</title>
    <content type="html">&lt;p&gt;In the rails version the numbers are not cast to Floats before dividing, so the results are not consistent when you put this code and time_ago_in_words side by side. Using Math.floor will give the proper results.&lt;/p&gt;

&lt;pre&gt;distanceOfTimeInWords: function(to, from) {
  seconds_ago = ((to  - from) / 1000);
  minutes_ago = Math.floor(seconds_ago / 60);

  if(minutes_ago == 0) { return &amp;quot;less than a minute&amp;quot;; }
  if(minutes_ago == 1) { return &amp;quot;1 minute ago&amp;quot;; }
  if(minutes_ago &amp;lt; 45) { return minutes_ago + &amp;quot; minutes&amp;quot;; }
  if(minutes_ago &amp;lt; 90) { return &amp;quot; about 1 hour&amp;quot;; }
  hours_ago  = Math.floor(minutes_ago / 60);
  if(minutes_ago &amp;lt; 1440) { return &amp;quot;about &amp;quot; + hours_ago + &amp;quot; hours&amp;quot;; }
  if(minutes_ago &amp;lt; 2880) { return &amp;quot;1 day&amp;quot;; }
  days_ago  = Math.floor(minutes_ago / 1440);
  if(minutes_ago &amp;lt; 43200) { return days_ago + &amp;quot; days&amp;quot;; }
  if(minutes_ago &amp;lt; 86400) { return &amp;quot;about 1 month&amp;quot;; }
  months_ago  = Math.floor(minutes_ago / 43200);
  if(minutes_ago &amp;lt; 525960) { return months_ago + &amp;quot; months&amp;quot;; }
  if(minutes_ago &amp;lt; 1051920) { return &amp;quot;about 1 year&amp;quot;; }
  years_ago  = Math.floor(minutes_ago / 525960);
  return &amp;quot;over &amp;quot; + years_ago + &amp;quot; years&amp;quot;;
}&lt;/pre&gt;</content>
    <author>
      <name>makenai</name>
      <email>makenai@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/7-how-to-make-time_ago_in_words-cachable/refactors/4820" rel="alternate"/>
  </entry>
</feed>

