Sha256: 94ae31034bfa7606e7edabf4fdcd6bd751c964d76ac431b52d4435673ca1c825

Contents?: true

Size: 687 Bytes

Versions: 2

Compression:

Stored size: 687 Bytes

Contents

module KingKonf
  # Decodes specially formatted duration strings.
  module DurationDecoder
    # Either a number or a time unit.
    PART = /(\d+|[wdhms])/

    # One or more parts, possibly separated by whitespace.
    VALID_DURATION = /^(#{PART}\s*)+$/

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

    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
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
king_konf-0.3.1 lib/king_konf/duration_decoder.rb
king_konf-0.3.0 lib/king_konf/duration_decoder.rb