Sha256: 5333283c2be79bcf5a94265a2b16b00eb4df5761d06a07a339a508c5760aa29e

Contents?: true

Size: 929 Bytes

Versions: 1

Compression:

Stored size: 929 Bytes

Contents

class DurationFormat
  SECONDS_PER_DAY = 86400
  SECONDS_PER_HOUR = 3600
  SECONDS_PER_MINUTE = 60
  PARTS = %i[day hour min sec].freeze
  PARTS_IN_SECONDS = { sec: 1, min: SECONDS_PER_MINUTE, hour: SECONDS_PER_HOUR, day: SECONDS_PER_DAY }.freeze

  def self.build_parts(value)
    parts = {}
    remainder = value.to_f

    PARTS.each do |part|
      next if part == :sec
      part_in_seconds = PARTS_IN_SECONDS[part]
      parts[part] = remainder.div(part_in_seconds)
      remainder = (remainder % part_in_seconds).round(9)
    end

    parts[:sec] = remainder

    parts
  end

  def self.format(value)
    parts = build_parts(value)
    (parts[:day] > 0 ? "#{parts[:day]}day " : "") + sprintf('%02d:%02d:%02d', parts[:hour], parts[:min], parts[:sec].round)
  end
end

class Integer
  def duration_format
    DurationFormat.format(self)
  end
end

class Float
  def duration_format
    DurationFormat.format(self)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
remain_timer-0.2.1 lib/duration_format.rb