Created
July 21, 2011 11:25
-
-
Save gouthamvel/1096991 to your computer and use it in GitHub Desktop.
simple timespan class for operations on time span
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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