Module: KingKonf::DurationDecoder

Defined in:
lib/king_konf/duration_decoder.rb

Overview

Decodes specially formatted duration strings.

Constant Summary collapse

UNITS =
{
  "ms" => 0.001,
  "s"  => 1,
  "m"  => 60,
  "h"  => 60 * 60,
  "d"  => 60 * 60 * 24,
  "w"  => 60 * 60 * 24 * 7,
}
PART =

Either a number or a time unit.

/(\d+|#{UNITS.keys.join('|')})/
VALID_DURATION =

One or more parts, possibly separated by whitespace.

/^(#{PART}\s*)+$/

Class Method Summary collapse

Class Method Details

.decode(value) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/king_konf/duration_decoder.rb', line 20

def self.decode(value)
  if value !~ VALID_DURATION
    raise ConfigError, "#{value.inspect} is not a duration: must be e.g. `1h 30m`"
  end

  value.scan(PART).flatten.each_slice(2).map {|number, letter|
    number.to_i * UNITS.fetch(letter)
  }.sum
end