class GoDuration::Duration

Duration deals with Golang's time.Duration. This type is commonly used in API's and/or CLI's, and is defined in the language itself (there is no formal specifcation or RFC for it). This class can be used to both parse and format duration strings.

Attributes

nanoseconds[R]

Public Class Methods

new(number, unit: :s) click to toggle source

Initializes a new duration instance.

@param number [Fixnum] @param unit [Symbol, :s]

@return [Duration]

# File lib/go-duration/duration.rb, line 45
def initialize(number, unit: :s)
  raise InvalidUnitError, unit unless UNITS[unit]
  @nanoseconds = number * UNITS[unit]
end

Public Instance Methods

hours() click to toggle source

Returns the number of hours in the duration.

@return [Fixnum]

# File lib/go-duration/duration.rb, line 81
def hours
  nanoseconds / UNITS[:h]
end
microseconds() click to toggle source

Returns the number of microseconds in the duration.

@return [Fixnum]

# File lib/go-duration/duration.rb, line 53
def microseconds
  nanoseconds / UNITS[:µs]
end
milliseconds() click to toggle source

Returns the number of milliseconds in the duration.

@return [Fixnum]

# File lib/go-duration/duration.rb, line 60
def milliseconds
  nanoseconds / UNITS[:ms]
end
minutes() click to toggle source

Returns the number of minutes in the duration.

@return [Fixnum]

# File lib/go-duration/duration.rb, line 74
def minutes
  nanoseconds / UNITS[:m]
end
seconds() click to toggle source

Returns the number of seconds in the duration.

@return [Fixnum]

# File lib/go-duration/duration.rb, line 67
def seconds
  nanoseconds / UNITS[:s]
end
to_i() click to toggle source

Returns the exact duration in nanoseconds.

@return [Fixnum]

# File lib/go-duration/duration.rb, line 88
def to_i
  nanoseconds
end
to_s() click to toggle source

Formats the duration into a Go duration string.

@return [String]

# File lib/go-duration/duration.rb, line 95
def to_s
  ns = nanoseconds
  fmt = ""

  UNITS.each do |unit, value|
    number, ns = ns.divmod(value)
    fmt << "#{number}#{unit}" if number > 0
  end

  fmt
end