Class: Timely::TimeDifference

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

Constant Summary collapse

TIME_COMPONENTS =
i[years months weeks days hours minutes seconds].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.between(start_time, end_time) ⇒ Object



12
13
14
# File 'lib/timely/rails/time_difference.rb', line 12

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

Instance Method Details

#humanizeObject



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

def humanize
  diff_parts = []
  in_general.each do |part, quantity|
    next if quantity <= 0

    part = part.to_s.humanize

    part = part.singularize if quantity <= 1

    diff_parts << "#{quantity} #{part}"
  end

  last_part = diff_parts.pop
  if diff_parts.empty?
    last_part
  else
    [diff_parts.join(', '), last_part].join(' and ')
  end
end

#in_daysObject



28
29
30
# File 'lib/timely/rails/time_difference.rb', line 28

def in_days
  in_component(:days)
end

#in_each_componentObject



44
45
46
47
48
# File 'lib/timely/rails/time_difference.rb', line 44

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

#in_generalObject



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/timely/rails/time_difference.rb', line 50

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



32
33
34
# File 'lib/timely/rails/time_difference.rb', line 32

def in_hours
  in_component(:hours)
end

#in_minutesObject



36
37
38
# File 'lib/timely/rails/time_difference.rb', line 36

def in_minutes
  in_component(:minutes)
end

#in_monthsObject



20
21
22
# File 'lib/timely/rails/time_difference.rb', line 20

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

#in_secondsObject



40
41
42
# File 'lib/timely/rails/time_difference.rb', line 40

def in_seconds
  @time_diff
end

#in_weeksObject



24
25
26
# File 'lib/timely/rails/time_difference.rb', line 24

def in_weeks
  in_component(:weeks)
end

#in_yearsObject



16
17
18
# File 'lib/timely/rails/time_difference.rb', line 16

def in_years
  in_component(:years)
end