Skip to content

Commit 2d84a6b

Browse files
Widdershinjeremy
authored andcommitted
Add Duration#before and #after as aliases for #ago and #since
It's common in test cases at my job to have code like this: let(:today) { customer_start_date + 2.weeks } let(:earlier_date) { today - 5.days } With this change, we can instead write let(:today) { 2.weeks.after(customer_start_date) } let(:earlier_date) { 5.days.before(today) } Closes rails#27721
1 parent 8fc71d1 commit 2d84a6b

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

activesupport/CHANGELOG.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,19 @@
1+
* Add `ActiveSupport::Duration#before` and `#after` as aliases for `#until` and `#since`
2+
3+
These read more like English and require less mental gymnastics to read and write.
4+
5+
Before:
6+
7+
2.weeks.since(customer_start_date)
8+
5.days.until(today)
9+
10+
After:
11+
12+
2.weeks.after(customer_start_date)
13+
5.days.before(today)
14+
15+
*Nick Johnstone*
16+
117
* Soft-deprecated the top-level `HashWithIndifferentAccess` constant.
218
`ActiveSupport::HashWithIndifferentAccess` should be used instead.
319

activesupport/lib/active_support/duration.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,13 +180,15 @@ def since(time = ::Time.current)
180180
sum(1, time)
181181
end
182182
alias :from_now :since
183+
alias :after :since
183184

184185
# Calculates a new Time or Date that is as far in the past
185186
# as this Duration represents.
186187
def ago(time = ::Time.current)
187188
sum(-1, time)
188189
end
189190
alias :until :ago
191+
alias :before :ago
190192

191193
def inspect #:nodoc:
192194
parts.

activesupport/test/core_ext/duration_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,19 @@ def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_is_set
179179
Time.zone = nil
180180
end
181181

182+
def test_before_and_afer
183+
t = Time.local(2000)
184+
assert_equal t + 1, 1.second.after(t)
185+
assert_equal t - 1, 1.second.before(t)
186+
end
187+
188+
def test_before_and_after_without_argument
189+
Time.stub(:now, Time.local(2000)) do
190+
assert_equal Time.now - 1.second, 1.second.before
191+
assert_equal Time.now + 1.second, 1.second.after
192+
end
193+
end
194+
182195
def test_adding_hours_across_dst_boundary
183196
with_env_tz "CET" do
184197
assert_equal Time.local(2009, 3, 29, 0, 0, 0) + 24.hours, Time.local(2009, 3, 30, 1, 0, 0)

0 commit comments

Comments
 (0)