Hi,
How would you refactor a code like this:
case filter do
:by_day ->
from(d in Download,
where: d.release_id == ^release_id,
group_by: fragment("date_trunc('day', ?)", d.day),
order_by: fragment("date_trunc('day', ?)", d.day),
select: {fragment("to_char(date_trunc('day', ?), 'YYYY-MM-DD')", d.day), fragment("sum(?)", d.downloads)})
:by_week ->
from(d in Download,
where: d.release_id == ^release_id,
group_by: fragment("date_trunc('week', ?)", d.day),
order_by: fragment("date_trunc('week', ?)", d.day),
select: {fragment("to_char(date_trunc('week', ?), 'YYYY-MM-DD')", d.day), fragment("sum(?)", d.downloads)})
:by_month ->
from(d in Download,
where: d.release_id == ^release_id,
group_by: fragment("date_trunc('month', ?)", d.day),
order_by: fragment("date_trunc('month', ?)", d.day),
select: {fragment("to_char(date_trunc('month', ?), 'YYYY-MM')", d.day), fragment("sum(?)", d.downloads)})
end
I was not able to do it because of the nature of date_trunc and fragment. I would like to just pass “day”, “month” or “week” and build dynamically the query.
Which refactors would you do?