Module: DeprecationCollector::Web::Router

Included in:
Application
Defined in:
lib/deprecation_collector/web/router.rb

Overview

:nodoc:

Defined Under Namespace

Classes: ActionContext, Route

Constant Summary collapse

HTTP_METHODS =
%w[GET HEAD POST PUT PATCH DELETE].freeze
ROUTE_PARAMS =
"rack.route_params"
PATH_INFO =
"PATH_INFO"

Instance Method Summary collapse

Instance Method Details

#call(env, application = nil) ⇒ Object



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
# File 'lib/deprecation_collector/web/router.rb', line 51

def call(env, application = nil)
  action = match(env)
  unless action
    return [
      404,
      { "content-type" => "text/plain", "x-cascade" => "pass" },
      ["Not Found #{env['REQUEST_METHOD'].inspect} #{env[PATH_INFO].inspect}"]
    ]
  end

  resp = catch(:halt) { action.call(env, application) }

  return resp if resp.is_a?(Array) # raw rack responses (redirects etc.)

  # rendered content goes here
  headers = {
    "content-type" => "text/html",
    "cache-control" => "private, no-store"
    # TODO: locale/csp
    # "content-language" => action.locale,
    # "content-security-policy" => CSP_HEADER
  }
  # we'll let Rack calculate Content-Length for us.
  [200, headers, [resp]]
end

#helpers(mod = nil, &block) ⇒ Object



25
26
27
28
29
# File 'lib/deprecation_collector/web/router.rb', line 25

def helpers(mod = nil, &block)
  return ActionContext.class_eval(&block) if block

  ActionContext.send(:include, mod)
end

#match(env) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/deprecation_collector/web/router.rb', line 34

def match(env)
  request = ::Rack::Request.new(env)
  request_method = request.request_method
  request_method = request.params["_method"] if request.params["_method"]

  path_info = ::Rack::Utils.unescape env[PATH_INFO]
  path_info = "/" if path_info == "" # some buggy servers may pass empty root path

  @routes[request_method.upcase]&.find do |route|
    params = route.match(request_method.upcase, path_info)
    next unless params

    env[ROUTE_PARAMS] = params
    break ActionContext.new(request, &route.block)
  end
end

#root(&block) ⇒ Object



17
18
19
# File 'lib/deprecation_collector/web/router.rb', line 17

def root(&block)
  route(GET, "/", &block)
end

#route(method, path, &block) ⇒ Object



21
22
23
# File 'lib/deprecation_collector/web/router.rb', line 21

def route(method, path, &block)
  ((@routes ||= {})[method] ||= []) << Route.new(method, path, block)
end