Skip to content

Commit 1f92ae6

Browse files
Schwadjhawthorn
authored andcommitted
Deprecate adding two Time instances with ActiveSupport::TimeWithZone
Co-authored-by: Eileen M. Uchitelle <[email protected]> Co-authored-by: John Hawthorn <[email protected]> Ref: rails#52084 Subtracting two time instances results in a Float representing the time between the instances. Adding two time instances should not work, but it does. ```ruby 10.days.ago + 10.days.ago ``` [This change](https://github.com/rails/rails/pull/52084/files#diff-aa0ae5ccf92f812f874b632afe70375c52772636f927fe6e34ffeaebf54af9d1L303) removed the rescue statement that had made this possible. Now, it is a breaking change to have made that easy mistake. This commit instead deprecates this change until Rails 8.0 and raises a deprecation warning when adding two Time instances.
1 parent 55c4ade commit 1f92ae6

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

activesupport/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
* Deprecate addition for `Time` instances with `ActiveSupport::TimeWithZone`.
2+
3+
Previously adding time instances together such as `10.days.ago + 10.days.ago` produced a nonsensical future date. This behavior is deprecated and will be removed in Rails 8.0.
4+
5+
*Nick Schwaderer*
6+
17
* Support rfc2822 format for Time#to_fs & Date#to_fs.
28

39
*Akshay Birajdar*

activesupport/lib/active_support/time_with_zone.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,16 @@ def +(other)
300300
if duration_of_variable_length?(other)
301301
method_missing(:+, other)
302302
else
303-
result = utc + other
303+
begin
304+
result = utc + other
305+
rescue TypeError
306+
ActiveSupport.deprecator.warn(
307+
"Adding an instance of #{other.class} to an instance of #{self.class} is deprecated. This behavior will raise " \
308+
"a `TypeError` in Rails 8.1."
309+
)
310+
result = utc.since(other)
311+
result.in_time_zone(time_zone)
312+
end
304313
result.in_time_zone(time_zone)
305314
end
306315
end

activesupport/test/core_ext/time_with_zone_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,13 @@ def test_no_limit_on_times
400400
assert_equal [0, 0, 19, 31, 12, -8001], (twz - 10_000.years).to_a[0, 6]
401401
end
402402

403+
def test_plus_two_time_instances_raises_deprecation_warning
404+
twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), @time_zone)
405+
assert_deprecated(ActiveSupport.deprecator) do
406+
twz + 10.days.ago
407+
end
408+
end
409+
403410
def test_plus_with_duration
404411
assert_equal Time.utc(2000, 1, 5, 19, 0, 0), (@twz + 5.days).time
405412
end

0 commit comments

Comments
 (0)