提供日期范围的更好方法

Nicer way to provide Date Range

我在 rails 中创建了一个这样的日期时间范围:

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

Ruby 中是否有更好的方法使其更具可读性? 类似于:

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

非常感谢!

您可以"monkey-patch"Timeclass如下:

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 

Rails 不提供任何辅助方法来从日期创建日期范围。所以对你的问题的简短回答是 "no".

不过,您可以使用ActiveSupport::Duration的方法略微提高代码的可读性。当您执行 3.months.

之类的操作时返回
3.month.ago.to_date..Date.current
Date.current..40.days.from_now.to_date

如果您决定对 class 进行 monkeypatch 以添加其他功能,它应该是 ActiveSupport::Duration 而不是内置的 Time/DateTime class是的。


注意:

您将 ActiveSupport::TimeWithZone class 个实例与不支持时区 (Date) 的 class 个实例混合在一起。 3.months.ago returns ActiveSupport::TimeWithZone 的一个实例,您正在添加范围的另一边,没有任何时区信息。这可能会导致难以捕获错误。因此,最好使用 Date.current 而不是 Date.today.