Module: Philiprehberger::Duration::Parser

Defined in:
lib/philiprehberger/duration/parser.rb

Overview

Parse duration strings into total seconds

Constant Summary collapse

HUMAN_PATTERN =
/(\d+(?:\.\d+)?)\s*(ms|milliseconds?|w(?:eeks?)?|d(?:ays?)?|h(?:ours?)?|m(?:in(?:utes?)?)?|s(?:ec(?:onds?)?)?)/i
ISO_PATTERN =
/\AP(?:(\d+)W)?(?:(\d+)D)?T?(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?\z/

Class Method Summary collapse

Class Method Details

.iso_to_seconds(match) ⇒ Object



46
47
48
49
# File 'lib/philiprehberger/duration/parser.rb', line 46

def self.iso_to_seconds(match)
  w, d, h, m, s = (1..5).map { |i| (match[i] || 0).to_f }
  (w * 604_800) + (d * 86_400) + (h * 3600) + (m * 60) + s
end

.parse(input) ⇒ Float

Parse input into total seconds

Parameters:

  • input (String, Numeric)

    the input to parse

Returns:

  • (Float)

    total seconds

Raises:



16
17
18
19
20
21
22
# File 'lib/philiprehberger/duration/parser.rb', line 16

def self.parse(input)
  case input
  when Numeric then input.to_f
  when String then parse_string(input)
  else raise Duration::Error, "Cannot parse #{input.class}"
  end
end