Module: Slimer::WebRouter

Included in:
WebApplication
Defined in:
lib/slimer/web/router.rb

Overview

A simple Rack router. Borrowed from Sidekiq:

https://github.com/mperham/sidekiq/blob/master/lib/sidekiq/web/router.rb

Constant Summary collapse

GET =
"GET"
DELETE =
"DELETE"
POST =
"POST"
PUT =
"PUT"
PATCH =
"PATCH"
HEAD =
"HEAD"
ROUTE_PARAMS =
"rack.route_params"
REQUEST_METHOD =
"REQUEST_METHOD"
PATH_INFO =
"PATH_INFO"

Instance Method Summary collapse

Instance Method Details

#delete(path, &block) ⇒ Object



37
38
39
# File 'lib/slimer/web/router.rb', line 37

def delete(path, &block)
  route(DELETE, path, &block)
end

#get(path, &block) ⇒ Object



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

def get(path, &block)
  route(GET, path, &block)
end

#match(env) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/slimer/web/router.rb', line 48

def match(env)
  request_method = env[REQUEST_METHOD]
  path_info = ::Rack::Utils.unescape env[PATH_INFO]

  # There are servers which send an empty string when requesting the root.
  # These servers should be ashamed of themselves.
  path_info = "/" if path_info == ""

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

    env[ROUTE_PARAMS] = params

    return WebAction.new(env, route.block)
  end

  nil
end

#patch(path, &block) ⇒ Object



33
34
35
# File 'lib/slimer/web/router.rb', line 33

def patch(path, &block)
  route(PATCH, path, &block)
end

#post(path, &block) ⇒ Object



25
26
27
# File 'lib/slimer/web/router.rb', line 25

def post(path, &block)
  route(POST, path, &block)
end

#put(path, &block) ⇒ Object



29
30
31
# File 'lib/slimer/web/router.rb', line 29

def put(path, &block)
  route(PUT, path, &block)
end

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



41
42
43
44
45
46
# File 'lib/slimer/web/router.rb', line 41

def route(method, path, &block)
  @routes ||= { GET => [], POST => [], PUT => [], PATCH => [], DELETE => [], HEAD => [] }

  @routes[method] << WebRoute.new(method, path, block)
  @routes[HEAD] << WebRoute.new(method, path, block) if method == GET
end