From d17bc19b23d914b239ccea3e331a64828f01acf0 Mon Sep 17 00:00:00 2001 From: Petko Bordjukov Date: Thu, 13 Oct 2016 07:24:53 +0300 Subject: [PATCH] Optimize the conflicts table and summary models --- app/models/conflicts_summary.rb | 28 +++++++++++++++++++++++++++- app/models/conflicts_table.rb | 10 +++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/app/models/conflicts_summary.rb b/app/models/conflicts_summary.rb index 7eb6b5d..28f3761 100644 --- a/app/models/conflicts_summary.rb +++ b/app/models/conflicts_summary.rb @@ -11,8 +11,34 @@ class ConflictsSummary talk_ids.map do |talk_id| { talk_id: talk_id, - conflicts: ConflictsTable.new(talk_id: talk_id, other_talks_ids: talk_ids.reject { |id| id == talk_id }).conflicts + conflicts: conflicts_table[talk_id] } end end + + private + + def conflicts_table + @conflicts_table ||= blank_conflicts_table.merge(database_conflicts_table) + end + + def database_conflicts_table + Conflicts.where(left: talk_ids, right: talk_ids).group_by(&:left).map do |left, conflicts| + conflicts_row = blank_conflicts_row(talk_ids_without(left)) + conflicts_row.merge! conflicts.map { |right_conflicts| [right_conflicts.right, right_conflicts.conflicts] }.to_h + [left, conflicts_row] + end.to_h + end + + def talk_ids_without(talk_id) + talk_ids.reject { |id| id == talk_id } + end + + def blank_conflicts_row(other_talk_ids) + other_talk_ids.map { |talk_id| [talk_id, 0] }.to_h + end + + def blank_conflicts_table + talk_ids.map { |talk_id| [talk_id, blank_conflicts_row(talk_ids_without(talk_id))] }.to_h + end end diff --git a/app/models/conflicts_table.rb b/app/models/conflicts_table.rb index 464ce1d..0d1c71d 100644 --- a/app/models/conflicts_table.rb +++ b/app/models/conflicts_table.rb @@ -11,8 +11,16 @@ class ConflictsTable other_talks_ids.map do |right| { talk_id: right, - number_of_conflicts: Conflicts.new(left: talk_id, right: right).conflicts + number_of_conflicts: conflicts_hash[right] || 0 } end end + + private + + def conflicts_hash + @conflicts_hash ||= Conflicts.where(left: talk_id, right: other_talks_ids).map do |conflicts| + [conflicts.right, conflicts.conflicts] + end.to_h + end end