Sha256: 4308d7e7e8405f8f44f018de582e9ba45131f6393ee0674cb1f4f713e81c1af1

Contents?: true

Size: 797 Bytes

Versions: 3

Compression:

Stored size: 797 Bytes

Contents

# frozen_string_literal: true

require "chronic_duration"

module Eye::Patch

  class ValueParser

    TIME_MATCHER = /\s(?<duration>(?:week|day|hour|minute|second)s?)(?:\s|\Z)/
    SIZE_MATCHER = /\s(?<size>(?:tera|giga|mega|kilo)?bytes?)(?:\s|\Z)/
    MATCHERS = {
      time: TIME_MATCHER,
      size: SIZE_MATCHER,
    }.freeze

    def self.parse(value)
      return value unless value.is_a?(String)

      result = MATCHERS.detect do |match_type, matcher|
        break send(:"parse_#{match_type}", value) if value.match(matcher)
      end

      result || value
    end

    def self.parse_time(value)
      ChronicDuration.parse(value)
    end

    def self.parse_size(value)
      unit = value.match(SIZE_MATCHER)[:size]
      value.gsub(/[^\d.]/, "").to_f.send(unit)
    end

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
eye-patch-1.1.0 lib/eye/patch/value_parser.rb
eye-patch-1.0.1 lib/eye/patch/value_parser.rb
eye-patch-1.0.0 lib/eye/patch/value_parser.rb