Skip to content

Commit 233c2ae

Browse files
authored
Merge pull request #83 from ramzieus/add-pretty
Add :pretty to ago
2 parents 462addf + f7028ae commit 233c2ae

File tree

2 files changed

+58
-2
lines changed

2 files changed

+58
-2
lines changed

lib/tago.rb

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,46 @@ class Float
1414
def seconds(format = nil)
1515
s = self
1616
s = -s if s.negative?
17+
if format == :pretty
18+
locales = {
19+
en: {
20+
numbers: { 0 => 'zero', 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six',
21+
7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten' },
22+
units: { microsecond: %w[microsecond microseconds], millisecond: %w[millisecond milliseconds],
23+
second: %w[second seconds], minute: %w[minute minutes], hour: %w[hour hours], day: %w[day days],
24+
week: %w[week weeks] }
25+
}
26+
}.freeze
27+
28+
if s < 0.001
29+
val = (s * 1_000_000).to_i
30+
unit = :microsecond
31+
elsif s < 1
32+
val = (s * 1000).to_i
33+
unit = :millisecond
34+
elsif s < 60
35+
val = s.to_i
36+
unit = :second
37+
elsif s < 60 * 60
38+
val = (s / 60).to_i
39+
unit = :minute
40+
elsif s < 24 * 60 * 60
41+
val = (s / (60 * 60)).to_i
42+
unit = :hour
43+
elsif s < 7 * 24 * 60 * 60
44+
val = (s / (24 * 60 * 60)).to_i
45+
unit = :day
46+
else
47+
val = (s / (7 * 24 * 60 * 60)).to_i
48+
unit = :week
49+
end
50+
51+
num = val < 10 ? locales[:en][:numbers][val] : val.to_s
52+
names = locales[:en][:units].fetch(unit)
53+
unit_name = val == 1 ? names[0] : names[1]
54+
return format('%<num>s %<unit_name>s', num:, unit_name:)
55+
end
56+
1757
if s < 0.001
1858
format('%dμs', s * 1000 * 1000)
1959
elsif s < 1
@@ -69,7 +109,15 @@ def seconds(format = nil)
69109
# Copyright:: Copyright (c) 2024-2025 Yegor Bugayenko
70110
# License:: MIT
71111
class Time
72-
def ago(now = Time.now)
73-
(now - self).seconds
112+
def ago(arg = Time.now, pretty = nil)
113+
if arg.is_a?(Symbol) || arg.nil?
114+
format = arg
115+
now = pretty || Time.now
116+
else
117+
now = arg
118+
format = pretty
119+
end
120+
121+
(now - self).seconds(format)
74122
end
75123
end

test/test_tago.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,4 +90,12 @@ def test_round_formatting
9090
assert_equal('1d', 86_400.0.seconds(:round))
9191
assert_equal('1w', 604_800.0.seconds(:round))
9292
end
93+
94+
def test_pretty_formatting
95+
t = Time.now
96+
assert_equal('45 seconds', (t - 45.6).ago(:pretty))
97+
five_weeks_three_days = (5 * 7 * 24 * 60 * 60) + (3 * 24 * 60 * 60)
98+
assert_equal('five weeks', (t - five_weeks_three_days).ago(:pretty))
99+
assert_equal('45 seconds', 45.6.seconds(:pretty))
100+
end
93101
end

0 commit comments

Comments
 (0)