From 1084d836c1ea7d16cb7ffccdb346421f66c789bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Sch=C3=A4dler?= Date: Sun, 7 Apr 2024 18:07:55 +0200 Subject: [PATCH] Implement sorting correctly with <=> operator --- app/models/group_score.rb | 13 +++++++++++++ app/serializers/group_serializer.rb | 8 +------- app/services/group_stage_service.rb | 12 +----------- 3 files changed, 15 insertions(+), 18 deletions(-) diff --git a/app/models/group_score.rb b/app/models/group_score.rb index 077b081..0882d87 100644 --- a/app/models/group_score.rb +++ b/app/models/group_score.rb @@ -7,4 +7,17 @@ class GroupScore < ApplicationRecord def difference_in_points scored_points - received_points end + + def <=>(other) + point_comparison = [-group_points, -difference_in_points, -scored_points] <=> [-other.group_points, -other.difference_in_points, -other.scored_points] + p point_comparison, team.name, other.team.name + if point_comparison.zero? + comparison_match = group.matches.find do |match| + match.match_scores.any? { |match_score| match_score.team == team } + end + comparison_match.scored_points_of(team) <=> comparison_match.scored_points_of(other.team) + else + point_comparison + end + end end diff --git a/app/serializers/group_serializer.rb b/app/serializers/group_serializer.rb index dbdca40..b533d39 100644 --- a/app/serializers/group_serializer.rb +++ b/app/serializers/group_serializer.rb @@ -7,12 +7,6 @@ class GroupSerializer < ApplicationSerializer has_many :matches def group_scores - sorted_group_scores = object.group_scores.sort_by do |x| - # sort sorts from smallest to largest, therefore we need to negate the values - [ - -x.group_points, -(x.scored_points - x.received_points), -x.scored_points - ] - end - sorted_group_scores.map { |group_score| GroupScoreSerializer.new(group_score) } + object.group_scores.sort.map { |group_score| GroupScoreSerializer.new(group_score) } end end diff --git a/app/services/group_stage_service.rb b/app/services/group_stage_service.rb index 6606d05..36e7732 100644 --- a/app/services/group_stage_service.rb +++ b/app/services/group_stage_service.rb @@ -93,17 +93,7 @@ class GroupStageService # @param group Group the group to get the teams from # @return [Array] of teams def teams_sorted_by_group_scores(group) - group.teams.sort do |a, b| - group_score_a = group.group_scores.find_by(team: a) - group_score_b = group.group_scores.find_by(team: b) - - [group_score_b.group_points, - group_score_b.difference_in_points, - group_score_b.scored_points] <=> - [group_score_a.group_points, - group_score_a.difference_in_points, - group_score_a.scored_points] - end + group.group_scores.sort.map(&:team) end # Returns all teams advancing to playoff stage from given group stage