This repository has been archived by the owner on Oct 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.rb
119 lines (100 loc) · 2.53 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
require 'sinatra'
require 'sass'
require 'pp'
require 'code'
require 'mongo'
configure :development do
connection = Mongo::Connection.from_uri 'mongodb://localhost'
db = connection.db('explainruby')
ExplainRuby::Code.mongo = db.collection('results')
end
require 'mustache/sinatra'
set :mustache, { :templates => './templates', :views => './views' }
require 'rocco_ext'
helpers do
def email_link(email)
"<a href='mailto:#{email}'>#{email}</a>"
end
def link_to(text, path)
"<a href='#{path}'>#{text}</a>"
end
def redirect_to(code)
redirect "/#{code.slug}"
end
def image_tag(file, attributes = {})
attributes = attributes.merge(:src => "/images/#{file}")
attributes[:alt] ||= ''
"<img#{html_attributes(attributes)}>"
end
def html_attributes(hash)
hash.map { |key, value|
case value
when NilClass, FalseClass
''
when TrueClass
" #{key}"
else
" #{key}='#{value}'"
end
}.join('')
end
def rocco(options = {}, &block)
options = settings.rocco.merge(options)
Rocco.new(default_title, [], options, &block).to_html
rescue Racc::ParseError
status 500
@message = "There was a parse error when trying to process Ruby code"
mustache :error
end
def default_title
"Explain Ruby"
end
def sass_with_caching(name)
time = ::File.mtime ::File.join(settings.views, "#{name}.sass")
expires 500, :public, :must_revalidate if settings.environment == :production
last_modified time
content_type 'text/css'
sass name
end
end
get '/' do
mustache :home
end
get '/url/*:url' do
code = ExplainRuby::Code.from_url params[:url]
redirect_to code
end
post '/' do
if not params[:url].empty?
code = ExplainRuby::Code.from_url params[:url]
redirect_to code
elsif not params[:code].empty?
code = ExplainRuby::Code.create params[:code]
redirect_to code
else
status "400 Not Chunky"
@message = "Please paste some code or enter a URL"
mustache :error
end
end
get '/f/:name' do
code = ExplainRuby::Code.from_test_fixture(params[:name])
rocco(:url => code.url) { code.to_s }
end
get '/f/:name/sexp' do
content_type 'text/plain'
code = ExplainRuby::Code.from_test_fixture(params[:name])
code.pretty_inspect
end
get '/explain.css' do
sass_with_caching :explain
end
get '/docco.css' do
sass_with_caching :docco
end
get %r!^/([a-z0-9]{3,})$! do
code = ExplainRuby::Code.find params[:captures][0]
halt 404 unless code
etag code.md5
rocco(:url => code.url) { code.to_s }
end