I don't. What does an Integer have to know about times and dates?
This is why I use it as an extension in specific cases.
For me, sometimes
convenience wins over principle.
irb(main):001:0> 3 + Time.now
TypeError: Time can't be coerced into Fixnum
from (irb):1:in `+'
from (irb):1
irb(main):002:0> Time.now + 3
=> Tue Aug 02 14:20:43 CEST 2005
I can live with that. The value in redefining + and - isn't worth the cost in
that case.
# - need different constants in Time/Date, etc.
# but then, 3.days.from(Time.now) and 3.days.from(Date.today)
# is going to stink too, unless you introduce a Day or Duration class...
Why? 6.months.ago returns a Time.
Date.today.ago(6.months) returns a Date.
Is the objection that 3.days returns 259200? I can see that on one level,
because Date and DateTime work off of a different scale than Time, does.
Adding 10 to a DateTime is entirely different than adding 10 to a Time. But,
really, adding 3.days to each should work the same (in my library, though, it
currently does not).
### Advantages:
# - no 'readable' methods polluting Integer namespace.
True. But, again, this is an extension to be used when it's pragmatic, and
isn't intended to be part of the core.
a = Time.now - 4*Days
b = a + Week
# I'm much shorter here and I don't have the confusing word "now" in the
# code.
from_now is just an alias. I could also do:
b = a + 1.week
And, in fact, when I use these, that's how I do it, most of the time. Every
once in a while, from_now _reads_ better to me, for a specific use, though,
and since my goal is to make this code easy for _me_ to read and maintain,
I'll use it in those cases.
That works if b is a Time. With your constants, though, that fails if b is a
Date or DateTime, as you alluded to in your Disadvantages list.
irb(main):003:0> b = DateTime.now
=> #<DateTime: 211989753587396153/86400000000,-1/4,2299161>
irb(main):004:0> 2.weeks.since(b).to_time
=> Tue Aug 16 08:39:47 MDT 2005
please use "next" and "prev" (as well as "last" and "first"
)
in pairs.
In my English vernacular, last month is the previous month, but yeah, one can
do:
a = Time.now.prev_month
if anything, last_month should be a class method, like Time.now()
Maybe. next_month and next_year and their ilk are just sugar to make the code
read a bit more easily, for me.
One of the places where I use this is in a web based calendar that a customer
uses to schedule her workshops and conferences. It shows her a view of three
months at a time, and for me it is convenient to just keep track of the
middle month and then refer to the following or previous months with
#next_month and #last_month.
Making next_month into a class method would be far less useful to me.
Thanks,
Kirk Haines