Skip to content

Commit

Permalink
Avoid deprecation warning when raising
Browse files Browse the repository at this point in the history
When calling + or since between two time objects we should avoid
emitting two deprecation messages and avoiding any deprecation messages
if the deprecated fallback raises an exception.
  • Loading branch information
jhawthorn committed Jul 19, 2024
1 parent efd0e6c commit 3df6768
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 4 deletions.
4 changes: 2 additions & 2 deletions activesupport/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
* Deprecate addition for `Time` instances with `ActiveSupport::TimeWithZone`.
* Deprecate addition and since between two `Time` and `ActiveSupport::TimeWithZone`.

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.
Previously adding time instances together such as `10.days.ago + 10.days.ago` or `10.days.ago.since(10.days.ago)` produced a nonsensical future date. This behavior is deprecated and will be removed in Rails 8.1.

*Nick Schwaderer*

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,11 +218,12 @@ def ago(seconds)
def since(seconds)
self + seconds
rescue TypeError
result = to_datetime.since(seconds)
ActiveSupport.deprecator.warn(
"Passing an instance of #{seconds.class} to #{self.class}#since is deprecated. This behavior will raise " \
"a `TypeError` in Rails 8.1."
)
to_datetime.since(seconds)
result
end
alias :in :since

Expand Down
2 changes: 1 addition & 1 deletion activesupport/lib/active_support/time_with_zone.rb
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,11 @@ def +(other)
begin
result = utc + other
rescue TypeError
result = utc.to_datetime.since(other)
ActiveSupport.deprecator.warn(
"Adding an instance of #{other.class} to an instance of #{self.class} is deprecated. This behavior will raise " \
"a `TypeError` in Rails 8.1."
)
result = utc.since(other)
result.in_time_zone(time_zone)
end
result.in_time_zone(time_zone)
Expand Down
9 changes: 9 additions & 0 deletions activesupport/test/core_ext/time_with_zone_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,15 @@ def test_plus_two_time_instances_raises_deprecation_warning
end
end

def test_plus_with_invalid_argument
twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), @time_zone)
assert_not_deprecated(ActiveSupport.deprecator) do
assert_raises TypeError do
twz + Object.new
end
end
end

def test_plus_with_duration
assert_equal Time.utc(2000, 1, 5, 19, 0, 0), (@twz + 5.days).time
end
Expand Down

0 comments on commit 3df6768

Please sign in to comment.