Class: Aspera::Units::Duration

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/aspera/units/duration.rb

Overview

Duration in the format of Aspera Sync (async DURATION): parsed from user input and formatted for display. Immutable, kept as an integer number of microseconds.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, unit = 's') ⇒ Duration

Returns a new instance of Duration.

Parameters:

  • value (Numeric, String) —

    Number of unit, or text parsed (a plain number in text is seconds, whatever unit)

  • unit (String) (defaults to: 's') —

    Time unit of a Numeric value, e.g. ms

Raises:



23
24
25
26
27
28
29
30
31
32
# File 'lib/aspera/units/duration.rb', line 23

def initialize(value, unit = 's')
  @microseconds =
    if value.is_a?(Numeric)
      (value * unit_us(unit)).round
    else
      Aspera.assert_type(value, String) { 'duration' }
      parse_us(value)
    end
  freeze
end

Instance Attribute Details

#microseconds ⇒ Integer (readonly)

Returns Duration in microseconds.

Returns:

  • (Integer) —

    Duration in microseconds



35
36
37
# File 'lib/aspera/units/duration.rb', line 35

def microseconds
  @microseconds
end

Instance Method Details

#<=>(other) ⇒ Object



58
59
60
61
# File 'lib/aspera/units/duration.rb', line 58

def <=>(other)
  return unless other.is_a?(Duration)
  @microseconds <=> other.microseconds
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/aspera/units/duration.rb', line 63

def eql?(other)
  other.is_a?(Duration) && @microseconds.eql?(other.microseconds)
end

#hash ⇒ Object



67
68
69
# File 'lib/aspera/units/duration.rb', line 67

def hash
  @microseconds.hash
end

#to_hms ⇒ String

Returns Duration as hh:mm:ss (seconds rounded).

Returns:

  • (String) —

    Duration as hh:mm:ss (seconds rounded)



53
54
55
56
# File 'lib/aspera/units/duration.rb', line 53

def to_hms
  seconds = rounded_seconds
  format('%02d:%02d:%02d', seconds / 3600, (seconds / 60) % 60, seconds % 60)
end

#to_s ⇒ String

Returns Duration as 1h02m03s, 2m03s or 3s (seconds rounded), accepted by #initialize.

Returns:

  • (String) —

    Duration as 1h02m03s, 2m03s or 3s (seconds rounded), accepted by #initialize



44
45
46
47
48
49
50
# File 'lib/aspera/units/duration.rb', line 44

def to_s
  seconds = rounded_seconds
  return "#{seconds}s" if seconds < 60
  hours, rest = seconds.divmod(3600)
  minutes, secs = rest.divmod(60)
  hours.positive? ? format('%dh%02dm%02ds', hours, minutes, secs) : format('%dm%02ds', minutes, secs)
end

#to_unit(unit) ⇒ Integer

Returns Duration in unit, rounded down.

Parameters:

  • unit (String) —

    Time unit of result, e.g. ms

Returns:

  • (Integer) —

    Duration in unit, rounded down



39
40
41
# File 'lib/aspera/units/duration.rb', line 39

def to_unit(unit)
  @microseconds / unit_us(unit)
end