-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwatts.rb
354 lines (314 loc) · 9.82 KB
/
watts.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
%w(
forwardable
rack
set
watts/monkey_patching
).each &method(:require)
# Here's the main module, Watts.
module Watts
# You are unlikely to need to interact with this. It's mainly for covering
# up the path-matching logic for Resources.
class Path
extend Forwardable
include Enumerable
attr_accessor :resource
attr_new Hash, :sub_paths
def match path, args
if path.empty?
[resource, args] if resource
elsif(sub = self[path[0]])
sub.match(path[1..-1], args)
else
each { |k,sub|
if k.kind_of?(Regexp) && k.match(path[0])
return sub.match(path[1..-1], args + [path[0]])
end
}
each { |k,sub|
if k.kind_of?(Symbol)
return sub.match(path[1..-1], args + [path[0]])
end
}
nil
end
end
def rmatch res, args, acc = []
return "/#{acc.join('/')}" if args.empty? && resource == res
rest = args[1..-1] || []
accnext = acc.dup << args[0]
each { |k,sub|
if k.kind_of?(String)
t = sub.rmatch res, args, acc + [k]
return t if t
elsif k.kind_of?(Regexp) && k.match(args[0])
t = sub.rmatch res, rest, accnext
return t if t
elsif k.kind_of?(Symbol)
t = sub.rmatch res, rest, accnext
return t if t
end
}
nil
end
def_delegators :sub_paths, :'[]', :'[]=', :each
end
# In order to have a Watts app, you'll want to subclass Watts::App. For a
# good time, you'll also probably want to provide some resources to that
# class using the resource method, which maps paths to resources.
class App
Errors = {
400 =>
[400, {'Content-Type' => 'text/plain'}, ["400 Bad Request.\n"]],
404 =>
[404, {'Content-Type' => 'text/plain'}, ["404 Not Found\n"]],
501 =>
[501, {'Content-Type' => 'text/plain'},
["501 Not Implemented.\n"]],
}
# The "empty" set.
ESet = Set.new(['/', ''])
# Method name cache. Maps HTTP methods to object methods.
MNCache = Hash.new { |h,k|
h[k] = k.downcase.to_sym
}
# Prefill MNCache above with the likely culprits:
%w(
GET PUT POST DELETE OPTIONS HEAD TRACE CONNECT PATCH
).each &MNCache.method(:'[]')
class << self
attr_new Hash, :http_methods
attr_new Watts::Path, :path_map
attr_new Array, :path_stack
attr_writer :path_stack
end
def self.decypher_path p
return p if p.kind_of?(Array)
return [] if ESet.include?(p)
return [p] if p.kind_of?(Regexp) || p.kind_of?(Symbol)
p.split('/').tap { |a| a.reject! { |c| '' == c } } #(&''.method(:'==')) }
end
to_instance :path_map, :decypher_path, :path_to
# If you want your Watts application to do anything at all, you're very
# likely to want to call this method at least once. The basic purpose
# of the method is to tell your app how to match a resource to a path.
# For example, if you create a resource (see Watts::Resource) Foo, and
# you want requests against '/foo' to match it, you could do this:
# resource('foo', Foo)
#
# The first argument is the path, and the second is the resource that
# path is to match. (Please see the README for more detailed
# documentation of path-matching.) You may also pass it a block, in
# which resources that are defined are 'namespaced'. For example, if
# you also had a resource called Bar and wanted its path to be a
# sub-path of the Foo resource's (e.g., '/foo/bar'), then typing these
# lines is a pretty good plan:
# resource('foo', Foo) {
# resource('bar', Bar)
# }
#
# Lastly, the resource argument itself is optional, for when you want a
# set of resources to be namespaced under a given path, but don't
# have a resource in mind. For example, if you suddenly needed your
# entire application to reside under '/api', you could do this:
# resource('api') {
# resource('foo', Foo) {
# resource('bar', Bar)
# resource('baz', Baz)
# }
# }
#
# This is probably the most important method in Watts. Have a look at
# the README and the example applications under doc/examples if you
# want to understand the pattern-matching, arguments to resources, etc.
def self.resource(path, res = nil, &b)
path = decypher_path(path)
last = (path_stack + path).inject(path_map) { |m,p|
m[p] ||= Path.new
}
last.resource = res
if b
old_stack = path_stack
self.path_stack = old_stack + path
b.call
self.path_stack = old_stack
end
res
end
# And because res(...) is a little less distracting than resource(...):
class << self; alias_method :res, :resource; end
# Given a resource (and, optionally, arguments if the path requires
# them), this method returns an absolute path to the resource.
def self.path_to res, *args
path_map.rmatch res, args
end
# Given a path, returns the matching resource, if any.
def match req_path
req_path = decypher_path req_path
path_map.match req_path, []
end
# Our interaction with Rack.
def call env, req_path = nil
rm = MNCache[env['REQUEST_METHOD']]
return(Errors[501]) unless Resource::HTTPMethods.include?(rm)
req_path ||= decypher_path env['PATH_INFO']
resource_class, args = path_map.match req_path, []
return Errors[404] unless resource_class
res = resource_class.new env, self
res.send(rm, *args)
end
end
# HTTP is all about resources, and this class represents them. You'll want
# to subclass it and then define some HTTP methods on it, then use
# your application's resource method to tell it where to find these
# resources. (See Watts::App.resource().) If you want your resource to
# respond to GET with a cheery, text/plain greeting, for example:
# class Foo < Watts::Resource
# get { || "Hello, world!" }
# end
#
# Or you could do something odd like this:
# class RTime < Watts::Resource
# class << self; attr_accessor :last_post_time; end
#
# get { || "The last POST was #{last_post_time}." }
# post { ||
# self.class.last_post_time = Time.now.strftime('%F %R')
# [204, {}, []]
# }
#
# def last_post_time
# self.class.last_post_time || "...never"
# end
# end
#
# It is also possible to define methods in the usual way (e.g., 'def get
# ...'), although you'll need to add them to the list of allowed methods
# (for OPTIONS) manually. Have a look at the README and doc/examples.
class Resource
HTTPMethods =
Set.new(%i(get post put delete head options trace connect))
class << self; attr_accessor :http_methods; end
def self.inherited base
base.http_methods = (http_methods || []).dup
end
# For each method allowed by HTTP, we define a "Method not allowed"
# response, and a method for generating a method. You may also just
# def methods, as seen below for the options method.
HTTPMethods.each { |http_method|
define_singleton_method(http_method) { |&b|
(http_methods << http_method.to_s.upcase).uniq!
bmname = :"__#{http_method}"
define_method(bmname, &b)
define_method(http_method) { |*args|
begin
resp = send bmname, *args
rescue ArgumentError => e
# TODO: Arity/path args mismatch handler here.
# ...Maybe. It seems appropriate, but I've never
# needed it.
raise e
end
# TODO: Problems.
case resp
when nil
response
when Array, Rack::Response
resp
else
resp = resp.to_s
[
200,
{'Content-Type' => 'text/plain',
'Content-Length' => resp.bytesize.to_s,
},
[resp]
]
end
}
}
define_method(http_method) { |*args| default_http_method(*args) }
}
# This method is for creating Resources that simply wrap first-class
# HTML views. It was created with Hoshi in mind, although you can use
# any class that can be instantiated and render some HTML when the
# specified method is called. It takes two arguments: the view class,
# and the method to call to render the HTML.
def self.for_html_view klass, method
c = Class.new HTMLViewResource
c.view_class = klass
c.view_method = method
c
end
# This method generates a HEAD that just calls #get and only passes
# back the headers. It's sub-optimal when GET is expensive, so it is
# disabled by default.
def self.auto_head
head { |*a|
status, headers, = get(*a)
[status, headers, []]
}
end
to_instance :http_methods
attr_new Rack::Response, :response
attr_accessor :env, :app
# Every resource, on being instantiated, is given the Rack env.
def initialize(env, app = nil)
@env, @app = env, app
end
# The default options method, to comply with RFC 2616, returns a list
# of allowed methods in the Allow header. These are filled in when the
# method-defining methods (i.e., get() et al) are called.
def options(*args)
[
200,
{
'Content-Length' => '0', # cf. RFC 2616
'Content-Type' => 'text/plain', # Appease Rack::Lint
'Allow' => http_methods.join(', ')
},
[]
]
end
def request
@request ||= Rack::Request.new(env)
end
# By default, we return "405 Method Not Allowed" and set the Allow:
# header appropriately.
def default_http_method(*args)
s = 'Method not allowed.'
[405,
{ 'Allow' => http_methods.join(', '),
'Content-Type' => 'text/plain',
'Content-Length' => s.bytesize.to_s,
},
['Method not allowed.']]
end
# HEAD responds the same way as the default_method, but does not return
# a body.
def head(*args)
r = default_http_method
r[2] = []
r
end
end
# See the documentation for Watts::Resource.for_html_view().
class HTMLViewResource < Resource
class << self
attr_writer :view_class, :view_method
end
def self.view_class
@view_class ||= (superclass.view_class rescue nil)
end
def self.view_method
@view_method ||= (superclass.view_method rescue nil)
end
to_instance :view_class, :view_method
def get *args
body = view_class.new.send(view_method, *args)
[200,
{'Content-Type' => 'text/html',
'Content-Length' => body.bytesize.to_s},
[body]]
end
end
end