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:



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

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

Instance Method Details

#serializeObject

Builds and returns output string.



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

def serialize
  parts, sign = normalize
  return "PT0S" 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