When it comes to compare dates, for some reason my brain really struggles. I mix up <
and >=
all the time and end up flipping them.
Is start_date
greater than end_date
? Or vice-versa? I get confused because I think about dates in terms of before
and after
not greater_than
or less_than
.
Usage
Luckily, Rails is here to save the day and make sure I never make this mistake again by adding before?
and after?
for all Date-related comparisons.
start_date = Date.new(2019, 3, 31)
end_date = Date.new(2019, 4, 1)
start_date.before? end_date
#=> true
end_date.after? start_date
#=> true
start_date = Date.new(2020, 8, 11)
end_date = Date.new(2018, 8, 11)
start_date.before? end_date
#=> false
I find myself using these methods frequently in Rails model validations when I need to ensure two dates form a valid range.
class Promotion < ApplicationRecord
validate :valid_eligiblity_range?
def valid_eligiblity_range?
return unless expiration_date? && start_date?
if !expiration_date.after?(start_date)
errors.add(:start_date, "must be before Expiration Date")
errors.add(:expiration_date, "must be after Start Date")
end
end
end
Additional Resources
Rails API Docs: DateAndTime::Calculations#before?
Rails API Docs: DateAndTime::Calculations#after?
Top comments (0)