class ActiveSupport::Duration::ISO8601Serializer

Parent:
Object

Serializes duration to string according to ISO 8601 Duration format.

Public Class Methods

new(duration, precision: nil) Show source
# File activesupport/lib/active_support/duration/iso8601_serializer.rb, line 8
def initialize(duration, precision: nil)
  @duration = duration
  @precision = precision
end

Public Instance Methods

serialize() Show source
# File activesupport/lib/active_support/duration/iso8601_serializer.rb, line 14
def serialize
  output = 'P'
  parts, sign = normalize
  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}"  if time.present?
  "#{sign}#{output}"
end

Builds and returns output string.

© 2004–2018 David Heinemeier Hansson
Licensed under the MIT License.