Last Updated: February 25, 2016
· h3h

Working with time offsets into the past

When using ActiveRecord models to store objects with dates, it’s somewhat common
to want to create a method that uses a time offset into the past. For instance:

class Report < ActiveRecord::Base

  #  id            :integer(4)      not null, primary key
  #  name          :string(255)
  #  status        :string(255)
  #  created_at    :datetime
  #  updated_at    :datetime

  # Returns true if the report hasn't been modified in 30 days.
  def stale?
    # ...

In this case, I find it best to create a constant at the top of my class to represent the time period:


Then, I take advantage of ActiveSupport’s #ago method:

def stale?
  updated_at < STALE_TIME_PERIOD.ago

This way the actual value is in a constant (instead of appearing as a
“magic number” in the code), and the
method that uses the constant’s value isn’t doing any weird indirect math.

I find this to be expressive and useful when this pattern emerges.