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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# app_kit.rb — a pure-Ruby, Sinatra-style web-app DSL for rubylang.
#
# This is the ergonomic layer that sits directly on top of rack.rb: instead of
# hand-writing `[status, headers, body]` triples you subclass AppKit::Base and
# declare routes with a block DSL:
#
# class App < AppKit::Base
# get "/hello/:name" do
# "Hello, #{params[:name]}!"
# end
# end
#
# The class itself is a Rack app — `App.call(env)` returns a Rack triple, so it
# plugs straight into Rack::Builder / Rack::Handler, and `App.run!(9292)` boots
# the shipped raw-TCP handler.
#
# --- How this maps onto rubylang's object model -----------------------------
#
# Sinatra runs each route block in a fresh per-request *instance* (via
# instance_exec / a generated instance method) so that `params`, `request`, etc.
# resolve as instance methods. rubylang does not rebind `self` for blocks:
# neither `instance_exec`, `instance_eval`, nor `define_method` change what
# `self` a block sees (verified — a block keeps the `self` of its defining
# scope). Inside `get "/x" do ... end` written in the class body, that `self` is
# the subclass itself, and bare calls like `params` resolve to *class* methods.
#
# So AppKit is built the way that model actually allows: the request helpers
# (`params`, `request`, `response`, `status`, `headers`, `content_type`,
# `redirect`, `halt`, `erb`) are class methods on AppKit::Base, and the
# per-request state lives in class-level ivars set at the top of `call`. This is
# effectively Sinatra's "classic" single-namespace style. Dispatch is
# synchronous and one-request-at-a-time (matching Rack::Handler::Simple), so a
# single current-request slot is correct here.
#
# require_relative pulls in the Rack layer this builds on.
# AppKit::Base — subclass it, declare routes, get a Rack app.
#
# Everything is a class method because a route block's `self` is the subclass
# (see the file header). Subclasses inherit these; per-request state is stored
# in ivars on the subclass during `call`.
# ---- Route + hook registration (class-def time) ------------------------
# The ordered list of [method, pattern, block] route entries.
@routes ||= []
end
@before_hooks ||= []
end
@after_hooks ||= []
end
# Configuration bag (Sinatra's `set`). `:views` is the ERB template dir.
@settings ||= { => }
end
# `set :views, "path"` — store a config value. Accepts symbol or string keys
# (stored stringified for indifferent lookup).
settings[key.to_s] = value
value
end
settings[]
end
# The route DSL. `get "/users/:id" do ... end`. A `:segment` in the pattern
# is a named parameter available as `params[:segment]`.
route(, pattern, &block)
end
route(, pattern, &block)
end
route(, pattern, &block)
end
route(, pattern, &block)
end
route(, pattern, &block)
end
routes << [method, pattern, block]
end
# `before { ... }` / `after { ... }` — filters run around every request.
before_hooks << block
end
after_hooks << block
end
# `not_found { ... }` — handler invoked when no route matches. Its block runs
# like a route block (status is forced to 404 first).
@not_found_hook = block
end
@not_found_hook
end
# ---- Per-request helpers (called with implicit self inside route blocks) --
# The merged, indifferent-access params hash: query string + form body
# (from Rack::Request) overlaid with named route segments. Both string and
# symbol keys are present, so `params[:id]` and `params["id"]` both work.
@params
end
# The Rack::Request for this request.
@request
end
# The Rack::Response accumulating status/headers/body for this request.
@response
end
# `status` reads the current code; `status 201` sets it.
return @response.status if code.nil?
@response.status = code
end
# `headers` returns the mutable header hash; `headers "X" => "Y"` merges in.
hash.each { @response.headers[k] = v } unless hash.nil?
@response.headers
end
# Set the Content-Type. A symbol is looked up in MIME_TYPES; a string is
# used verbatim.
value = type.is_a?(Symbol) ? (MIME_TYPES[type] || ) : type.to_s
@response.headers[] = value
value
end
= {
:html => ,
:text => ,
:txt => ,
:json => ,
:xml => ,
:css => ,
:js => ,
}
# Redirect to `url` (default 302). Ends the request immediately via halt.
@response.headers[] = url
@response.status = code
throw(:halt, [code, @response.headers, []])
end
# Abort the request with an explicit response. Sinatra-style overloads:
# halt -> current status, empty body
# halt 404 -> status 404, empty body
# halt "gone" -> current status, body "gone"
# halt 404, "missing" -> status 404, body "missing"
code = @response.status
body =
if args.length == 1
arg = args[0]
arg.is_a?(Integer) ? (code = arg) : (body = arg.to_s)
elsif args.length >= 2
code = args[0]
body = args[1].to_s
end
@response.status = code
throw(:halt, [code, @response.headers, [body]])
end
# Render an ERB template.
# erb :show -> views/show.erb
# erb :show, locals: { id: 1 } -> with locals exposed as bare names
# erb "<%= 1 + 1 %>" -> inline (a String is the template source)
# erb "<%= x %>", :inline, locals: {x: 5} -> the :inline marker is accepted
#
# A String template renders inline; a Symbol reads views/<name>.erb. If a
# layout template resolves (views/layout.erb, or :layout option), the page is
# wrapped in it with `<%= yield %>` replaced by the rendered page. Pass
# `layout: false` to skip.
#
# NOTE: rubylang's ERB does not expose `@ivars` through `binding` (verified —
# `ERB#result(binding)` renders ivars as empty), so templates read values as
# bare locals supplied via `locals:` (a first-class Sinatra option), e.g.
# `<%= title %>` with `erb :page, locals: { title: "Home" }`.
opts = rest.last.is_a?(Hash) ? rest.last : {}
locals = symbolize(opts[] || opts[:locals] || {})
source = template.is_a?(String) ? template : read_template(template)
# trim mode "-" (Sinatra's default): a `-%>` chomps the trailing newline so
# `<% ... -%>` control lines don't emit blank lines.
inner = ERB.new(source, trim_mode: ).result_with_hash(locals)
layout_name = if opts.key?(:layout)
opts[:layout]
elsif opts.key?()
opts[]
else
:layout
end
return inner if layout_name == false
layout_path = template_path(layout_name)
return inner unless File.exist?(layout_path)
layout_src = File.read(layout_path).gsub(, )
wrap_locals = locals.merge({ :_appkit_yield => inner })
ERB.new(layout_src, trim_mode: ).result_with_hash(wrap_locals)
end
# ---- Rack app contract -------------------------------------------------
# AppKit::Base.call(env) — the Rack entry point. Returns [status, headers,
# body]. Sets up per-request state, runs before-filters, dispatches to the
# first matching route (or the not_found handler), then runs after-filters.
# `redirect`/`halt` short-circuit via `throw :halt`.
reset_request(env)
result = catch(:halt) do
run_hooks(before_hooks)
block, route_params = match_route(env)
if block
merge_params(route_params)
finalize(block.call)
else
finalize_not_found
end
end
# After-filters run for every request, including halted ones (Sinatra
# semantics). They may still mutate the shared response header hash, which
# is the same object referenced by `result`.
run_hooks(after_hooks)
result
end
# AppKit::Base.run!(port) — serve this app over real HTTP via the Rack
# handler. Blocks forever (the handler loops on accept).
Rack::Handler::Simple.run(self, port, host)
end
# ---- Internals ---------------------------------------------------------
@request = Rack::Request.new(env)
@response = Rack::Response.new
@params = {}
# Seed with query/form params from Rack::Request (string keys), adding a
# symbol alias for each so both access forms work.
@request.params.each do
@params[k] = v
@params[k.to_sym] = v
end
end
route_params.each do
@params[k] = v
@params[k.to_sym] = v
end
end
# Find the first route whose method + segment pattern matches. Returns
# [block, {param => value}] or [nil, {}].
method = env[]
path = env[] ||
request_segments = split_path(path)
routes.each do
next unless route_method == method
pattern_segments = split_path(pattern)
next unless pattern_segments.length == request_segments.length
captured = {}
matched = true
i = 0
while i < pattern_segments.length
pseg = pattern_segments[i]
rseg = request_segments[i]
if pseg.start_with?()
captured[pseg[1..-1]] = rseg
elsif pseg != rseg
matched = false
break
end
i += 1
end
return [block, captured] if matched
end
[nil, {}]
end
# Split a path into non-empty segments. "/a/b" -> ["a", "b"]; "/" -> [].
path.split().reject { s.empty? }
end
hooks.each { hook.call }
end
# Turn a route block's return value into a Rack triple, honoring anything the
# block set on @response (status, headers, content-type).
# String -> body, default Content-Type text/html
# Hash / Array (+json content-type) -> JSON.generate
# full Rack triple -> passed through
# nil -> empty body
# A block may return an explicit Rack triple; pass it through untouched.
if result.is_a?(Array) && result.length == 3 &&
result[0].is_a?(Integer) && result[1].is_a?(Hash)
return result
end
ctype = @response.headers[]
body =
if result.is_a?(String)
result
elsif (result.is_a?(Hash) || result.is_a?(Array)) &&
ctype ==
JSON.generate(result)
elsif result.nil?
else
result.to_s
end
@response.headers[] = if @response.headers[].nil?
[@response.status, @response.headers, [body]]
end
@response.status = 404
if not_found_hook
finalize(not_found_hook.call)
else
@response.headers[] = if @response.headers[].nil?
[404, @response.headers, []]
end
end
File.join(views_dir, )
end
path = template_path(name)
raise unless File.exist?(path)
File.read(path)
end
# Return a new hash with all keys converted to symbols (result_with_hash
# exposes each key as a bare local variable in the template).
out = {}
hash.each { out[k.to_sym] = v }
out
end
end
end