Matthew Lindfield Seager

Matthew Lindfield Seager

Ruby date comparison

I spent way too many minutes figuring out this “active” scope is valid:

scope :active, -> { where("read_at IS NULL OR read_at > ?", 7.days.ago) }

I want ones that were read less than 7 days ago!?

The key insight is that a date that is greater than another date is “more recent than” instead of “more than”. At first I just added a comment for future me, but then I fixed it properly with a comment AND a well-named scope:

scope :unread, -> { where(read_at: nil) }
scope :read_within_past, ->(period) { where("read_at > ?", period.ago) } # '>' == 'more recent than'
scope :active, -> { unread.or(read_within_past(7.days)) }

“Unread or read within past 7 days” is something even future me with too-little sleep should be able to read and understand!