Extract object to represent a period to tidy up params repetition

This commit is contained in:
Jorge Manrubia
2025-09-02 10:55:53 +02:00
parent dfbc77c2e5
commit a9d9351472
3 changed files with 55 additions and 25 deletions
+16 -24
View File
@@ -1,39 +1,31 @@
class PeriodHighlights < ApplicationRecord
class << self
def create_or_find_for(collections, starts_at:, duration: 1.week)
starts_at = normalize_anchor_date(starts_at)
self.for(collections, starts_at:, duration:) || create_for(collections, starts_at:, duration:)
end
def create_for(collections, starts_at:, duration: 1.week)
starts_at = normalize_anchor_date(starts_at)
key = key_for(collections)
events = Event.where(collection: collections).where(created_at: starts_at..starts_at + duration)
if events.any?
summarizer = Event::Summarizer.new(events)
summarized_content = summarizer.summarized_content # outside of transaction as this can be slow
create_or_find_by!(key:, starts_at:, duration:) do |record|
record.content = summarized_content
record.cost_in_microcents = summarizer.cost.in_microcents
end
end
end
def for(collections, starts_at:, duration: 1.week)
starts_at = normalize_anchor_date(starts_at)
key = key_for(collections)
find_by(key:, starts_at:, duration:)
period = Period.new(collections, starts_at:, duration:)
find_by(**period.as_params) if period.has_activity?
end
private
def key_for(collections)
Digest::SHA256.hexdigest(collections.ids.sort.join("-"))
def create_for(collections, starts_at:, duration: 1.week)
period = Period.new(collections, starts_at:, duration:)
if period.has_activity?
summarizer = Event::Summarizer.new(period.events)
summarized_content = summarizer.summarized_content # outside of transaction as this can be slow
create_or_find_by!(**period.as_params) do |record|
record.content = summarized_content
record.cost_in_microcents = summarizer.cost.in_microcents
end
end
end
def normalize_anchor_date(date)
date.utc.beginning_of_day
def key_for(events)
Digest::SHA256.hexdigest(events.ids.sort.join("-"))
end
end
+38
View File
@@ -0,0 +1,38 @@
class PeriodHighlights::Period
attr_reader :collections, :starts_at, :duration
def initialize(collections, starts_at:, duration:)
@collections = collections
@starts_at = normalize_anchor_date(starts_at)
@duration = duration
end
def events
@events ||= Event.where(collection: collections).where(created_at: window)
end
def has_activity?
events.any?
end
def key
@keu ||= Digest::SHA256.hexdigest(events.ids.sort.join("-"))
end
def as_params
{
key: key,
starts_at: starts_at,
duration: duration
}
end
private
def window
starts_at..starts_at + duration
end
def normalize_anchor_date(date)
date.utc.beginning_of_day
end
end
+1 -1
View File
@@ -18,7 +18,7 @@ module User::Highlights
end
def weekly_highlights_for(date)
PeriodHighlights.for collections, starts_at: highlights_starts_at(date), duration: 1.week
PeriodHighlights.for(collections, starts_at: highlights_starts_at(date), duration: 1.week)
end
private