Class: Tins::Duration
- 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.:wordsuses spelled-out units (the default);:abbrevuses single-letter suffixes. A caller may instead pass their ownHashwith the same keys to #to_human to override either built-in, e.g. for another language. { 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
Hashwith three keys::words(3+ items),:two_words(exactly 2), and:last_word(before the final item, 3+ only).:noneproduces compact output ("1m30s");:spacesseparates with single spaces ("1 minutes 30 seconds");:proseuses grammatical connectors ("1 minutes, and 30 seconds").#to_human and parse_human accept a
connector:keyword argument that is either aSymbolnaming one of these presets or aHashwith the three keys for full control. Whenconnector:isnil(the default), the preset is derived fromstyle: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
-
.from_string(string, template: nil) ⇒ Duration
Creates a new Duration instance by parsing the given string with #parse.
-
.parse(string, template: nil) ⇒ Integer, Float
Parses a duration string against one or more templates, returning the total number of seconds.
- .parse_human(string, style: :words, connector: nil) ⇒ Duration
-
.parse_template(string, template:) ⇒ Object
Parses a duration string against a single template.
Instance Method Summary collapse
-
#<=>(other) ⇒ Integer
The <=> method compares this object with another object after converting both to floats.
-
#days? ⇒ TrueClass, FalseClass
Returns true if the duration includes days, false otherwise.
-
#format(template = '%S%d+%h:%m:%s.%f', precision: nil) ⇒ String
Formats the duration according to the given template and precision.
-
#format_smart ⇒ String
private
The format_smart method provides intelligent formatting based on the duration's components.
-
#fractional_seconds? ⇒ TrueClass, FalseClass
Returns true if the duration includes fractional seconds.
-
#hours? ⇒ TrueClass, FalseClass
Returns true if the duration has any hours component.
-
#initialize(seconds) ⇒ Duration
constructor
Initializes a new Duration object with the specified number of seconds.
-
#minutes? ⇒ TrueClass, FalseClass
Returns true if the duration has minutes, false otherwise.
-
#negative? ⇒ TrueClass, FalseClass
Returns true if the duration is negative.
-
#seconds? ⇒ TrueClass, FalseClass
Returns true if the duration has a positive seconds component.
-
#to_f ⇒ Float
Returns the duration's magnitude in seconds as a floating-point number.
-
#to_human(max: nil, style: :words, connector: nil) ⇒ String
Returns a human-readable string representation of the duration.
-
#to_s ⇒ String
The formatted duration string.
Methods included from ConnectorResolver
Constructor Details
#initialize(seconds) ⇒ Duration
Initializes a new Duration object with the specified number of seconds.
represent
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.
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.
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.
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
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
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.
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
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
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
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.
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
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
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?.
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).
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.
516 517 518 |
# File 'lib/tins/duration.rb', line 516 def to_s format_smart end |