Sha256: bd4bfb9d66e8ff894a98e1031ec1257b129756c4e893fea162c6861e8e7a705e

Contents?: true

Size: 1.36 KB

Versions: 12

Compression:

Stored size: 1.36 KB

Contents

module Tins
  class Duration
    def initialize(seconds)
      @days, @hours, @minutes, @seconds, @fractional_seconds =
        [ 86_400, 3600, 60, 1, 0 ].inject([ [], seconds ]) {|(r, s), d|
          if d > 0
            dd, rest = s.divmod(d)
            r << dd
            [ r, rest ]
          else
            r << s
          end
        }
    end

    def days?
      @days > 0
    end

    def hours?
      @hours > 0
    end

    def minutes?
      @minutes > 0
    end

    def seconds?
      @seconds > 0
    end

    def fractional_seconds?
      @fractional_seconds > 0
    end

    def format(template = '%d+%h:%m:%s.%f', precision: nil)
      result = template.gsub(/%[dhms]/,
        '%d' => @days,
        '%h' => '%02u' % @hours,
        '%m' => '%02u' % @minutes,
        '%s' => '%02u' % @seconds,
      )
      if result.include?('%f')
        if precision
          fractional_seconds = "%.#{precision}f" % @fractional_seconds
        else
          fractional_seconds = '%f' % @fractional_seconds
        end
        result.gsub!('%f', fractional_seconds[2..-1])
      end
      result
    end

    def to_s
      template  = '%h:%m:%s'
      precision = nil
      if days?
        template.prepend '%d+'
      end
      if fractional_seconds?
        template << '.%f'
        precision = 3
      end
      format template, precision: precision
    end
  end
end

Version data entries

12 entries across 12 versions & 3 rubygems

Version Path
ivanvc-logstash-input-s3-3.1.1.4 vendor/local/gems/tins-1.13.0/lib/tins/duration.rb
ivanvc-logstash-input-s3-3.1.1.3 vendor/local/gems/tins-1.13.0/lib/tins/duration.rb
ivanvc-logstash-input-s3-3.1.1.2 vendor/local/gems/tins-1.13.0/lib/tins/duration.rb
tins-1.13.0 lib/tins/duration.rb
tdiary-5.0.2 vendor/bundle/gems/tins-1.12.0/lib/tins/duration.rb
tins-1.12.0 lib/tins/duration.rb
tins-1.11.0 lib/tins/duration.rb
tdiary-5.0.1 vendor/bundle/gems/tins-1.10.2/lib/tins/duration.rb
tins-1.10.2 lib/tins/duration.rb
tins-1.10.1 lib/tins/duration.rb
tins-1.10.0 lib/tins/duration.rb
tins-1.9.0 lib/tins/duration.rb