app.kluk.fr/app/models/mood.rb

46 lines
1.2 KiB
Ruby
Raw Permalink Normal View History

2025-08-05 16:11:24 +02:00
class Mood < ApplicationRecord
2025-10-03 18:03:46 +02:00
class << self
def history_for_a_year
history(Date.today - 1.year, Date.today)
end
private
def history(from, to)
return [] if Mood.count < 1
2025-08-05 16:11:24 +02:00
2025-10-03 18:03:46 +02:00
first_monday = monday_of_the_week(first_mood_date(from))
2025-08-05 16:11:24 +02:00
2025-10-03 18:03:46 +02:00
current_date = first_monday
current_mode = last_mode_before(current_date)
log_mood = []
mood_range = Mood.order(:recorded_at).where(recorded_at: (first_monday..to))
mood_range.each do |mood|
while current_date < mood.recorded_at.to_date do
log_mood << [ current_date.to_s, current_mode ]
current_date += 1
end
current_mode = mood.mode
end
while current_date <= to.to_date do
2025-08-05 16:11:24 +02:00
log_mood << [ current_date.to_s, current_mode ]
current_date += 1
end
2025-10-03 18:03:46 +02:00
log_mood.each_slice(7).to_a
2025-08-05 16:11:24 +02:00
end
2025-10-03 18:03:46 +02:00
def first_mood_date(from)
Mood.order(recorded_at: :asc).where("recorded_at >= ?", from).first.recorded_at.to_date
end
def monday_of_the_week(date)
date - date.wday + 1
end
def last_mode_before(date)
mood = Mood.where("recorded_at < ?", date).last
mood&.mode || "croisiere"
2025-08-05 16:11:24 +02:00
end
end
end