This blog is part of our Rails 6 series.
Rails 6 adds before? and after? to Date , DateTime , Time and ActiveSupport::TimeWithZone classes.
before? and after? are aliases to < (less than) and > (greater than) methods respectively.
Let's checkout how it works.
Rails 5.2
Let's try calling before? on a date object in Rails 5.2.
1 2> > Date.new(2019, 3, 31).before?(Date.new(2019, 4, 1)) 3 4=> NoMethodError: undefined method 'before?' for Sun, 31 Mar 2019:Date 5from (irb):1 6 7> > Date.new(2019, 3, 31) < Date.new(2019, 4, 1) 8 9=> true
Rails 6.0.0.beta2
Now, let's compare Date , DateTime , Time and ActiveSupport::TimeWithZone objects using before? and after? in Rails 6.
1 2> > Date.new(2019, 3, 31).before?(Date.new(2019, 4, 1)) 3 4=> true 5 6> > Date.new(2019, 3, 31).after?(Date.new(2019, 4, 1)) 7 8=> false 9 10> > DateTime.parse('2019-03-31').before?(DateTime.parse('2019-04-01')) 11 12=> true 13 14> > DateTime.parse('2019-03-31').after?(DateTime.parse('2019-04-01')) 15 16=> false 17 18> > Time.parse('2019-03-31').before?(Time.parse('2019-04-01')) 19 20=> true 21 22> > Time.parse('2019-03-31').after?(Time.parse('2019-04-01')) 23 24=> false 25 26> > ActiveSupport::TimeWithZone.new(Time.utc(2019, 3, 31, 12, 0, 0), ActiveSupport::TimeZone["Eastern Time (US & Canada)"]).before?(ActiveSupport::TimeWithZone.new(Time.utc(2019, 4, 1, 12, 0, 0), ActiveSupport::TimeZone["Eastern Time (US & Canada)"])) 27 28=> true 29 30> > ActiveSupport::TimeWithZone.new(Time.utc(2019, 3, 31, 12, 0, 0), ActiveSupport::TimeZone["Eastern Time (US & Canada)"]).after?(ActiveSupport::TimeWithZone.new(Time.utc(2019, 4, 1, 12, 0, 0), ActiveSupport::TimeZone["Eastern Time (US & Canada)"])) 31 32=> false
Here is the relevant pull request for adding before? and after? methods and the pull request for moving before? and after? to DateAndTime::Calculations.