Class: Humane::TimeFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/humane/time_formatter.rb

Overview

Formats one time relative to another the way Finder-adjacent tools do.

Instance Method Summary collapse

Constructor Details

#initialize(include_seconds: false, approximate: false) ⇒ TimeFormatter

include_seconds shows exact seconds under a minute instead of collapsing to "less than a minute ago/in less than a minute". Defaults to false, matching ActionView's include_seconds. approximate prefixes "about"/"in about" on buckets of an hour or more, matching ActionView's distance_of_time_in_words past that same boundary. Defaults to false.



8
9
10
11
# File 'lib/humane/time_formatter.rb', line 8

def initialize(include_seconds: false, approximate: false)
  @include_seconds = include_seconds
  @approximate = approximate
end

Instance Method Details

#string(at:, relative_to:) ⇒ Object

Returns the time at at relative to relative_to as a human-readable string.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/humane/time_formatter.rb', line 14

def string(at:, relative_to:)
  seconds = relative_to - at
  future = seconds.negative?
  seconds = seconds.abs

  if !@include_seconds && seconds < 60
    return future ? "in less than a minute" : "less than a minute ago"
  end

  text =
    if seconds < 60
      pluralize(seconds.to_i, "second")
    elsif seconds < 3600
      pluralize((seconds / 60.0).round, "minute")
    elsif seconds < 86_400
      pluralize((seconds / 3600.0).round, "hour")
    else
      pluralize((seconds / 86_400.0).round, "day")
    end

  text = "about #{text}" if @approximate && seconds >= 3600

  future ? "in #{text}" : "#{text} ago"
end