I love the extensions that Rails has for the Ruby Time object (see ActiveSupport::CoreExtensions::Integer::Time) – you can do calculations like Time.now + 1.month, (4.months + 5.years).from_now, and other cool things.
In my last post, I mentioned working with an application that uses a subscription service. One of the things I want to do is send the subscriber an e-mail when the current subscription is about to expire. (I am not comfortable with the concept of auto-renewal; customers should have the right to “opt in” on the continuation of a subscription. Just personal preference.) So I set up a cron job that tests subscription expiration dates. Here’s the one that checks a month in advance:
next_month = Subscription.find(:all, :conditions => [ "subscription_expires_on = ?", (Time.now + 1.month).to_s.split() ])
With a test case subscription expiring on Feb 28, e-mail went out correctly on Jan 28. And also on Jan 29, Jan 30 and Jan 31. Ooops! My reminder has turned into nagware. What I really want is:
next_month = Subscription.find(:all, :conditions => [ "subscription_expires_on = ?", (Time.now + 30.days).to_s.split() ])
Live and learn.