forked from MLH/mlh-no-light
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathno_light_sinatra.rb
104 lines (83 loc) · 2.57 KB
/
no_light_sinatra.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
97
98
99
100
101
102
103
104
require_relative 'models/submission'
class NoLightSinatra < Sinatra::Base
set public_folder: 'public', static: true
configure do
environments = {
'development' => { 'uri' => 'mongodb://localhost/no_light_development' },
'test' => { 'uri' => 'mongodb://localhost/no_light_test' },
'production' => { 'uri' => ENV['MONGODB_URI'] }
}
DEFAULT_BRANDING = 'dell'
MongoMapper.setup(environments, ENV['RACK_ENV'])
end
get '/' do show_default_page end
post '/submit' do
@submission = Submission.new(get_submit_params)
if @submission.already_exists?
show_error
else
@submission.save
show_submitted
end
end
get '/:hackathon.zip' do
if @submissions = Submission.by_hackathon(get_hackathon)
create_zip_folder(@submissions)
set_response_headers
download_zip_folder
end
end
get '/:hackathon' do show_editor(DEFAULT_BRANDING) end
get '/:hackathon/:branding' do show_editor(params[:branding]) end
private
def show_default_page
erb :default_page
end
def show_error
erb :error
end
def show_submitted
erb :submitted
end
def show_editor(custom_branding)
@body_class = ['editor', custom_branding].join(' ')
erb :editor
end
def create_tempfile
@create_tempfile ||= Tempfile.new(get_hackathon)
end
def get_submit_params
get_submit_params = params[:submission] || {}
get_submit_params.merge('seconds' => seconds_from(params[:submission][:seconds]))
end
def get_hackathon
params[:hackathon].to_s.downcase
end
def seconds_from(time_to_compare)
(Time.now - Time.parse(time_to_compare)).to_i
end
def create_zip_folder(array = [])
Zippy.create(create_tempfile.path) do |zip|
if block_given?
yield(zip)
else
array.to_a.each do |entry|
zip[entry.filename] = entry.html
end
end
end
end
def download_zip_folder
File.read(create_tempfile.path)
end
def set_response_headers
response.headers['Pragma'] = 'public'
response.headers['Expires'] = '0'
response.headers['Cache-Control'] = 'must-revalidate, post-check=0, pre-check=0'
response.headers['Cache-Control'] = 'public'
response.headers['Content-Type'] = 'application/octet-stream'
response.headers['Content-Disposition'] = 'attachment; filename="' + get_hackathon + '.zip"'
response.headers['Content-Transfer-Encoding'] = 'binary'
response.headers['Content-Length'] = create_tempfile.size
end
end