Ruby或Rails中是否有一组内置的默认日期范围



我有一个模型,需要对照一些明显的常见日期范围或自定义日期范围进行检查。在Ruby或Rails中有没有内置的方法来实现这一点,或者至少有没有更优雅的方法来编写这一点?

class Model < ApplicationRecord
attr_accessor :range
RANGES = ['Today','This Week','This Month','Yesterday','Last Week','Last Month','Custom']
private
def set_range
if range.present?
if range == 'Today'
self.start_date = Date.today.beginning_of_day
self.end_date = Date.today.end_of_day
elsif range == 'This Week'
self.start_date = Date.today.beginning_of_week
self.end_date = Date.today.end_of_week
elsif range == 'This Month'
self.start_date = Date.today.beginning_of_month
self.end_date = Date.today.end_of_month
elsif range == 'Yesterday'
self.start_date = 1.day.ago.beginning_of_day
self.end_date = 1.day.ago.end_of_day
elsif range == 'Last Week'
self.start_date = 1.week.ago.beginning_of_week
self.end_date = 1.week.ago.end_of_week
elsif range == 'Last Month'
self.start_date = 1.month.ago.beginning_of_month
self.end_date = 1.month.ago.end_of_month
elsif range == 'Custom'
self.start_date = start_date.beginning_of_day if start_date.present?
self.end_date = end_date.beginning_of_day if end_date.present?
end
end
end
end

据我所知,没有任何内置内容,但我可能会做以下事情:

def set_range
return unless RANGES.include?(range)
# if you need dates
self.start_date, self.end_date = range_dates(range)
# if you need date/times (renamed attribute)
dates = range_dates(range)
self.starts = dates.first&.beginning_of_day
self.ends   = dates.last&.end_of_day
end
def range_dates(range)
today = Date.today
case range
when 'Today'
[today, today]
when 'This Week'
[today.beginning_of_week, today.end_of_week]
when 'This Month'
[today.beginning_of_month, today.end_of_month]
when 'Yesterday'
[today.yesterday, today.yesterday]
when 'Last Week'
[today.last_week.beginning_of_week, today.last_week.end_of_week]
when 'Last Month'
[today.last_month.beginning_of_month, today.last_month.end_of_month]
when 'Custom'
[start_date, end_date]
end
end

对于查询,可以使用groupdategem(https://github.com/ankane/groupdate)。在它的代码库中,你肯定会发现一些时间范围(如果我没有弄错的话,在那个gem中称为periods(。然而,我不确定你是否能把它们作为日期范围;如果没有,那将是对该gem的gread添加,或者更好的做法是:在另一个gem中提取它。我自己有时也会对这种需求感到困惑。

然后,对于简单的"单词"->时间跨度解析,有chronic:https://github.com/mojombo/chronic(这也允许像"去年冬天"这样的东西(。然而,这似乎是浪费资源,因为你只需要很少的案例,这可能是";预编译的";并且不需要在运行时进行解析。

总而言之,你的方法(和@dinjas的改进(在我看来很好,但据我所知,生态系统中确实缺少一个可以快速访问的宝石(例如TimeRanges.last_month(。但是,正如您的代码片段所示,实现并不太困难。

最新更新