Class: RackStep::Router

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



13
14
15
# File 'lib/router.rb', line 13

def initialize
  @routes = Hash.new
end

Instance Attribute Details

#routesObject

Will store all the possible routes. By default it’s empty and should be populated by the application (RackStep will add a 404 route, the others should be added by the user).



11
12
13
# File 'lib/router.rb', line 11

def routes
  @routes
end

Instance Method Details

#add_route(verb, path, controller, method) ⇒ Object



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

def add_route(verb, path, controller, method)
  route = Route.new(verb, path, controller, method)
  routes[route.id] = route
end

#find_route_for(path, verb) ⇒ Object

Given a request, will parse it’s path to find what it the apropriate controller and mehod/action to respond it.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/router.rb', line 24

def find_route_for(path, verb)
  # Ignoring the first char if path starts with '/'. This way the path of
  # 'http//localhost/' will be the same of 'http://localhost' (both will
  # be empty strings).
  path = path[1..-1] if path[0] == '/'
  # Re-creating the route id (verb + path).
  route_id = verb + path
  # Getting the correspondent route or nil if route is invalid.
  route = routes[route_id]
  # If no route was found, set it to 'notfound' route (maintaining the
  # original verb).
  route = routes["#{verb}notfound"] if route == nil

  return route
end