date range based on year and quarter

588 Views Asked by At

I have an attribute quarter, which I save in a string form - "2015-1", meaning year 2015 and first quarter of the year.

How can I get the range of all dates within this quarter?

I need it for inclusion validation:

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

There are 1 best solutions below

1
On BEST ANSWER

I would do it like this:

#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