/
app.rb
95 lines (77 loc) · 1.77 KB
/
app.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
require 'rubygems'
require 'sinatra'
require 'builder'
require 'rest_client'
require 'dm-core'
require 'dm-postgres-adapter'
require 'dm-migrations'
require 'dm-validations'
DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/development.db")
class Competitor
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true
property :code, Integer, :required => true
has n, :votes
def self.nth_place(n)
ranked_competitors = all.sort {|a,b| -1*a.votes.count <=> b.votes.count}
return ranked_competitors[n.to_i-1]
end
end
class Authorization
include DataMapper::Resource
property :id, Serial
property :phone, String
property :pin, Integer
property :used, Boolean, :default => false
has 1, :vote
end
class Vote
include DataMapper::Resource
property :id, Serial
belongs_to :competitor
belongs_to :authorization
end
DataMapper.auto_upgrade!
post '/call' do
builder :call
end
post '/authorize_phone' do
a = Authorization.first(:phone => params[:From], :used => false)
if a
builder :collect_vote
else
builder :authorize_pin
end
end
post '/authorize_pin' do
a = Authorization.first(:pin => params[:Digits], :used => false)
if a
a.phone = params[:From]
a.save
builder :collect_vote
else
builder :authorize_pin
end
end
post '/collect_vote' do
builder :collect_vote
end
post '/tally_vote' do
if c = Competitor.first(:code => params[:Digits])
a = Authorization.first(:phone => params[:From])
v = Vote.new()
v.authorization = a
v.competitor = c
v.save
a.used = true
a.save
@name = c.name
builder :confirm_vote
else
builder :collect_vote
end
end
get %r{/nth_place/(\d+)} do |n|
puts Competitor.nth_place(n)
end