by equalarrow · 10y ago · 0 comments
I found Rails during the 0.9 releases. Coming from the horrific world of Java web frameworks like Spring and Tapestry, it was a revelation to see how fun and productive web programming could be again.
When I saw things like 2.times, 1.day.ago, and ActiveRecord, I knew I was done with Java web development. This isn't a knock against Java per se, but I just spent so much time in the trenches having to do busywork and configuration that isn't necessary if authors of those frameworks put programmer productivity and enjoyment first.
Thank you DHH!
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-impl...
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...
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.