3 ms·
> 1.day.ago So apparently .day multiplies the number of seconds in a day by the receiver, then .ago subtracts that from the current date[0]. However, not all
by cballard 11y ago
> 1.day.ago
So apparently .day multiplies the number of seconds in a day by the receiver, then .ago subtracts that from the current date[0].
However, not all days contain the same number of seconds. This is where "friendly" APIs like this lose me - they're vague and sometimes incorrect.
In Foundation, which I consider to have a decently designed date API, "dates" are doubles of seconds all since a reference date, and "date components" are used to express the concept of days, months, and years - which also require a time zone and a calendar to even make sense.
[0] https://stackoverflow.com/questions/21392065/how-do-you-implement-1-day-ago-in-ruby https://stackoverflow.com/questions/21392065/how-do-you-impl...
- tomp 11y agoThat's a problem of implementation, not API. It could just as well instatiate a generic Day class that would know how to add itself to different dates.
- beat 11y agoSo if it actually matters, you do a better implementation. Or hack the Rails code and share your improvement back to the community. But the fact is, in most circumstances, good enough is good enough. And making programmer's lives easier is generally more valuable than corner-case optimization that makes things really hard to implement and understand.
- danielvf 11y agoThat StackOverflow answer is wrong. Rails does correctly handle `1.day.ago`, taking into account the number of seconds in a day. `1.day.ago` is a perfect example of what DHH was saying, in that it looks beautiful, but requires a bit of work under the hood. `1.day` creates a duration. This isn't just a number of seconds, but is represented by hash, more like `{:days=>1}`. When it's time to do the actual math, Rails looks at the :days number, and actually moves the day part of the date forwards and backwards. Source here: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/date/calculations.rb#L113 https://github.com/rails/rails/blob/master/activesupport/lib...