-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.rb
More file actions
38 lines (29 loc) · 1.06 KB
/
app.rb
File metadata and controls
38 lines (29 loc) · 1.06 KB
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
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'json'
DB = Mongo::Connection.new.db("mydb", :pool_size => 5, :timeout => 5)
get '/' do
haml :index, :attr_wrapper => '"', :locals => {:title => 'haii'}
end
get '/todo' do
haml :todo, :attr_wrapper => '"', :locals => {:title => 'MongoDB Backed TODO App'}
end
get '/api/:thing' do
DB.collection(params[:thing]).find.to_a.map{|t| from_bson_id(t)}.to_json
end
get '/api/:thing/:id' do
from_bson_id(DB.collection(params[:thing]).find_one(to_bson_id(params[:id]))).to_json
end
post '/api/:thing' do
oid = DB.collection(params[:thing]).insert(JSON.parse(request.body.read.to_s))
"{\"_id\": \"#{oid.to_s}\"}"
end
delete '/api/:thing/:id' do
DB.collection(params[:thing]).remove('_id' => to_bson_id(params[:id]))
end
put '/api/:thing/:id' do
DB.collection(params[:thing]).update({'_id' => to_bson_id(params[:id])}, {'$set' => JSON.parse(request.body.read.to_s).reject{|k,v| k == '_id'}})
end
def to_bson_id(id) BSON::ObjectId.from_string(id) end
def from_bson_id(obj) obj.merge({'_id' => obj['_id'].to_s}) end