18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
# File 'lib/theusual/time.rb', line 18
def humanize(to_time = nil, options = {})
from_time = self.utc
to_time ||= Time.now.utc
from_time, to_time = to_time, from_time if from_time > to_time
distance_in_minutes = ((to_time.to_i - from_time.to_i) / 60.0).to_i
distance_in_seconds = (to_time.to_i - from_time.to_i).to_i
res = case distance_in_minutes
when 0
if options[:seconds]
case distance_in_seconds
when 1 then [ :a_second ]
when 2..4 then [ :less_than_x_seconds, 5 ]
when 5..9 then [ :less_than_x_seconds, 10 ]
when 10..29 then [ :less_than_x_seconds, 30 ]
when 30..39 then [ :half_a_minute ]
when 40..59 then [ :less_than_a_minute ]
else [ :a_minute ]
end
else
if distance_in_seconds == 0
[ :just_now ]
else
[ :less_than_a_minute ]
end
end
when 1 then [ :a_minute ]
when 2...45 then [ :x_minutes, distance_in_minutes ]
when 45...59 then [ :about_an_hour ]
when 60 then [ :an_hour ]
when 61...90 then [ :about_an_hour ]
when 90...1440 then [ :about_x_hours, (distance_in_minutes.to_f / 60.0).round ]
when 1440...2160 then [ :a_day ]
when 2160...43200 then [ :x_days, (distance_in_minutes.to_f / 1440.0).round ]
when 43200...86400 then [ :about_x_months, (distance_in_minutes.to_f / 43200.0).round ]
when 86400...525600 then [ :x_months, (distance_in_minutes.to_f / 43200.0).round ]
else
fyear = from_time.year
fyear += 1 if from_time.month >= 3
tyear = to_time.year
tyear -= 1 if to_time.month < 3
leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count{|x| Date.leap?(x)}
minute_offset_for_leap_year = leap_years * 1440
minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
remainder = (minutes_with_offset % MINUTES_IN_YEAR)
distance_in_years = (minutes_with_offset.div MINUTES_IN_YEAR)
if remainder < MINUTES_IN_QUARTER_YEAR
[ :about_x_years, distance_in_years ]
elsif remainder < MINUTES_IN_THREE_QUARTERS_YEAR
[ :over_x_years, distance_in_years ]
else
[ :almost_x_years, distance_in_years + 1 ]
end
end
if res.count > 1
res.first.to_s.sub 'x', res.last.to_s
else
res.first.to_s
end.gsub '_', ' '
end
|