Class: Puffs::Router

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

Overview

The Puffs Router.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



6
7
8
# File 'lib/router.rb', line 6

def initialize
  @routes = []
end

Instance Attribute Details

#routesObject (readonly)

Returns the value of attribute routes.



4
5
6
# File 'lib/router.rb', line 4

def routes
  @routes
end

Instance Method Details

#add_route(pattern, method, controller_class, action_name) ⇒ Object

Adds a new route to the list of routes



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

def add_route(pattern, method, controller_class, action_name)
  routes << Route.new(pattern, method, controller_class, action_name)
end

#draw(&proc) ⇒ Object

evaluate the proc in the context of the instance for syntactic sugar :)



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

def draw(&proc)
  instance_eval(&proc)
end

#match(req) ⇒ Object

should return the route that matches this request



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

def match(req)
  routes.each do |route|
    return route if route.matches?(req)
  end
  nil
end

#run(req, res) ⇒ Object

either throw 404 or call run on a matched route



38
39
40
41
42
43
44
45
46
# File 'lib/router.rb', line 38

def run(req, res)
  route = match(req)
  if route
    route.run(req, res)
  else
    res.status = 404
    res.body = ["Sorry, Charlie. That page doesn't exist."]
  end
end