John Smith
John Smith

Reputation: 6259

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!

Upvotes: 2

Views: 107

Answers (2)

Uzbekjon
Uzbekjon

Reputation: 11813

Rails does not provide any helper methods to create date ranges from dates. So a short answer to your question would be "no".

However, you can slightly improve your code readability by using method of ActiveSupport::Duration. It is returned when you do things like 3.months.

3.month.ago.to_date..Date.current
Date.current..40.days.from_now.to_date

And if you decide to monkeypatch a class to add additional functionality, it should be ActiveSupport::Duration and not built-in Time/DateTime classes.


NOTE:

You are mixing ActiveSupport::TimeWithZone class instances with instances of classes that don't support time zones (Date). 3.months.ago returns an instance of ActiveSupport::TimeWithZone and you are adding the other side of the range without any timezone information. This may lead to hard to catch bugs. So, instead it is better to use Date.current instead of Date.today.

Upvotes: 4

Sergii K
Sergii K

Reputation: 845

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 

Upvotes: 1

Related Questions