Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 50 additions & 2 deletions lib/tago.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,46 @@ class Float
def seconds(format = nil)
s = self
s = -s if s.negative?
if format == :pretty
locales = {
en: {
numbers: { 0 => 'zero', 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six',
7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten' },
units: { microsecond: %w[microsecond microseconds], millisecond: %w[millisecond milliseconds],
second: %w[second seconds], minute: %w[minute minutes], hour: %w[hour hours], day: %w[day days],
week: %w[week weeks] }
}
}.freeze

if s < 0.001
val = (s * 1_000_000).to_i
unit = :microsecond
elsif s < 1
val = (s * 1000).to_i
unit = :millisecond
elsif s < 60
val = s.to_i
unit = :second
elsif s < 60 * 60
val = (s / 60).to_i
unit = :minute
elsif s < 24 * 60 * 60
val = (s / (60 * 60)).to_i
unit = :hour
elsif s < 7 * 24 * 60 * 60
val = (s / (24 * 60 * 60)).to_i
unit = :day
else
val = (s / (7 * 24 * 60 * 60)).to_i
unit = :week
end

num = val < 10 ? locales[:en][:numbers][val] : val.to_s
names = locales[:en][:units].fetch(unit)
unit_name = val == 1 ? names[0] : names[1]
return format('%<num>s %<unit_name>s', num:, unit_name:)
end

if s < 0.001
format('%dμs', s * 1000 * 1000)
elsif s < 1
Expand Down Expand Up @@ -69,7 +109,15 @@ def seconds(format = nil)
# Copyright:: Copyright (c) 2024-2025 Yegor Bugayenko
# License:: MIT
class Time
def ago(now = Time.now)
(now - self).seconds
def ago(arg = Time.now, pretty = nil)
if arg.is_a?(Symbol) || arg.nil?
format = arg
now = pretty || Time.now
else
now = arg
format = pretty
end

(now - self).seconds(format)
end
end
8 changes: 8 additions & 0 deletions test/test_tago.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,12 @@ def test_round_formatting
assert_equal('1d', 86_400.0.seconds(:round))
assert_equal('1w', 604_800.0.seconds(:round))
end

def test_pretty_formatting
t = Time.now
assert_equal('45 seconds', (t - 45.6).ago(:pretty))
five_weeks_three_days = (5 * 7 * 24 * 60 * 60) + (3 * 24 * 60 * 60)
assert_equal('five weeks', (t - five_weeks_three_days).ago(:pretty))
assert_equal('45 seconds', 45.6.seconds(:pretty))
end
end