image by Jon Tyson
Active Support contains many additions to the basic classes that form the standard libraries of Ruby. There are extensions to
Array and even
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.
…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
Date.new(1979, 9, 12).after?(Time.zone.now) #=> false 10.minutes_ago.before?(5.minutes.from_now) #=> true
This is a personal stylistic choice. I find the readability to be hugely improved when using
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.
Maybe you never get it wrong when you compare date and time objects. I do. A lot.
Last updated on September 19th, 2022 by @andycroll
An email newsletter, with one Ruby/Rails technique delivered with a ‘why?’ and a ‘how?’ every two weeks. It’s deliberately brief, focussed & opinionated.