-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnancy.rb
More file actions
98 lines (75 loc) · 1.96 KB
/
nancy.rb
File metadata and controls
98 lines (75 loc) · 1.96 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
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
require "rack"
module Nancy
class Base
def initialize
@routes = {}
end
attr_reader :routes
attr_reader :request
def get(path, &handler)
route("GET", path, &handler)
end
def post(path, &handler)
route("POST", path, &handler)
end
def put(path, &handler)
route("PUT", path, &handler)
end
def patch(path, &handler)
route("PATCH", path, &handler)
end
def delete(path, &handler)
route("DELETE", path, &handler)
end
def head(path, &handler)
route("HEAD", path, &handler)
end
def call(env)
@request = Rack::Request.new(env)
verb = @request.request_method
requested_path = @request.path_info
handler = @routes.fetch(verb, {}).fetch(requested_path, nil)
if handler
result = instance_eval(&handler)
if result.class == String
[200, {}, [result]]
else
result
end
else
[404, {}, ["Oops! No route for #{verb} #{requested_path}"]]
end
end
private
def route(verb, path, &handler)
@routes[verb] ||= {}
@routes[verb][path] = handler
end
def params
request.params
end
end
Application = Base.new
module Delegator
def self.delegate(*methods, to:)
Array(methods).each do |method_name|
define_method(method_name) do |*args, &block|
to.send(method_name, *args, &block)
end
private method_name
end
end
delegate :get, :patch, :put, :post, :delete, :head, to: Application
end
end
include Nancy::Delegator
get "/get-it" do
"Whoa, it works!"
end
get "/hello" do
"Hello World!"
end
post "/" do
request.body.read
end
Rack::Handler::WEBrick.run Nancy::Application, Port: 9292