Class: AgileProxy::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/agile_proxy/router.rb

Overview

A rack router used for selecting a ‘request spec’ from a shortlist

Constant Summary collapse

VERSION =
'0.4.0'
HEAD =
'HEAD'.freeze
GET =
'GET'.freeze
POST =
'POST'.freeze
PUT =
'PUT'.freeze
DELETE =
'DELETE'.freeze
REQUEST_METHOD =
'REQUEST_METHOD'.freeze
PATH_INFO =
'PATH_INFO'.freeze
ROUTE_PARAMS =
'rack.route_params'.freeze
QUERY_STRING =
'QUERY_STRING'.freeze
FORM_HASH =
'rack.request.form_hash'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Router

Returns a new instance of Router.



21
22
23
24
# File 'lib/agile_proxy/router.rb', line 21

def initialize(&block)
  @named_routes = {}
  routes(&block)
end

Instance Method Details

#[](route_name) ⇒ Object



26
27
28
# File 'lib/agile_proxy/router.rb', line 26

def [](route_name)
  @named_routes[route_name]
end

#call(env) ⇒ Object



67
68
69
70
71
72
73
74
# File 'lib/agile_proxy/router.rb', line 67

def call(env)
  app = match(env)
  if app
    app.call(env)
  else
    not_found(env)
  end
end

#delete(route_spec) ⇒ Object



47
48
49
# File 'lib/agile_proxy/router.rb', line 47

def delete(route_spec)
  route(DELETE, route_spec)
end

#get(route_spec) ⇒ Object



35
36
37
# File 'lib/agile_proxy/router.rb', line 35

def get(route_spec)
  route(GET, route_spec)
end

#match(env) ⇒ Object



76
77
78
79
80
81
82
83
84
85
# File 'lib/agile_proxy/router.rb', line 76

def match(env)
  routes.each do |route|
    params = route.match(env)
    if params
      env[ROUTE_PARAMS] = params
      return route.app
    end
  end
  nil
end

#not_found(env) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
# File 'lib/agile_proxy/router.rb', line 87

def not_found(env)
  body = "<h1>Not Found</h1><p>No route matches #{env[REQUEST_METHOD]} #{env[PATH_INFO]}</p>"
  [
    404,
    {
      'Content-Type' => 'text/html',
      'Content-Length' => body.length.to_s
    },
    [body]
  ]
end

#post(route_spec) ⇒ Object



39
40
41
# File 'lib/agile_proxy/router.rb', line 39

def post(route_spec)
  route(POST, route_spec)
end

#put(route_spec) ⇒ Object



43
44
45
# File 'lib/agile_proxy/router.rb', line 43

def put(route_spec)
  route(PUT, route_spec)
end

#route(method, route_spec) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/agile_proxy/router.rb', line 51

def route(method, route_spec)
  route = Route.new(
      method,
      route_spec.first.first,
      route_spec.first.last,
      route_spec.reject { |k, _| k == route_spec.first.first }
  )
  @routes ||= []
  @routes << route
  if route_spec && route_spec[:as]
    # Using ||= so the first route with that name will be returned
    @named_routes[route_spec[:as].to_sym] ||= route_spec.first.first
  end
  route
end

#routes(&block) ⇒ Object



30
31
32
33
# File 'lib/agile_proxy/router.rb', line 30

def routes(&block)
  instance_eval(&block) if block
  @routes
end