Class: TimeDifference

Inherits:
Object
  • Object
show all
Defined in:
lib/time_difference.rb

Constant Summary collapse

TIME_COMPONENTS =
[:years, :months, :weeks, :days, :hours, :minutes, :seconds]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.between(start_time, end_time) ⇒ Object



10
11
12
# File 'lib/time_difference.rb', line 10

def self.between(start_time, end_time)
  new(start_time, end_time)
end

Instance Method Details

#humanizeObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/time_difference.rb', line 61

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

#in_daysObject



26
27
28
# File 'lib/time_difference.rb', line 26

def in_days
  in_component(:days)
end

#in_each_componentObject



42
43
44
45
46
# File 'lib/time_difference.rb', line 42

def in_each_component
  Hash[TIME_COMPONENTS.map do |time_component|
    [time_component, public_send("in_#{time_component}")]
  end]
end

#in_generalObject



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/time_difference.rb', line 48

def in_general
  remaining = @time_diff
  Hash[TIME_COMPONENTS.map do |time_component|
    if remaining > 0
      rounded_time_component = (remaining / 1.send(time_component).seconds).round(2).floor
      remaining -= rounded_time_component.send(time_component)
      [time_component, rounded_time_component]
    else
      [time_component, 0]
    end
  end]
end

#in_hoursObject



30
31
32
# File 'lib/time_difference.rb', line 30

def in_hours
  in_component(:hours)
end

#in_minutesObject



34
35
36
# File 'lib/time_difference.rb', line 34

def in_minutes
  in_component(:minutes)
end

#in_monthsObject



18
19
20
# File 'lib/time_difference.rb', line 18

def in_months
  (@time_diff / (1.day * 30.42)).round(2)
end

#in_secondsObject



38
39
40
# File 'lib/time_difference.rb', line 38

def in_seconds
  @time_diff
end

#in_weeksObject



22
23
24
# File 'lib/time_difference.rb', line 22

def in_weeks
  in_component(:weeks)
end

#in_yearsObject



14
15
16
# File 'lib/time_difference.rb', line 14

def in_years
  in_component(:years)
end