Class: Shipit::Duration

Inherits:
ActiveSupport::Duration
  • Object
show all
Defined in:
app/models/shipit/duration.rb

Constant Summary collapse

ParseError =
Class.new(ArgumentError)
FORMAT =
/
  \A
  (?<days>\d+d)?
  (?<hours>\d+h)?
  (?<minutes>\d+m)?
  (?<seconds>\d+s?)?
  \z
/x
UNITS =
{
  's' => :seconds,
  'm' => :minutes,
  'h' => :hours,
  'd' => :days
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, parts = [[:seconds, value]]) ⇒ Duration

Returns a new instance of Duration.



42
43
44
# File 'app/models/shipit/duration.rb', line 42

def initialize(value, parts = [[:seconds, value]])
  super
end

Class Method Details

.parse(value) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'app/models/shipit/duration.rb', line 23

def parse(value)
  return new(-1) if value.to_s == "-1"

  unless match = FORMAT.match(value.to_s)
    raise ParseError, "not a duration: #{value.inspect}"
  end

  parts = []
  UNITS.each_value do |unit|
    if value = match[unit]
      parts << [unit, value.to_i]
    end
  end

  time = ::Time.current
  new(time.advance(parts.to_h) - time, parts)
end

Instance Method Details

#to_sObject



46
47
48
49
50
51
52
53
# File 'app/models/shipit/duration.rb', line 46

def to_s
  days, seconds_left = value.divmod(1.day.to_i)
  if days > 0
    "#{days}d#{Time.at(seconds_left).utc.strftime('%Hh%Mm%Ss')}"
  else
    Time.at(value).utc.strftime('%Hh%Mm%Ss')[/[^0a-z]\w+/] || '0s'
  end
end