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, symmetric "X ago"/"X from now".

Instance Method Summary collapse

Constructor Details

#initialize(collapse_minute: true) ⇒ TimeFormatter

collapse_minute buckets anything under a minute as "less than a minute ago/from now". Defaults to true.



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

def initialize(collapse_minute: true)
  @collapse_minute = collapse_minute
end

Instance Method Details

#string(at:, relative_to:) ⇒ Object

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



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

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

  if @collapse_minute && seconds < 60
    return future ? "less than a minute from now" : "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

  future ? "#{text} from now" : "#{text} ago"
end