Watch out when saying something like 1.year
in Rails. The result is not a Fixnum
and can cause unexpected errors when the receiving end expects a Fixnum
.
While anything from seconds to months are Fixnum
s, a year is a Float
in Rails -- when called on a Fixnum
itself:
>> 10.seconds.class
=> Fixnum
>> 2.minutes.class
=> Fixnum
>> 24.hours.class
=> Fixnum
>> 28.days.class
=> Fixnum
>> 9.months.class
=> Fixnum
>> 1.year.class
=> Float # Boom.
While they are
technically correct
Show archive.org snapshot
(a year is almost never exactly 365 days), even 1.year.to_f
won't return a result that would justify always using floats: 31557600.0
is just the same as 365.days.to_f
.
Note that saying something like 8.5.hours
will be a Float
(for somewhat obvious reasons).
Rails 4
Introduced by Rails 4 accurate date and time measurements are provided by ActiveSupport::Duration
. It mainly supports the methods on Numeric.
>> 10.seconds.class
=> ActiveSupport::Duration
…
>> 1.year.class
=> ActiveSupport::Duration
Posted by Arne Hartherz to makandra dev (2013-03-06 09:52)