From 84a1ce23296a1e9d40c19b3a53dd75846680a976 Mon Sep 17 00:00:00 2001 From: Malaber <32635600+Malaber@users.noreply.github.com> Date: Wed, 29 May 2019 18:30:10 +0200 Subject: [PATCH] Simplify controller code Matches update now gets rolled back via a Transaction --- app/controllers/matches_controller.rb | 40 +++++++++++++++++---------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/app/controllers/matches_controller.rb b/app/controllers/matches_controller.rb index b978852..ca5275d 100644 --- a/app/controllers/matches_controller.rb +++ b/app/controllers/matches_controller.rb @@ -13,27 +13,37 @@ class MatchesController < ApplicationController # PATCH/PUT /matches/1 def update new_state = match_params['state'] - if new_state == 'finished' && @match.current_leading_team.nil? - render json: { error: 'Stopping undecided Matches isn\'t allowed in playoff stage' }, - status: :unprocessable_entity - return - end - if @match.update(match_params) - if new_state == 'finished' - result = PopulateMatchBelowAndSave.call(match: @match) unless @match.group_match? - unless result.success? - render json: { error: 'Moving Team one stage down failed' }, status: :unprocessable_entity - return - end + + Match.transaction do + if @match.update(match_params) + handle_match_end if new_state == 'finished' + + render json: @match + else + render json: @match.errors, status: :unprocessable_entity + raise ActiveRecord::Rollback end - render json: @match - else - render json: @match.errors, status: :unprocessable_entity end end private + def handle_match_end + return if @match.group_match? + + if @match.winner.nil? + render json: { error: 'Stopping undecided Matches isn\'t allowed in playoff stage' }, + status: :unprocessable_entity + raise ActiveRecord::Rollback + end + + return if PopulateMatchBelowAndSave.call(match: @match).success? + + render json: { error: 'Moving Team one stage down failed' }, + status: :unprocessable_entity + raise ActiveRecord::Rollback + end + def validate_params case match_params['state'] when 'in_progress'