Skip to content

Instantly share code, notes, and snippets.

@teeerevor
Created October 24, 2011 09:14
Show Gist options
  • Save teeerevor/1308645 to your computer and use it in GitHub Desktop.
Save teeerevor/1308645 to your computer and use it in GitHub Desktop.
Team#result refactor
Moved to League. Stats now updated by module, which is mixed into LeagueStats, TeamStats etc
class League < ActiveRecord::Base
...
def result(game)
team_result(game, game.team1, game.team1_score, game.team2_score)
team_result(game, game.team2, game.team2_score, game.team1_score)
end
def team_result(game, team, score_for, score_against)
current_stats = {score_for: score_for, score_against: score_against }.with_indifferent_access
team.league_stats.latest.compute_order.each do |stat|
value = stat.new_value(current_stats)
current_stats[stat.stat_type.name] = value
team.league_stats << LeagueStat.create(stat.attributes.merge("game_id" => game.id, "value" => value))
stat.update_attribute(:latest, false)
end
end
...
end
module Stat
class StatMissingError < StandardError; end
def new_value(stats)
send("#{stat_type.name}_new_value", stats)
end
def played_new_value(stats)
value + 1
end
def wins_new_value(stats)
check_for_needed_stats([:score_for, :score_against], stats)
stats[:score_for] > stats[:score_against] ? value + 1 : value
end
def draws_new_value(stats)
check_for_needed_stats([:score_for, :score_against], stats)
stats[:score_for] == stats[:score_against] ? value + 1 : value
end
def loses_new_value(stats)
check_for_needed_stats([:score_for, :score_against], stats)
stats[:score_for] < stats[:score_against] ? value + 1 : value
end
def for_new_value(stats)
check_for_needed_stats([:score_for], stats)
value + stats[:score_for]
end
def against_new_value(stats)
check_for_needed_stats([:score_against], stats)
value + stats[:score_against]
end
def difference_new_value(stats)
check_for_needed_stats([:score_for, :score_against], stats)
value + stats[:score_for] - stats[:score_against]
end
def points_new_value(stats)
check_for_needed_stats([:score_for, :score_against], stats)
v = value
v += 3 if stats[:score_for] > stats[:score_against]
v += 1 if stats[:score_for] == stats[:score_against]
v
end
def points_percentage_new_value(stats)
check_for_needed_stats([:for, :against], stats)
stats[:for].to_f / (stats[:against].nonzero? || 1) * 100
end
def win_percentage_new_value(stats)
check_for_needed_stats([:wins, :draws, :played], stats)
(stats[:wins] + stats[:draws] * 0.5).to_f / (stats[:played].nonzero? || 1) * 100
end
def check_for_needed_stats(needed_stats, stats)
needed_stats.each do |stat|
raise StatMissingError, "#{stat.to_s} missing" if stats[stat].nil?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment