Rails 6 adds before? and after? methods to Date, DateTime, Time, and TimeWithZone.

Rails 6 adds before? and after? methods to Date, DateTime, Time, and TimeWithZone.

We read > and < as “greater than” and “less than” in ruby. before? and after? methods make the date/time comparisons much more human-readable.

Before

We can compare two date or time objects using > and <.

Time.utc(2017, 3, 6, 11, 59, 59) < Time.utc(2016, 3, 6, 11, 59, 59)
# => false
Date.tomorrow > Date.today
# => true

This is not so easy to read. We read it as Date.tomorrow is “greater than” Date.today.

before? and after? methods

When comparing dates in English, one would say:

The due date for the assignment is before the end of the month. All submissions after the end date will be ignored.

To match these, we now have before? and after? comparison methods in ActiveSupport. We can now compare date and time values like so:

due_date = 4.days.from_now
due_date.before?(Date.today)
# => false
due_date.after?(Date.today)
# => true

The comparison is now much more readable and reads like: Is due date before today or after today?

Need expert help with Rails?

Saeloun is a Rails Foundation Contributing Member helping teams modernize, upgrade, scale, and maintain production Rails applications.

Our Expertise

  • Rails contributors
  • 500+ Technical Articles
  • Production Rails consulting
  • Performance Optimization

Services

  • Rails application development
  • Code Audits
  • Rails upgrades
  • Team Augmentation

Need help on your Ruby on Rails or React project?

Join Our Newsletter