Class: ActiveSupport::Duration::ISO8601Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/active_support/duration/iso8601_serializer.rb

Overview

Serializes duration to string according to ISO 8601 Duration format.

Instance Method Summary collapse

Constructor Details

#initialize(duration, precision: nil) ⇒ ISO8601Serializer

:nodoc:



8
9
10
11
# File 'lib/active_support/duration/iso8601_serializer.rb', line 8

def initialize(duration, precision: nil)
  @duration = duration
  @precision = precision
end

Instance Method Details

#serializeObject

Builds and returns output string.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/active_support/duration/iso8601_serializer.rb', line 14

def serialize
  parts, sign = normalize
  return "PT0S".freeze if parts.empty?

  output = "P"
  output << "#{parts[:years]}Y"   if parts.key?(:years)
  output << "#{parts[:months]}M"  if parts.key?(:months)
  output << "#{parts[:weeks]}W"   if parts.key?(:weeks)
  output << "#{parts[:days]}D"    if parts.key?(:days)
  time = ""
  time << "#{parts[:hours]}H"     if parts.key?(:hours)
  time << "#{parts[:minutes]}M"   if parts.key?(:minutes)
  if parts.key?(:seconds)
    time << "#{sprintf(@precision ? "%0.0#{@precision}f" : '%g', parts[:seconds])}S"
  end
  output << "T#{time}" unless time.empty?
  "#{sign}#{output}"
end