Create a gist now

Instantly share code, notes, and snippets.

class StatisticsController < ApplicationController
WeeklyReport = Struct.new(
:week_number,
:date_from,
:date_to,
:count_entries,
:avg_distance,
:avg_speed
)
def index
@weekly_reports = []
current_user.entries.group_by(&:week).each do |week, entries|
@weekly_reports << WeeklyReport.new.tap do |r|
r.week_number = week
r.date_from = weeks_to_date_from(week)
r.date_to = weeks_to_date_to(week)
r.count_entries = entries.count
r.avg_distance = avg_distance(entries)
r.avg_speed = avg_speed(entries)
end
end
end
private
def weeks_to_date_from(week)
(Date.new + week.to_i.weeks).to_s.split(',')[0]
end
def weeks_to_date_to(week)
(Date.new + week.to_i.weeks + 7.days).to_s.split(',')[0]
end
def avg_distance(entries)
distances = entries.sum(&:distance)
(distances / entries.count).round(2)
end
def avg_speed(entries)
speeds = entries.sum(&:speed)
(speeds / entries.count).round(2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment