Code Coverage
 
Lines
Covered
98.55% covered (success)
98.55%
68 / 69
1
require 'chronic_duration'
1
module TheFox
1
module Timr
# Uses seconds as basis.
1
class Duration
1
include Error
# Basis Data (Integer)
#
# A Duration is stored as seconds.
1
attr_reader :seconds
1
def initialize(seconds = 0)
400
@seconds = seconds.to_i
400
@smh_seconds = nil
400
@smh_minutes = nil
400
@smh_hours = nil
end
# Seconds, Minutes, Hours as Array
1
def to_smh
1
@smh_seconds = @seconds
1
@smh_hours = @smh_seconds / 3600
1
@smh_seconds -= @smh_hours * 3600
1
@smh_minutes = @smh_seconds / 60
1
@smh_seconds -= @smh_minutes * 60
1
[@smh_seconds, @smh_minutes, @smh_hours]
end
# Converts seconds to `nh nm ns` format. Where `n` is a number.
1
def to_human
119
dur_opt = {
:format => :short,
:limit_to_hours => true,
:keep_zero => false,
:units => 2,
}
119
h = ChronicDuration.output(@seconds, dur_opt)
end
# Convert to_human to a String when nil.
1
def to_human_s
20
h = to_human
20
h ? h : '---'
end
# Man-days, Man-hours
#
# Man Unit:
#
# - 8 hours are 1 man-day.
# - 5 man-days are 1 man-week, and so on.
1
def to_man_days
7
if @seconds < 28800 # 8 * 3600 = 1 man-day
5
to_human
2
elsif @seconds < 144000 # 5 * 28800 = 1 man-week
1
seconds = @seconds
1
man_days = seconds / 28800
1
seconds -= man_days * 28800
1
man_hours = seconds / 3600
1
'%dd %dh' % [man_days, man_hours]
else
1
seconds = @seconds
1
man_weeks = seconds / 144000
1
seconds -= man_weeks * 144000
1
man_days = seconds / 28800
1
seconds -= man_days * 28800
1
man_hours = seconds / 3600
1
'%dw %dd %dh' % [man_weeks, man_days, man_hours]
end
end
# Adds two Durations.
1
def +(duration)
68
case duration
when Integer
1
Duration.new(@seconds + duration)
when Duration
66
Duration.new(@seconds + duration.seconds)
when nil
0
Duration.new(@seconds)
else
1
raise DurationError, "Wrong type #{duration.class} for '+' function."
end
end
# Subtract two Durations.
1
def -(duration)
23
case duration
when Integer
2
diff = @seconds - duration
when Duration
20
diff = @seconds - duration.seconds
else
1
raise DurationError, "Wrong type #{duration.class} for '+' function."
end
22
if diff < 0
5
diff = 0
end
22
Duration.new(diff)
end
# Lesser
1
def <(obj)
2
case obj
when Integer
1
@seconds < obj
when Duration
1
@seconds < obj.to_i
end
end
# Greater
1
def >(obj)
4
case obj
when Integer
1
@seconds > obj
when Duration
3
@seconds > obj.to_i
end
end
# String
1
def to_s
67
@seconds.to_s
end
# Use this instead of `Duration.seconds`.
1
def to_i
72
@seconds
end
# All methods in this block are static.
1
class << self
# Parse a String using [ChronicDuration](https://rubygems.org/gems/chronic_duration) and create a new Duration instance.
1
def parse(str)
14
Duration.new(ChronicDuration.parse(str))
end
end
end # class Duration
end # module Timr
end # module TheFox