forked from nusco/scoreboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscoreboard.rb
96 lines (83 loc) · 1.67 KB
/
scoreboard.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
require 'bundler/setup'
require 'sinatra'
configure do
require 'redis'
if ENV["REDISTOGO_URL"]
uri = URI.parse(ENV["REDISTOGO_URL"])
REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
end
begin
REDIS.get("key")
rescue
puts "WARNING: Could not connect to redis - using an in-memory mock"
require "mock_redis"
REDIS = MockRedis.new
end
end
get '/' do
index
end
get '/score' do
index
end
post '/score' do
team = params[:teamName]
closed = REDIS.get("closed")
if closed
return 405
end
begin
score = Integer(params[:score])
if score > 10
throw ArgumentError
elsif score == 10
REDIS.set("closed", "true")
winner = team
end
rescue
return 400
end
scoreboard = fetch_score_board
scoreboard[team] = score
save(scoreboard)
index(winner)
end
error [400, 405] do
index
end
helpers do
def score
scoreboard = fetch_score_board
if !scoreboard.empty?
scoreboard = scoreboard.sort_by {|key, value| value}.reverse
table = "<table>"
scoreboard.each do |key,value|
table << "<tr><td>#{key}</td><td>#{value}</td></tr>"
end
table << "</table>"
end
end
end
def index(winner = nil)
locals = {}
if REDIS.get("closed")
locals['message'] = "The challenge is over"
end
if winner
locals['message'] = "#{winner} Wins!"
end
erb :index, locals: locals
end
def fetch_score_board
scoreboard = {}
keys = REDIS.hkeys("scoreboard")
keys.each do |team|
scoreboard[team] = REDIS.hget("scoreboard", team)
end
return scoreboard
end
def save(scoreboard)
scoreboard.each do |team, value|
REDIS.hset("scoreboard", team, value)
end
end