Skip to content

Instantly share code, notes, and snippets.

@gouthamvel
Created July 21, 2011 11:25
Show Gist options
  • Save gouthamvel/1096991 to your computer and use it in GitHub Desktop.
Save gouthamvel/1096991 to your computer and use it in GitHub Desktop.
simple timespan class for operations on time span
# usage Timespan.to_words (Time.now + 10)
# usage t_one = Time.now
# usage t_two = Time.now + 100
# usage Timespan.to_words t_one
# usage Timespan.to_words t_one..t_two
class Timespan
def self.to_words(time)
unless (time.is_a?(Time) or (time.is_a?(Range) and (time.first.is_a?(Time) and time.last.is_a?(Time))) )
raise 'Time should be a Time/(Range in Time) object #{time.class} given'
end
diff = time.is_a?(Range) ? time.first.to_i - time.last.to_i : Time.now.to_i - time.to_i
diff_to_words(diff)
end
def self.diff_to_words(diff)
diff_noun = noun(diff)
diff_count = count(diff)
"about #{diff_count} #{infect(diff_noun, diff_count)} %s" % (diff >0 ? 'ago' : 'from now')
end
private
def self.infect(word, count)
count.abs > 1 ? word + "'s" : word
end
def self.count(num)
num = num.abs
ret_val = num
[60,60,24,7,4,12].each do |n|
break if (num = num/n) == 0
ret_val = num % n
end
ret_val
end
def self.noun(diff)
limits = [["minute", 60], ["hour", 3600], ["day", 86400], ["week", 604800], ["month", 2678400], ["year", 31622400]]
ret_val = 'second'
limits.each{|val| ret_val = val[0] if val[1] < diff.abs }
ret_val
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment