基于年份和季度的日期范围

date range based on year and quarter

我有一个属性 quarter,我以字符串形式保存 - "2015-1",表示 2015 年和今年第一季度。

如何获取此 quarter 内所有日期的范围?

我需要它来进行包含验证:

validates :date,
    presence: true,
    inclusion: { in: something_that_returns_the_range_from_quarter_attr }

我会这样做:

#i would do the validation like so
validates :date_in_quarter

def date_in_quarter
  if self.date.blank? || !self.quarter_date_range.include?(self.date)
    self.errors.add(:date, "is blank or not in allowed range")
  end
end 

#the validation uses this method which gets date range from quarter attribute
def quarter_date_range
  year, quarter = self.quarter.split("-").collect(&:to_i)
  start_month = ((3 * quarter) - 2)
  start_date = Date.parse("#{year}-#{start_month}-01")
  end_date = start_date + 3.months - 1.day
  start_date..end_date
end