Ruby on Rails has many useful helpers and extensions to core Ruby. Everyone using Rails does know forms like 10.days.ago
or 2.months.ago
. Well the former is sometimes risky one. Why? Look at this:
./script/console Loading development environment. >> Time.now => Mon Mar 12 13:58:16 +0100 2007 >> 12.months.ago => Fri Mar 17 13:58:19 +0100 2006 >>
This is what You have expected? Well in that case You probably know that months
has this simple definition:
44: def months 45: self * 30.days 46: end
Time travel was anticipated as an hard task :) and it is really. So what is answer to question: how to travel back in time with right months calculations? It is Time#advance
:
>> Time.now => Mon Mar 12 14:02:42 +0100 2007 >> Time.now.advance(:months => -2) => Fri Jan 12 14:02:43 +0100 2007 >>
Got it?
It\’ll be fixed in the next release: http://ryandaigle.com/articles/2007/1/26/what-s-new-in-edge-rails-1-month-from_now-no_longer-effed