ActiveSupport: Numeric#seconds and friends
One of the most iconic ActiveSupport extensions. Turning bare numbers into named durations.
poll_every = 30.seconds
cache_ttl = 15.minutes
grace_period = 2.hours + 30.minutes
schedule_in = 2.weeks
poll_every.to_i
# => 30
cache_ttl.to_i
# => 900
grace_period.to_i
# => 9000
schedule_in.to_i
# => 1209600
const pollEvery = 30 * 1000;
const cacheTtl = 15 * 60 * 1000;
const gracePeriod = 2 * 60 * 60 * 1000 + 30 * 60 * 1000;
const scheduleIn = 2 * 7 * 24 * 60 * 60 * 1000;
pollEvery / 1000;
// => 30
cacheTtl / 1000;
// => 900
gracePeriod / 1000;
// => 9000
scheduleIn / 1000;
// => 1209600
The readability matters, but the composability matters too. 1.day + 12.hours, 3.weeks - 2.days, 1.day.in_hours... all of that reads nicely and stays precise enough for ordinary application code.
The full family of methods includes:
- seconds
- minutes
- hours
- days
- weeks
- fortnights
- months
- years
Note that months and years are only implemented on Integer, while the rest are implemented on Numeric. This is because of the calendar-aware math that ActiveSupport does for those two units, which doesn't make as much sense for fractional values.
History
The original minutes, hours, days, and friends were already part of ActiveSupport 0.10.0, released in 2005.
seconds was added in Rails 1.1.0 in 2006, and Rails 2.0.0 in 2007 reworked the internals around ActiveSupport::Duration.