-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.rb
73 lines (59 loc) · 1.46 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
require "rubygems"
require "bundler/setup"
require "sinatra"
require "data_mapper"
require "net/http"
DataMapper::setup(:default, ENV['DATABASE_URL'] || 'postgres://localhost/printer-mail')
class Printer
include DataMapper::Resource
property :id, Serial
property :url, Text
property :nickname, String
has n, :messages
end
class Message
include DataMapper::Resource
property :id, Serial
property :from, String
property :sent_at, DateTime
property :body, Text
belongs_to :printer
end
# Perform basic sanity checks and initialize all relationships
# Call this when you've defined all your models
DataMapper.finalize
# automatically create the post table
Printer.auto_upgrade!
Message.auto_upgrade!
helpers do
def send_message(printer, message_attributes)
message = printer.messages.create!(message_attributes)
printer_url = URI.parse(printer.url)
message_url = url("/messages/#{message.id}")
Net::HTTP.post_form(printer_url, url: message_url)
message
end
end
get "/" do
erb :index
end
get "/register" do
p url("/messages")
erb :register
end
post "/register" do
@printer = Printer.create!(params[:printer])
erb :registered
end
get "/send/:nickname" do
erb :send
end
post "/send/:nickname" do
printer = Printer.first(nickname: params[:nickname])
@message = send_message(printer, params[:message].merge(sent_at: Time.now))
erb :sent
end
get "/messages/:id" do
@message = Message.first(id: params[:id])
erb :message
end