-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.rb
77 lines (66 loc) · 1.79 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
require "rubygems"
require "sinatra"
require "mongoid"
require "json"
set :static, true
set :public, File.dirname(__FILE__) + "/app"
db_host = ENV["DBHOST"] || "localhost"
db_port = ENV["DBPORT"] || "27017"
db_name = ENV["DBNAME"] || "firestarter"
Mongoid.database = Mongo::Connection.new(db_host, db_port).db(db_name)
class GenericModel
include Mongoid::Document
include Mongoid::Timestamps
before_create :set_id
def set_id
last = GenericModel.last
next_id = (last.nil? ? 0 : last.id) + 1
self.id = next_id
end
def build_json
hash = {}
self.attributes.each { |k, v| hash[k] = v }
hash[:id] = self.id
hash
end
end
def find_model(klass, id)
GenericModel.where(:_klass => klass, :_id => id.to_i).first
end
before do
content_type :json
expires -1, :public, :must_revalidate
end
# returns any HTML page in /app
get "/app/:filename" do |filename|
content_type :html
send_file File.join(settings.public, "#{filename}.html")
end
# returns a list of all models of the given klass
get "/:klass" do |klass|
GenericModel.where(:_klass => klass).all.map(&:build_json).to_json
end
# returns a single model of the given klass
get "/:klass/:id" do |klass, id|
find_model(klass, id).build_json.to_json
end
# adds a single model
post "/:klass" do |klass|
model_params = JSON.parse(params[:model])
model_params[:_klass] = klass
GenericModel.create(model_params).build_json.to_json
end
# updates a single model
put "/:klass/:id" do |klass, id|
current_model = find_model(klass, id)
model_params = JSON.parse(params[:model])
model_params[:_klass] = klass
current_model.update_attributes(model_params)
current_model.build_json.to_json
end
# deletes a single model
delete "/:klass/:id" do |klass, id|
model = find_model(klass, id)
model.delete
true.to_json
end