Class: Kali::Type::Duration

Inherits:
Kali::Type show all
Defined in:
lib/kali/type/duration.rb

Overview

Used to represent a duration of time, which can be nominal (days or weeks) or accurate (hours, days, minutes, or seconds).

See tools.ietf.org/html/rfc5545#section-3.3.6

Constant Summary collapse

LABELS =
{ week: "W", day: "D", hour: "H", minute: "M", second: "S" }

Instance Method Summary collapse

Methods inherited from Kali::Type

#decode, #encode, #initialize, #parameters

Constructor Details

This class inherits a constructor from Kali::Type

Instance Method Details

#decode!(string) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/kali/type/duration.rb', line 26

def decode!(string)
  duration = {}
  duration[:negative] = true if string.start_with?("-")
  matches = string.gsub(/\-\+PT/, "").scan(/((\d+)([WDHMS]))/)
  matches.each.with_object(duration) do |(_, n, suffix), duration|
    duration[LABELS.key(suffix)] = Integer(n)
  end
end

#encode!(obj) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/kali/type/duration.rb', line 9

def encode!(obj)
  negative = obj.delete(:negative) { false }
  duration = obj.sort_by { |label, _| LABELS.key(label) }

  nominal = true
  duration = obj.each_with_object("") do |(label, amount), acc|
    suffix = LABELS.fetch(label) do
      raise ArgumentError, "#{label.inspect} is not a valid duration period. It must be one of #{labels.keys.inspect}"
    end

    acc << "T" if nominal && !(nominal = nominal?(label))
    acc << "#{amount}#{suffix}"
  end

  "#{"-" if negative}P#{duration}"
end