Clocks piled on top of each other

Jon Tyson

Use before? and after? Methods When Comparing Dates and Times in Rails

Active Support contains many additions to the basic classes that form the standard libraries of Ruby. There are extensions to String, Hash, Array and even Date and Time.

If you spend most of your time working inside Rails applications, you might not realise that these are Rails-isms rather than Ruby-isms.

Some folks dislike these ”superfluous” additions. Some of these additions end up back inside the Ruby standard library itself. Some of these methods help me not make mistakes when comparing times and dates.

Instead of…

…comparing dates and times with greater than or less than operators:

Date.new(1979, 9, 12) > Time.zone.now
#=> false

10.minutes_ago < 5.minutes.from_now
#=> true

Use…

before? and after?.

Date.new(1979, 9, 12).after?(Time.zone.now)
#=> false

10.minutes_ago.before?(5.minutes.from_now)
#=> true

Why?

This is a personal stylistic choice. I find the readability to be hugely improved when using before? and after?. It helps me to reason about the code much more easily as I’m writing it and, more importantly, to quickly understand my logic when I come back to it months later.

Why not?

Maybe you never get it wrong when you compare date and time objects. I do. A lot.

Sign up to get a nugget of Ruby knowledge every couple of weeks or so.

Last updated on September 19th, 2022