Browse files

calculate ratings after match confirmation

  • Loading branch information...
1 parent c30c783 commit 5d9aeac7608c84d48f437ec7302ff8454473afb5 @aserafin aserafin committed Jan 3, 2014
Showing with 27 additions and 5 deletions.
  1. +20 −2 app/models/match.rb
  2. +6 −1 app/models/player.rb
  3. +1 −2 spec/models/player_spec.rb
View
22 app/models/match.rb
@@ -5,7 +5,7 @@ class Match < ActiveRecord::Base
state_machine :state, initial: :pending do
- after_transition on: :finished, do: :send_confirmation_email
+ after_transition on: :finished, do: :after_finished
after_transition on: :confirmed, do: :update_ratings
event :finish do
@@ -17,14 +17,32 @@ class Match < ActiveRecord::Base
end
end
+ def after_finished
+ set_winners_and_loosers
+ send_confirmation_email
+ end
+
+ def set_winners_and_loosers
+ case score.result
+ when 1 then self.winners = competitors.where(side: :home).pluck(:player_id)
+ when 0.5 then self.winners = []
+ when 0 then self.winners = competitors.where(side: :away).pluck(:player_id)
+ end
+
+ self.save
+ end
+
def send_confirmation_email
competitors.each do |competitor|
MatchMailer.confirmation_request(competitor.player, self).deliver unless competitor.player.id.eql?(self.finished_by)
end
end
def update_ratings
+ home_player = competitors.where(side: :home).first.player
+ away_player = competitors.where(side: :away).first.player
+ home_player.ratings.create value: tournament.rating.compute(score.result, home_player, away_player), rating_type: tournament.rating.class.to_s
+ away_player.ratings.create value: tournament.rating.compute(1 - score.result, away_player, home_player), rating_type: tournament.rating.class.to_s
end
-
end
View
7 app/models/player.rb
@@ -3,9 +3,14 @@ class Player < ActiveRecord::Base
has_many :ratings, class_name: 'PlayerRating'
+ after_create :setup_default_rating
+
def avatar_url
hash = Digest::MD5.hexdigest(email.downcase)
-
return "http://www.gravatar.com/avatar/#{hash}"
end
+
+ def setup_default_rating
+ self.ratings.create rating_type: 'Ratings::Elo', value: 1000
+ end
end
View
3 spec/models/player_spec.rb
@@ -5,6 +5,5 @@
it { should be_valid }
it { should respond_to :ratings }
- its(:ratings) { should be_empty }
-
+ it { subject.ratings.length.should == 1 }
end

0 comments on commit 5d9aeac

Please sign in to comment.