Sha256: 0a8e0e7359afc5e7967bdb48dc128dc7e6ade0e06f681841d37d35bad03e2bb2

Contents?: true

Size: 1.08 KB

Versions: 15

Compression:

Stored size: 1.08 KB

Contents

module Shipit
  class Duration < ActiveSupport::Duration
    ParseError = Class.new(ArgumentError)

    FORMAT = /
      \A
      (?<days>\d+d)?
      (?<hours>\d+h)?
      (?<minutes>\d+m)?
      (?<seconds>\d+s?)?
      \z
    /x
    UNITS = {
      's' => :seconds,
      'm' => :minutes,
      'h' => :hours,
      'd' => :days,
    }.freeze

    class << self
      def parse(value)
        unless match = FORMAT.match(value.to_s)
          raise ParseError, "not a duration: #{value.inspect}"
        end
        parts = []
        UNITS.each_value do |unit|
          if value = match[unit]
            parts << [unit, value.to_i]
          end
        end

        time = ::Time.current
        new(time.advance(parts.to_h) - time, parts)
      end
    end

    def initialize(value, parts = [[:seconds, value]])
      super
    end

    def to_s
      days, seconds_left = value.divmod(1.day.to_i)
      if days > 0
        "#{days}d#{Time.at(seconds_left).utc.strftime('%Hh%Mm%Ss')}"
      else
        Time.at(value).utc.strftime('%Hh%Mm%Ss')[/[^0a-z]\w+/] || '0s'
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
shipit-engine-0.31.0 app/models/shipit/duration.rb
shipit-engine-0.30.0 app/models/shipit/duration.rb
shipit-engine-0.29.0 app/models/shipit/duration.rb
shipit-engine-0.28.1 app/models/shipit/duration.rb
shipit-engine-0.28.0 app/models/shipit/duration.rb
shipit-engine-0.27.1 app/models/shipit/duration.rb
shipit-engine-0.27.0 app/models/shipit/duration.rb
shipit-engine-0.26.0 app/models/shipit/duration.rb
shipit-engine-0.25.1 app/models/shipit/duration.rb
shipit-engine-0.25.0 app/models/shipit/duration.rb
shipit-engine-0.24.0 app/models/shipit/duration.rb
shipit-engine-0.23.1 app/models/shipit/duration.rb
shipit-engine-0.23.0 app/models/shipit/duration.rb
shipit-engine-0.22.0 app/models/shipit/duration.rb
shipit-engine-0.21.0 app/models/shipit/duration.rb