Skip to content

Instantly share code, notes, and snippets.

@semmons99
Created February 14, 2011 19:14
Show Gist options
  • Select an option

  • Save semmons99/826373 to your computer and use it in GitHub Desktop.

Select an option

Save semmons99/826373 to your computer and use it in GitHub Desktop.
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
@txus

txus commented Feb 15, 2011

Copy link
Copy Markdown

It's a lot cleaner. Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment