2018-04-24 17:30:22 -04:00
|
|
|
module DateGroupable extend ActiveSupport::Concern
|
|
|
|
class_methods do
|
|
|
|
def group_by_day(column)
|
|
|
|
group_by_unit(:day, column)
|
|
|
|
end
|
|
|
|
|
|
|
|
def group_by_week(column)
|
|
|
|
group_by_unit(:week, column)
|
|
|
|
end
|
|
|
|
|
|
|
|
def group_by_month(column)
|
|
|
|
group_by_unit(:month, column)
|
|
|
|
end
|
|
|
|
|
|
|
|
def group_by_quarter(column)
|
|
|
|
group_by_unit(:quarter, column)
|
|
|
|
end
|
|
|
|
|
|
|
|
def group_by_year(column)
|
|
|
|
group_by_unit(:year, column)
|
|
|
|
end
|
|
|
|
|
|
|
|
def group_by_unit(aggregation_unit, column)
|
2018-04-26 11:19:44 -04:00
|
|
|
group("date_trunc('#{aggregation_unit}', #{column})::DATE")
|
|
|
|
.order("date_trunc('#{aggregation_unit}', #{column})::DATE")
|
2018-04-24 17:30:22 -04:00
|
|
|
end
|
|
|
|
|
2018-05-03 09:41:41 -04:00
|
|
|
def aggregation_unit_for_period(start_date, end_date)
|
2018-04-24 17:30:22 -04:00
|
|
|
days = (start_date.to_date..end_date.to_date).count
|
|
|
|
|
|
|
|
case
|
|
|
|
when days <= 40
|
2018-05-03 09:41:41 -04:00
|
|
|
return :day
|
|
|
|
when days <= 210 # 30 weeks
|
|
|
|
return :week
|
|
|
|
when days <= 550 # ~18 months
|
|
|
|
return :month
|
|
|
|
when days <= 1461 # ~4 years
|
|
|
|
return :quarter
|
2018-04-24 17:30:22 -04:00
|
|
|
else
|
2018-05-03 09:41:41 -04:00
|
|
|
return :year
|
2018-04-24 17:30:22 -04:00
|
|
|
end
|
2018-05-03 09:41:41 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def smart_group_by_date(column, start_date, end_date)
|
|
|
|
aggregation_unit = aggregation_unit_for_period(start_date, end_date)
|
2018-04-24 17:30:22 -04:00
|
|
|
|
|
|
|
where("#{column} BETWEEN ? AND ?", start_date, end_date)
|
|
|
|
.group_by_unit(aggregation_unit, column)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|