Guest User

Untitled

a guest
Jul 22nd, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. module RubyFight
  2.  
  3. class Application < Sinatra::Base
  4.  
  5. get '/fight/:player1/vs/:player2' do
  6. player1_github = params[:player1].gsub(".json", "")
  7. player2_github = params[:player2].gsub(".json", "")
  8.  
  9. player1 = Player.fetch(github: player1_github)
  10. player2 = Player.fetch(github: player2_github)
  11. players = [player1, player2]
  12.  
  13. respond_to do |wants|
  14. wants.html { fight_html_for players }
  15. wants.json { fight_json_for players }
  16. end
  17. end
  18.  
  19. private
  20.  
  21. def fight_html_for(players)
  22. { slim :fight, {}, {players: players} }
  23. end
  24.  
  25. def fight_json_for(players)
  26. players.each do |player|
  27. player.populate_from_github
  28. player.populate_from_rubygems
  29. end
  30.  
  31. winner, loser = players.sort.reverse
  32.  
  33. { winner: winner.to_h, loser: loser.to_h }.to_json
  34. rescue
  35. Sinatra::NotFound
  36. end
  37.  
  38. end
  39.  
  40. class Player
  41.  
  42. def self.fetch(*args)
  43. Player.where(*args).first || Player.create(*args)
  44. end
  45.  
  46. def <=>(other)
  47. self.score <=> other.score
  48. end
  49.  
  50. def to_h
  51. { name: self.name, github: self.github, score: self.score }
  52. end
  53.  
  54. end
  55.  
  56. end
Add Comment
Please, Sign In to add comment