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

Returns a new instance of Format.



539
540
541
542
# File 'lib/puppet/pops/time/timespan.rb', line 539

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

Instance Method Details

#format(timespan) ⇒ Object



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

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

#parse(timespan) ⇒ Object

Raises:

  • (ArgumentError)


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

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



564
565
566
# File 'lib/puppet/pops/time/timespan.rb', line 564

def to_s
  @format
end