Class: ActiveSupport::Duration::ISO8601Serializer

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

Overview

Serializes duration to string according to ISO 8601 Duration format.

Constant Summary collapse

DATE_COMPONENTS =
%i(years months days)

Instance Method Summary collapse

Constructor Details

#initialize(duration, precision: nil) ⇒ ISO8601Serializer


11
12
13
14
# File 'activesupport/lib/active_support/duration/iso8601_serializer.rb', line 11

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

Instance Method Details

#serializeObject

Builds and returns output string.


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

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[: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 << "#{sprintf(@precision ? "%0.0#{@precision}f" : '%g', parts[:seconds])}S"
  end
  output << "T#{time}" unless time.empty?
  "#{sign}#{output}"
end