Module: Philiprehberger::Duration::Formatter

Defined in:
lib/philiprehberger/duration/formatter.rb

Overview

Format duration values for output

Constant Summary collapse

UNITS =
[
  [604_800, 'week', 'weeks'],
  [86_400, 'day', 'days'],
  [3600, 'hour', 'hours'],
  [60, 'minute', 'minutes'],
  [1, 'second', 'seconds']
].freeze

Class Method Summary collapse

Class Method Details

.to_human(total_seconds) ⇒ String

Format seconds as human-readable string

Parameters:

  • total_seconds (Numeric)

    total seconds

Returns:

  • (String)

    e.g. “2 hours, 30 minutes”



19
20
21
22
23
24
# File 'lib/philiprehberger/duration/formatter.rb', line 19

def self.to_human(total_seconds)
  return '0 seconds' if total_seconds.zero?

  parts = build_parts(total_seconds.to_i)
  parts.empty? ? '0 seconds' : parts.join(', ')
end

.to_iso8601(total_seconds) ⇒ String

Format seconds as ISO 8601 duration

Parameters:

  • total_seconds (Numeric)

    total seconds

Returns:

  • (String)

    e.g. “PT2H30M”



30
31
32
33
34
35
36
# File 'lib/philiprehberger/duration/formatter.rb', line 30

def self.to_iso8601(total_seconds)
  weeks, remainder = total_seconds.to_i.divmod(604_800)
  days, remainder = remainder.divmod(86_400)
  hours, remainder = remainder.divmod(3600)
  minutes, seconds = remainder.divmod(60)
  build_iso_string(weeks, days, hours, minutes, seconds)
end