John Smith John Smith - 5 months ago 15
Ruby Question

Nicer way to provide Date Range

I create a date time range like this in rails:

last_3_months = (Date.today - 3.month)..Date.today
next_40_days = Date.today..(Date.today + 40.days)


Is there a nicer way in Ruby to make it more readable?
Something like:

last_3_months = 3.months.ago.to_range
next_40_days = 40.days.from_now.to_range


Thanks a lot!

Answer

You can "monkey-patch" Time class as follows:

class Time
  def to_range
    self > Date.today ? (Date.today..self.to_date) : (self.to_date..Date.today)
  end
end

3.days.ago.to_range
# => Mon, 20 Jun 2016..Thu, 23 Jun 2016 
3.days.from_now.to_range
# => Thu, 23 Jun 2016..Sun, 26 Jun 2016