Created
February 14, 2011 19:14
-
-
Save semmons99/826373 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module RubyFight | |
| class Application < Sinatra::Base | |
| get '/fight/:player1/vs/:player2' do | |
| player1_github = params[:player1].gsub(".json", "") | |
| player2_github = params[:player2].gsub(".json", "") | |
| player1 = Player.fetch(github: player1_github) | |
| player2 = Player.fetch(github: player2_github) | |
| players = [player1, player2] | |
| respond_to do |wants| | |
| wants.html { fight_html_for players } | |
| wants.json { fight_json_for players } | |
| end | |
| end | |
| private | |
| def fight_html_for(players) | |
| { slim :fight, {}, {players: players} } | |
| end | |
| def fight_json_for(players) | |
| players.each do |player| | |
| player.populate_from_github | |
| player.populate_from_rubygems | |
| end | |
| winner, loser = players.sort.reverse | |
| { winner: winner.to_h, loser: loser.to_h }.to_json | |
| rescue | |
| Sinatra::NotFound | |
| end | |
| end | |
| class Player | |
| def self.fetch(*args) | |
| Player.where(*args).first || Player.create(*args) | |
| end | |
| def <=>(other) | |
| self.score <=> other.score | |
| end | |
| def to_h | |
| { name: self.name, github: self.github, score: self.score } | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's a lot cleaner. Thank you very much!