Class: Rack::Router

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

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

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Router

Returns a new instance of Router.



17
18
19
20
# File 'lib/rack/router.rb', line 17

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

Instance Method Details

#[](route_name) ⇒ Object



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

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

#call(env) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/rack/router.rb', line 58

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

#delete(route_spec) ⇒ Object



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

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

#get(route_spec) ⇒ Object



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

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

#match(env) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rack/router.rb', line 66

def match(env)
  request_method = env[REQUEST_METHOD]
  request_method = GET if request_method == HEAD
  routes.each do |route|
    if params = route.match(request_method, env[PATH_INFO])
      env[ROUTE_PARAMS] = params
      return route.app
    end
  end
  nil
end

#not_found(env) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/rack/router.rb', line 78

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



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

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

#put(route_spec) ⇒ Object



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

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

#route(method, route_spec) ⇒ Object



47
48
49
50
51
52
53
54
55
56
# File 'lib/rack/router.rb', line 47

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



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

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