-
Notifications
You must be signed in to change notification settings - Fork 1
/
is_it_a_haiku_app.rb
113 lines (96 loc) · 2.46 KB
/
is_it_a_haiku_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
class IsItAHaikuApp < Sinatra::Application
require "./lib/haiku"
require "haml"
require "sass"
require "rack-flash"
require 'json'
enable :sessions
use Rack::Flash
@@haikus = $mongo.collection("haikus")
configure :production do
require "exceptional"
require "json"
set :raise_errors, false
Exceptional.configure ENV['EXCEPTIONAL_API_KEY']
Exceptional::Remote.startup_announce(::Exceptional::ApplicationEnvironment.to_hash('sinatra'))
error do
Exceptional::Catcher.handle_with_rack(request.env['sinatra.error'],request.env, request)
end
end
get '/' do
@random_haiku = random_haiku
haml :index
end
post '/' do
text = params[:haiku]
is_it_a_haiku = Haiku.haiku?(text)
id = @@haikus.save(:text => text, :haiku => is_it_a_haiku, :timestamp => Time.now, :ip => request.ip)
redirect "/haikus/#{id}"
end
get '/haikus/:id' do
object_id = begin
BSON::ObjectId.from_string(params[:id])
rescue BSON::InvalidObjectId
pass
end
if @haiku = @@haikus.find_one(object_id)
haml :haiku
else
pass
end
end
get "/raise" do
raise "Uh-oh!"
end
get "/ip" do
"#{request.ip}"
end
# redirect to a random haiku
get '/haikus' do
haiku = random_haiku
if haiku['_id']
flash[:show_random_link] = true
redirect "/haikus/#{random_haiku['_id']}"
else
redirect "/"
end
end
get '/haikus/random.json' do
content_type :json
haiku = random_haiku
{:text => haiku['text']}.to_json
end
get '/stylesheet.css' do
content_type 'text/css', :charset => 'utf-8'
sass :stylesheet
end
get "/broken" do
@haikus = @@haikus.find(:haiku => false, :dismissed => {"$ne" => true}).limit(10)
haml :broken
end
post "/dismiss/:id" do
raise "not implemented (FIXME)"
object_id = begin
BSON::ObjectId.from_string(params[:id])
rescue BSON::InvalidObjectId
pass
end
if @haiku = @@haikus.find_one(object_id)
@haiku[:dismissed] = true
@@haikus.save(@haiku)
end
""
end
helpers do
def random_haiku
random_haiku = begin
count = @@haikus.find(:haiku => true).count()
if count > 0
@@haikus.find(:haiku => true).limit(-1).skip(rand(count)).first()
else
{'text' => "This is the first line\nand this is the second line\nand this is the third"}
end
end
end
end
end