Doing time math with raw integers is fiddly, and you constantly run into bugs from misinterpreting the unit that a particular integer represents. It seems like ActiveSupport::Duration
should solve this, and be the go-to tool for convenient & correct arithmetic on durations, but it has some counter-intuitive behaviours that make it not spark joy.
The fundamental issue is this:
# โ actual: "1 hour and -1 minutes" ?!
assert_equal "59 minutes", (1.hour - 1.minute).inspect
To fix it, you need to build a new duration manually:
assert_equal "59 minutes", ActiveSupport::Duration.build(1.hour - 1.minute).inspect # โ
I understand that we may not want to pay the cost of normalizing this on every arithmetic operation, but perhaps we could add a #normalize
method that the user can call on their result to return automatically fix up the units?
assert_equal "59 minutes", (1.hour - 1.minute).normalize # ๐ฆ๐ฆ๐
I opened an issue for this a while ago, but it went stale: Normalize `ActiveSupport::Duration` when substracting durations ยท Issue #45087 ยท rails/rails ยท GitHub