Class: GoDuration::Duration
- Inherits:
-
Object
- Object
- GoDuration::Duration
- Defined in:
- lib/go-duration/duration.rb
Overview
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.
Instance Attribute Summary collapse
-
#nanoseconds ⇒ Object
readonly
Returns the value of attribute nanoseconds.
Instance Method Summary collapse
-
#hours ⇒ Fixnum
Returns the number of hours in the duration.
-
#initialize(number, unit: :s) ⇒ Duration
constructor
Initializes a new duration instance.
-
#microseconds ⇒ Fixnum
Returns the number of microseconds in the duration.
-
#milliseconds ⇒ Fixnum
Returns the number of milliseconds in the duration.
-
#minutes ⇒ Fixnum
Returns the number of minutes in the duration.
-
#seconds ⇒ Fixnum
Returns the number of seconds in the duration.
-
#to_i ⇒ Fixnum
Returns the exact duration in nanoseconds.
-
#to_s ⇒ String
Formats the duration into a Go duration string.
Constructor Details
#initialize(number, unit: :s) ⇒ Duration
Initializes a new duration instance.
45 46 47 48 |
# File 'lib/go-duration/duration.rb', line 45 def initialize(number, unit: :s) raise InvalidUnitError, unit unless UNITS[unit] @nanoseconds = number * UNITS[unit] end |
Instance Attribute Details
#nanoseconds ⇒ Object (readonly)
Returns the value of attribute nanoseconds.
37 38 39 |
# File 'lib/go-duration/duration.rb', line 37 def nanoseconds @nanoseconds end |
Instance Method Details
#hours ⇒ Fixnum
Returns the number of hours in the duration.
81 82 83 |
# File 'lib/go-duration/duration.rb', line 81 def hours nanoseconds / UNITS[:h] end |
#microseconds ⇒ Fixnum
Returns the number of microseconds in the duration.
53 54 55 |
# File 'lib/go-duration/duration.rb', line 53 def microseconds nanoseconds / UNITS[: |
#milliseconds ⇒ Fixnum
Returns the number of milliseconds in the duration.
60 61 62 |
# File 'lib/go-duration/duration.rb', line 60 def milliseconds nanoseconds / UNITS[:ms] end |
#minutes ⇒ Fixnum
Returns the number of minutes in the duration.
74 75 76 |
# File 'lib/go-duration/duration.rb', line 74 def minutes nanoseconds / UNITS[:m] end |
#seconds ⇒ Fixnum
Returns the number of seconds in the duration.
67 68 69 |
# File 'lib/go-duration/duration.rb', line 67 def seconds nanoseconds / UNITS[:s] end |
#to_i ⇒ Fixnum
Returns the exact duration in nanoseconds.
88 89 90 |
# File 'lib/go-duration/duration.rb', line 88 def to_i nanoseconds end |
#to_s ⇒ String
Formats the duration into a Go duration string.
95 96 97 98 99 100 101 102 103 104 105 |
# 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 |