Class: Lennarb::RequestHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/lennarb/request_handler.rb

Overview

Handles requests and executes routes with helpers and hooks.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ RequestHandler

Initialize the request handler

Parameters:



10
11
12
# File 'lib/lennarb/request_handler.rb', line 10

def initialize(app)
  @app = app
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



5
6
7
# File 'lib/lennarb/request_handler.rb', line 5

def app
  @app
end

Instance Method Details

#call(env) ⇒ Array

Handle a request according to Rack interface

Parameters:

  • env (Hash)

    The Rack environment

Returns:

  • (Array)

    Rack response [status, headers, body]



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
# File 'lib/lennarb/request_handler.rb', line 18

def call(env)
  http_method = env[Rack::REQUEST_METHOD].to_sym
  parts = split_path(env[Rack::PATH_INFO])
  block, params = app.routes.match_route(parts, http_method)

  return [404, {"content-type" => CONTENT_TYPE[:TEXT]}, ["Not Found"]] unless block

  req = Request.new(env, params || {})
  res = Response.new

  catch(:halt) do
    context = create_context

    Hooks.execute(context, app.class, :before, req, res)

    context.instance_exec(req, res, params, &block)

    Hooks.execute(context, app.class, :after, req, res)

    res.finish
  rescue => e
    # In development, let the exception through so Rack::ShowExceptions --
    # already in App#default_middleware_stack -- can render the backtrace.
    raise if app.env.development?

    app.class.config.logger.error("Error: #{e.message}")
    app.class.config.logger.error(e.backtrace.first)
    [500, {"content-type" => CONTENT_TYPE[:TEXT]}, ["Internal Server Error"]]
  end
end