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.



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

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

Instance Method Details

#format(timespan) ⇒ Object



550
551
552
553
554
# File 'lib/puppet/pops/time/timespan.rb', line 550

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

#parse(timespan) ⇒ Object

Raises:

  • (ArgumentError)


556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# File 'lib/puppet/pops/time/timespan.rb', line 556

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



573
574
575
# File 'lib/puppet/pops/time/timespan.rb', line 573

def to_s
  @format
end