Dry out Tournaments Controller

This commit is contained in:
Daniel Schädler 2019-04-29 19:17:03 +02:00
parent 88d8367c47
commit bfadc7a6af
1 changed files with 18 additions and 30 deletions

View File

@ -36,34 +36,12 @@ class TournamentsController < ApplicationController
# create tournament # create tournament
tournament = current_user.tournaments.new params tournament = current_user.tournaments.new params
if group_stage if group_stage
# if parameter group_stage = true groups = organize_teams_in_groups(teams)
groups = {}
# each team gets put into a hash of groups depending on the value assigned in team[:group]
# groups is a key value hash; key being the group, value being the array of teams within that group
teams.each do |team|
team_id = team[:id]
team_name = team[:name]
group = team[:group]
# convert teams parameter into Team objects
if team_id
team = Team.find team_id
put_team_into_groups_hash!(groups, team, group)
elsif team_name
team = Team.create name: team_name
put_team_into_groups_hash!(groups, team, group)
end
end
# add groups to tournament # add groups to tournament
result = AddGroupStageToTournamentAndSaveTournamentToDatabase.call(tournament: tournament, groups: groups.values) result = AddGroupStageToTournamentAndSaveTournamentToDatabase.call(tournament: tournament, groups: groups)
else else
# convert teams parameter into Team objects # convert teams parameter into Team objects
teams = teams.map do |team| teams = teams.map(&method(:find_or_create_team))
if team[:id]
Team.find team[:id]
elsif team[:name]
Team.create name: team[:name]
end
end
# associate provided teams with tournament # associate provided teams with tournament
tournament.teams = teams tournament.teams = teams
# add playoff stage to tournament # add playoff stage to tournament
@ -98,11 +76,21 @@ class TournamentsController < ApplicationController
private private
def put_team_into_groups_hash!(groups, team, group) def organize_teams_in_groups(teams)
if groups[group].is_a?(Array) # each team gets put into a array of teams depending on the group specified in team[:group]
groups[group] << team teams.group_by { |team| team['group'] }.values.map do |group|
else group.map do |team|
groups[group] = [team] find_or_create_team(team)
end
end
end
def find_or_create_team(team)
# convert teams parameter into Team objects
if team[:id]
Team.find team[:id]
elsif team[:name]
Team.create name: team[:name]
end end
end end