Class: Tins::Duration

Inherits:
Object show all
Extended by:
ConnectorResolver
Includes:
Comparable, ConnectorResolver
Defined in:
lib/tins/duration.rb

Overview

A class to represent durations with support for formatting and parsing time intervals.

Defined Under Namespace

Modules: ConnectorResolver Classes: ParserError

Constant Summary collapse

HUMAN_STYLES =

Built-in label styles for #to_human. Keys are the unit symbols (+:days+, :hours, :minutes, :seconds); values are the literal strings appended directly after each unit's numeric value.

:words uses spelled-out units (the default); :abbrev uses single-letter suffixes. A caller may instead pass their own Hash with the same keys to #to_human to override either built-in, e.g. for another language.

See Also:

{
  abbrev: { days: 'd', hours: 'h', minutes: 'm', seconds: 's' }.freeze,
  words:  {
            days: ' days',   hours: ' hours',
            minutes: ' minutes', seconds: ' seconds'
          }.freeze
}.freeze
HUMAN_CONNECTORS =

Named connector presets for #to_human and parse_human.

Each entry maps to a Hash with three keys: :words (3+ items), :two_words (exactly 2), and :last_word (before the final item, 3+ only).

:none produces compact output ("1m30s"); :spaces separates with single spaces ("1 minutes 30 seconds"); :prose uses grammatical connectors ("1 minutes, and 30 seconds").

#to_human and parse_human accept a connector: keyword argument that is either a Symbol naming one of these presets or a Hash with the three keys for full control. When connector: is nil (the default), the preset is derived from style: via STYLE_DEFAULT_CONNECTOR.

{
  none:   { words: '',  two_words: '',  last_word: ''  }.freeze,
  spaces: { words: ' ', two_words: ' ', last_word: ' ' }.freeze,
  prose:  {
            words: ', ', two_words: ' and ', last_word: ', and '
          }.freeze
}.freeze
STYLE_DEFAULT_CONNECTOR =

Maps each built-in HUMAN_STYLES key to its default HUMAN_CONNECTORS preset. Used when connector: is not explicitly provided.

{ abbrev: :none, words: :prose }.freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ConnectorResolver

resolve_connector

Constructor Details

#initialize(seconds) ⇒ Duration

Initializes a new Duration object with the specified number of seconds.

represent

Parameters:

  • seconds (Integer, Float) —

    the total number of seconds to



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/tins/duration.rb', line 293

def initialize(seconds)
  @negative         = seconds < 0
  seconds           = seconds.abs
  @original_seconds = 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

Class Method Details

.from_string(string, template: nil) ⇒ Duration

Creates a new Tins::Duration instance by parsing the given string with #parse.

Examples:

Basic usage

Tins::Duration.from_string('6+05:04:03.21')
# => #<Tins::Duration: 6+05:04:03.210>

Custom template

Tins::Duration.from_string('05:04:03', template: '%h:%m:%s')
# => #<Tins::Duration: 0+05:04:03.000>

Parameters:

  • string (String) —

    The duration string to parse.

  • template (String, nil) (defaults to: nil) —

    for the duration format, see #format. Default: nil (falls back to the built-in format).

Returns:

Raises:

See Also:



228
229
230
# File 'lib/tins/duration.rb', line 228

def from_string(string, template: nil)
  new(parse(string, template:))
end

.parse(string, template: nil) ⇒ Integer, Float

Parses a duration string against one or more templates, returning the total number of seconds.

Templates are tried in order; the first one that matches wins. If no template matches, a ParserError is raised.

Examples:

Default template

Tins::Duration.parse('6+05:04:03')       # => 536643
Tins::Duration.parse('6+05:04:03.21')    # => 536643.21

Parsing negative durations

Tins::Duration.parse('-6+05:04:03')      # => -536643

Custom template

Tins::Duration.parse('05:04:03.21', template: '%h:%m:%s.%f')
# => 18243.21

Multiple templates (first match wins)

Tins::Duration.parse('1m 30s',
  template: [ '%m minutes %s seconds', '%S%d+%h:%m:%s.%f' ]
)

Parameters:

  • string (String) —

    The duration string to parse.

  • template (String, Array<String>, nil) (defaults to: nil) —

    A single template string, an array of template strings tried in order, or nil (the built-in default '%S%d+%h:%m:%s.%f').

Returns:

  • (Integer, Float) —

    The number of (fractional) seconds.

