Before? And After? - Ruby Time Class Mixin
Join the DZone community and get the full member experience.Join For Free
The mixin below allows comparison between two Time objects using the more intuitive and natural-sounding before? and after? methods. Some examples (using Rails' ActiveSupport Time extensions or (preferred) the 'units' gem):
2.minutes.ago.after? Time.now # => false
Time.now.before? 2.hours.from_now # => true
module BeforeAndAfter LEFT_SIDE_LATER = 1 RIGHT_SIDE_LATER = -1 def before?(input_time) (self <=> input_time) == RIGHT_SIDE_LATER end def after?(input_time) (self <=> input_time) == LEFT_SIDE_LATER end end Time.send :include , BeforeAndAfter
Opinions expressed by DZone contributors are their own.