module GoDuration

Constants

HOUR

One hour in nanoseconds.

MICROSECOND

One microsecond in nanoseconds.

MILLISECOND

One millisecond in nanoseconds.

MINUTE

One minute in nanoseconds.

NANOSECOND

The base unit, a single nanosecond.

SECOND

One second in nanoseconds.

UNITS

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

VERSION

Public Instance Methods

parse(duration) click to toggle source

Parses a Go time.Duration string.

@param duration [String] A Go duration string.

@return [Duration]

# 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