Raises:

See Also:



150
151
152
153
154
155
156
157
158
159
# File 'lib/tins/duration.rb', line 150

def parse(string, template: nil)
  templates = Array(template).dup
  templates.empty? and templates << '%S%d+%h:%m:%s.%f'
  templates.each do |template|
    result = parse_template(string, template:) and return result
  rescue ParserError
  end
  raise ParserError, "#{string.inspect} did not match any of the " \
    "templates in #{template.inspect}"
end

.parse_human(string, style: :words, connector: nil) ⇒ Duration

Parses a human-readable duration string (the inverse of #to_human) and returns a new Tins::Duration instance.

All 15 possible to_human output shapes (every subset of 1–4 units, in canonical order) are generated as templates for the given style, joined with the supplied connectors, and tried in order against #parse. The first template that matches wins.

Examples:

Spelled-out units (default)

Tins::Duration.parse_human('1 minutes and 30 seconds')
# => #<Tins::Duration: 00:01:30>

Abbreviated

Tins::Duration.parse_human('1m30s', style: :abbrev)
# => #<Tins::Duration: 00:01:30>

Round-trip with #to_human

d = Tins::Duration.new(3725)
Tins::Duration.parse_human(d.to_human).to_f  # => 3725.0

Parameters:

  • string (String) —

    The human-readable duration string.

  • style (Symbol, Hash) (defaults to: :words) —

    Built-in label style (+:abbrev+ or :words, see HUMAN_STYLES) or a custom Hash. Default: :words.

  • connector (Symbol, Hash, nil) (defaults to: nil) —

    Connector preset (HUMAN_CONNECTORS) or a custom Hash with keys :words, :two_words, :last_word. Default: nil (derived from style:).

Returns:

Raises:

  • (ArgumentError) —

    If style is neither a Symbol nor a Hash.

  • (ParserError) —

    If no generated template matches the string.

See Also:



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/tins/duration.rb', line 267

def parse_human(string, style: :words, connector: nil)
  labels =
    case style
    when Hash   then HUMAN_STYLES[:abbrev].merge(style)
    when Symbol then HUMAN_STYLES.fetch(style)
    else raise ArgumentError,
      "style must be a Symbol or Hash, got #{style.class}"
    end
  conn = resolve_connector(connector, style)
  units     = [ [ :days, '%d' ], [ :hours, '%h' ],
                [ :minutes, '%m' ], [ :seconds, '%s' ] ]
  templates = (1..4).reverse_each.flat_map do |n|
    units.combination(n).map do |combo|
      parts = combo.map { |k, d| "#{d}#{labels[k]}" }
                 .extend(EnumJoined)
      parts.joined(**conn)
    end
  end
  new(parse(string, template: templates))
end

.parse_template(string, template:) ⇒ Object

Parses a duration string against a single template.

Supported directives:

  • %S - Sign indicator (optional negative sign)
  • %d - Days component (integer)
  • %h - Hours component (integer)
  • %m - Minutes component (integer)
  • %s - Seconds component (integer)
  • %f - Fractional seconds component (decimal)
  • %% - Literal percent character

The parser is greedy and consumes as much of the input string as possible for each directive. If a directive expects a specific format but doesn't find it, a ParserError is raised.



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/tins/duration.rb', line 175

def parse_template(string, template:)
  s, t  = string.to_s.dup, template.dup
  d, sd = 0, 1
  loop do
    t.sub!(/\A(%[Sdhmsf%]|.)/) { |directive|
      case directive
      when '%S' then s.sub!(/\A-?/)   { sd *= -1 if _1 == ?-; '' }
      when '%d' then s.sub!(/\A\d+/)  { d += 86_400 * _1.to_i; '' }
      when '%h' then s.sub!(/\A\d+/)  { d += 3_600 * _1.to_i; '' }
      when '%m' then s.sub!(/\A\d+/)  { d += 60 * _1.to_i; '' }
      when '%s' then s.sub!(/\A\d+/)  { d += _1.to_i; '' }
      when '%f' then s.sub!(/\A\d+/)  { d += Float(?. + _1); '' }
      when '%%' then
        if s[0] == ?%
          s[0] = ''
        else
          raise ParserError, "expected %s, got #{s.inspect}"
        end
      else
        if directive == s[0]
          s[0] = ''
        else
          raise ParserError, "expected #{t.inspect}, got #{s.inspect}"
        end
      end
      ''
    } or break
  end
  sd * d
end

Instance Method Details

#<=>(other) ⇒ Integer

The <=> method compares this object with another object after converting both to floats.

equal, 1 if this object is greater than other

Parameters:

  • other (Object) —

    the object to compare with

Returns:

  • (Integer) —

    -1 if this object is less than other, 0 if they are



329
330
331
# File 'lib/tins/duration.rb', line 329

def <=>(other)
  to_f <=> other.to_f
end

#days? ⇒ TrueClass, FalseClass

Returns true if the duration includes days, false otherwise.

otherwise

Returns:

  • (TrueClass, FalseClass) —

    true if the duration has any days, false



345
346
347
# File 'lib/tins/duration.rb', line 345

def days?
  @days > 0
end

#format(template = '%S%d+%h:%m:%s.%f', precision: nil) ⇒ String

Formats the duration according to the given template and precision.

The template string supports the following directives:

  • %S - Sign indicator (negative sign if duration is negative)
  • %d - Days component
  • %H - Hours component (unpadded)
  • %h - Hours component (zero-padded to 2 digits)
  • %M - Minutes component (unpadded)
  • %m - Minutes component (zero-padded to 2 digits)
  • %u - Seconds component (unpadded)
  • %s - Seconds component (zero-padded to 2 digits)
  • %f - Fractional seconds component (without the leading decimal point)
  • %D - Smart format (automatically includes days, fractional seconds, and sign)
  • %% - Literal percent character

When using %f, the fractional part will be formatted according to the precision parameter.

Examples:

Basic formatting

duration = Tins::Duration.new(93784.123)
duration.format('%d+%h:%m:%s.%f') # => "1+02:03:04.123000"

Smart format

duration.format('%D') # => "1+02:03:04.123"

Custom precision

duration.format('%s.%f', precision: 2) # => "04.12"

Unpadded components

duration = Tins::Duration.new(93_784)
duration.format('%d day(s), %H hours, %M minutes, and %u seconds')
# => "1 day(s), 2 hours, 3 minutes, and 4 seconds"

Parameters:

  • template (String) (defaults to: '%S%d+%h:%m:%s.%f') —

    the format template to use for formatting Default: '%S%d+%h:%m:%s.%f'

  • precision (Integer) (defaults to: nil) —

    the precision to use for fractional seconds When nil, uses default formatting with 6 decimal places

Returns:

  • (String) —

    the formatted duration string



486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/tins/duration.rb', line 486

def format(template = '%S%d+%h:%m:%s.%f', precision: nil)
  result = template.gsub(/%[DdHhMmuSs%]/) { |directive|
    case directive
    when '%S' then ?- if negative?
    when '%d' then @days
    when '%H' then '%u' % @hours
    when '%h' then '%02u' % @hours
    when '%M' then '%u' % @minutes
    when '%m' then '%02u' % @minutes
    when '%u' then '%u' % @seconds
    when '%s' then '%02u' % @seconds
    when '%D' then format_smart
    when '%%' then '%'
    end
  }
  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

#format_smart ⇒ String (private)

The format_smart method provides intelligent formatting based on the duration's components. It automatically determines which components are present and formats them accordingly, making it ideal for human-readable output where you want to avoid showing zero values.

The smart format follows these rules:

  • If days are present, includes the day component (e.g., "1+02:03:04") - If fractional seconds are present, includes them with 3 decimal places (e.g., ".123")
  • If the duration is negative, includes the sign prefix

This method is used internally by #to_s and can also be called directly for smart formatting using the %D directive.

inclusion

Returns:

  • (String) —

    a formatted duration string using intelligent component



538
539
540
541
542
543
544
545
546
547
548
549
550
# File 'lib/tins/duration.rb', line 538

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

#fractional_seconds? ⇒ TrueClass, FalseClass

Returns true if the duration includes fractional seconds.

false otherwise

Returns:

  • (TrueClass, FalseClass) —

    true if fractional seconds are present,



376
377
378
# File 'lib/tins/duration.rb', line 376

def fractional_seconds?
  @fractional_seconds > 0
end

#hours? ⇒ TrueClass, FalseClass

Returns true if the duration has any hours component

otherwise

Returns:

  • (TrueClass, FalseClass) —

    true if hours are present, false



353
354
355
# File 'lib/tins/duration.rb', line 353

def hours?
  @hours > 0
end

#minutes? ⇒ TrueClass, FalseClass

Returns true if the duration has minutes, false otherwise.

Returns:

  • (TrueClass, FalseClass) —

    true if minutes are greater than 0, false otherwise



360
361
362
# File 'lib/tins/duration.rb', line 360

def minutes?
  @minutes > 0
end

#negative? ⇒ TrueClass, FalseClass

Returns true if the duration is negative.

negative time interval, false otherwise

Returns:

  • (TrueClass, FalseClass) —

    true if the duration represents a



337
338
339
# File 'lib/tins/duration.rb', line 337

def negative?
  @negative
end

#seconds? ⇒ TrueClass, FalseClass

Returns true if the duration has a positive seconds component.

false otherwise

Returns:

  • (TrueClass, FalseClass) —

    true if seconds are greater than zero,



368
369
370
# File 'lib/tins/duration.rb', line 368

def seconds?
  @seconds > 0
end

#to_f ⇒ Float

Returns the duration's magnitude in seconds as a floating-point number.

A duration represents the time span between two points; the span itself is always non-negative. The sign is a direction qualifier, tracked separately — see #negative?.

Returns:

  • (Float) —

    The magnitude of the duration in seconds. Always non-negative.



318
319
320
# File 'lib/tins/duration.rb', line 318

def to_f
  @original_seconds.to_f
end

#to_human(max: nil, style: :words, connector: nil) ⇒ String

Returns a human-readable string representation of the duration. By default, uses spelled-out units (e.g. 1 minutes and 30 seconds); pass style: :abbrev for compact single-letter suffixes (e.g. 1m30s), or pass your own Hash keyed by the unit symbols (+:days+, :hours, :minutes, :seconds) for arbitrary wording.

Fractional seconds are truncated (not rounded).

Examples:

Basic usage (default :words style)

Tins::Duration.new(90).to_human
# => "1 minutes and 30 seconds"
Tins::Duration.new(3725).to_human
# => "1 hours, 2 minutes, and 5 seconds"
Tins::Duration.new(86_400).to_human  # => "1 days"
Tins::Duration.new(0).to_human       # => "0 seconds"

Abbreviated units

Tins::Duration.new(90).to_human(style: :abbrev)
# => "1m30s"

Custom labels (e.g. another language)

Tins::Duration.new(90).to_human(
  style: { minutes: ' Min.', seconds: ' Sek.' }
)
# => "1 Min.30 Sek."

Negative durations

Tins::Duration.new(-90).to_human
# => "-1 minutes and 30 seconds"

Parameters:

  • max (Integer) (defaults to: nil) —

    Maximum number of time units to include, starting from the largest. Default: nil (all units).

  • connector (Symbol, Hash, nil) (defaults to: nil) —

    Connector preset (HUMAN_CONNECTORS) or a custom Hash with keys :words, :two_words, :last_word. Default: nil (derived from style:).

  • style (Symbol, Hash) (defaults to: :words) —

    Built-in label style (+:abbrev+ or :words, see HUMAN_STYLES) or a custom Hash mapping the unit symbols to label strings. A Hash is merged onto the :abbrev defaults, so omitting a key keeps the single-letter label. Default: :words.

Returns:

  • (String) —

    Human-readable duration string.

Raises:

  • (ArgumentError) —

    If style is neither a Symbol nor a Hash.

See Also:



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/tins/duration.rb', line 427

def to_human(max: nil, style: :words, connector: nil)
  labels =
    case style
    when Hash   then HUMAN_STYLES[:abbrev].merge(style)
    when Symbol then HUMAN_STYLES.fetch(style)
    else raise ArgumentError,
      "style must be a Symbol or Hash, got #{style.class}"
    end
  conn = resolve_connector(connector, style)
  parts = [
    [ @days, :days ], [ @hours, :hours ],
    [ @minutes, :minutes ], [ @seconds, :seconds ]
  ].select { |v, _| v > 0 }
  parts << [ 0, :seconds ] if parts.empty?
  parts  = parts.first(max) if max
  items  = parts.map { |v, k| "#{v}#{labels[k]}" }
           .extend(EnumJoined)
  result = items.joined(**conn)
  @negative ? "-#{result}" : result
end

#to_s ⇒ String

Returns the formatted duration string.

Returns:

  • (String) —

    the formatted duration string



516
517
518
# File 'lib/tins/duration.rb', line 516

def to_s
  format_smart
end