-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathtime_difference.rb
More file actions
79 lines (59 loc) · 1.75 KB
/
time_difference.rb
File metadata and controls
79 lines (59 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
require 'rubygems'
require "active_support/all"
class TimeDifference
private_class_method :new
TIME_COMPONENTS = [:years, :months, :weeks, :days, :hours, :minutes, :seconds]
def self.between(start_time, end_time)
new(start_time, end_time)
end
# Defining methods dynamically as in_years, in_months, etc.
TIME_COMPONENTS.each do |time_component|
define_method("in_#{time_component.to_s}") do
return @time_diff.round if time_component == :seconds
return (@time_diff / (1.day * 30.42)).round if time_component == :months
in_component(time_component)
end
end
def in_each_component
Hash[TIME_COMPONENTS.map do |time_component|
[time_component, public_send("in_#{time_component}")]
end]
end
def in_general
remaining = @time_diff
Hash[TIME_COMPONENTS.map do |time_component|
rounded_time_component = (remaining / 1.send(time_component)).floor
remaining -= rounded_time_component.send(time_component)
[time_component, rounded_time_component]
end]
end
def humanize
diff_parts = []
in_general.each do |part,quantity|
next if quantity <= 0
part = part.to_s.humanize
if quantity <= 1
part = part.singularize
end
diff_parts << "#{quantity} #{part}"
end
last_part = diff_parts.pop
if diff_parts.empty?
return last_part
else
return [diff_parts.join(', '), last_part].join(' and ')
end
end
private
def initialize(start_time, end_time)
start_time = time_in_seconds(start_time)
end_time = time_in_seconds(end_time)
@time_diff = (end_time - start_time).abs
end
def time_in_seconds(time)
time.to_time.to_f
end
def in_component(component)
(@time_diff / 1.send(component)).round
end
end