Class: Puppet::Pops::Time::Timespan::Format

Inherits:
Object
  • Object
show all
Defined in:
lib/puppet/pops/time/timespan.rb,
lib/puppet/pops/time/timespan.rb

Overview

Represents a compiled Timestamp format. The format is used both when parsing a timestamp in string format and when producing a string from a timestamp instance.

Defined Under Namespace

Classes: DaySegment, FragmentSegment, HourSegment, LiteralSegment, MilliSecondSegment, MinuteSegment, NanoSecondSegment, SecondSegment, Segment, ValueSegment

Constant Summary collapse

DEFAULTS =
['%D-%H:%M:%S.%-N', '%H:%M:%S.%-N', '%M:%S.%-N', '%S.%-N', '%D-%H:%M:%S', '%H:%M:%S', '%D-%H:%M', '%S'].map { |str| FormatParser.singleton.parse_format(str) }

Instance Method Summary collapse

Constructor Details

#initialize(format, segments) ⇒ Format


541
542
543
544
# File 'lib/puppet/pops/time/timespan.rb', line 541

def initialize(format, segments)
  @format = format.freeze
  @segments = segments.freeze
end

Instance Method Details

#format(timespan) ⇒ Object


546
547
548
549
550
# File 'lib/puppet/pops/time/timespan.rb', line 546

def format(timespan)
  bld = timespan.negative? ? '-' : ''
  @segments.each { |segment| segment.append_to(bld, timespan) }
  bld
end

#parse(timespan) ⇒ Object

Raises:

  • (ArgumentError)

552
553
554
555
556
557
558
559
560
561
562
563
564
# File 'lib/puppet/pops/time/timespan.rb', line 552

def parse(timespan)
  md = regexp.match(timespan)
  raise ArgumentError, _("Unable to parse '%{timespan}' using format '%{format}'") % { timespan: timespan, format: @format } if md.nil?
  nanoseconds = 0
  md.captures.each_with_index do |group, index|
    segment = @segments[index]
    next if segment.is_a?(LiteralSegment)
    group.lstrip!
    raise ArgumentError, _("Unable to parse '%{timespan}' using format '%{format}'") % { timespan: timespan, format: @format } unless group =~ /\A[0-9]+\z/
    nanoseconds += segment.nanoseconds(group)
  end
  Timespan.new(timespan.start_with?('-') ? -nanoseconds : nanoseconds)
end

#to_sObject


566
567
568
# File 'lib/puppet/pops/time/timespan.rb', line 566

def to_s
  @format
end