Skip to content

Instantly share code, notes, and snippets.

@sebyx07
Last active August 29, 2015 14:05
Show Gist options
  • Save sebyx07/ef67a442ec9a5ca6a585 to your computer and use it in GitHub Desktop.
Save sebyx07/ef67a442ec9a5ca6a585 to your computer and use it in GitHub Desktop.
class Match < ActiveRecord::Base
self.primary_key = :match_id
has_many :memberships, class_name: 'Match::Membership'
has_many :users, through: :memberships
validates :match_id, uniqueness: true
before_create :get_details
after_save :build_memberships_and_update_players_field
def get_details
self.attributes = Match.fetch(self.match_id).except('players')
end
def self.fetch(match_id)
req = Dota.match(match_id).raw_match
if req['error']
raise "No match details for #{self.match_id}"
end
req
end
def build_memberships_and_update_players_field(players = Match.fetch(self.match_id)['players'])
players.each do |player|
player['ability_upgrades'] = nil
player['steam_id'] = player['account_id'].to_i + 76561197960265728
profile = User::Profile.find_by(dota2_id: player['account_id'].to_s)
if profile && player['account_id'] != 4294967295
user = profile.user
profile_name = user.steam_profile.name
already_membership = Match::Membership.find_by(user: user, match_id: self.match_id)
if already_membership && already_membership.name != profile_name
already_membership.update(name: profile_name)
player['name'] = profile_name
else
player['registered'] = true
player['name'] = profile_name
membership = Match::Membership.new(player.except('ability_upgrades', 'steam_id', 'registered'))
membership.match_id = self.match_id
membership.user = user
membership.save!
end
elsif player['account_id'] != 4294967295
player['name'] = User.get_steam_name(player['steam_id'])
player['registered'] = false
else
player['name'] = 'peasant'
player['registered'] = false
end
end
self.players = players.to_json
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment