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.

Constant Summary collapse

DATE_COMPONENTS =

:nodoc:

%i(years months days)

Instance Method Summary collapse

Constructor Details

#initialize(duration, precision: nil) ⇒ ISO8601Serializer

Returns a new instance of ISO8601Serializer.



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 = 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[:days]}D"    if parts.key?(:days)
  output << "#{parts[:weeks]}W"   if parts.key?(:weeks)
  time = +""
  time << "#{parts[:hours]}H"     if parts.key?(:hours)
  time << "#{parts[:minutes]}M"   if parts.key?(:minutes)
  if parts.key?(:seconds)
    time << "#{format_seconds(parts[:seconds])}S"
  end
  output << "T#{time}" unless time.empty?
  output
end