Module: GoDuration

Defined in:
lib/go-duration/errors.rb,
lib/go-duration/version.rb,
lib/go-duration/duration.rb

Defined Under Namespace

Classes: Duration, GoDurationError, InvalidUnitError

Constant Summary collapse

VERSION =
"0.1.4".freeze
NANOSECOND =

The base unit, a single nanosecond.

1.freeze
MICROSECOND =

One microsecond in nanoseconds.

1000 * NANOSECOND.freeze
MILLISECOND =

One millisecond in nanoseconds.

1000 * MICROSECOND.freeze
SECOND =

One second in nanoseconds.

1000 * MILLISECOND.freeze
MINUTE =

One minute in nanoseconds.

60 * SECOND.freeze
HOUR =

One hour in nanoseconds.

60 * MINUTE.freeze
UNITS =

A mapping of Go’s unit notations to their nanosecond values. Order is important, it defines how to_s works.

{
  h: HOUR,
  m: MINUTE,
  s: SECOND,
  ms: MILLISECOND,
  µs: MICROSECOND,
  us: MICROSECOND,
  ns: NANOSECOND,
}.freeze

Class Method Summary collapse

Class Method Details

.parse(duration) ⇒ Duration

Parses a Go time.Duration string.

Parameters:

  • duration (String)

    A Go duration string.

Returns:



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/go-duration/duration.rb', line 115

def parse(duration)
  ns = 0

  until duration.empty?
    number = duration.slice!(/^[[:digit:]]+/).to_i
    unit = duration.slice!(/^[[:alpha:]]+/).to_sym

    # Check that the units are recognized.
    raise InvalidUnitError, unit unless UNITS[unit]

    # Convert to nanoseconds and add to the total.
    ns += (number * UNITS[unit])
  end

  Duration.new(ns, unit: :ns)
end