Class: Router

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

Overview

Router class for pairing incoming requests with routes

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



5
6
7
# File 'lib/route.rb', line 5

def initialize()
    @routes = []
end

Instance Attribute Details

#routesObject (readonly)

Returns the value of attribute routes.



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

def routes
  @routes
end

Instance Method Details

#add_route(method, input, &block) ⇒ Object

Method for adding a route to the router. Incoming requests will be checked against these routes to see if the incoming requests has a valid target.

Parameters:

  • method (String)

    A string with the method for the request

  • input (String)

    A string for the input to match the request with

  • &block (Block)

    The block to execute and respond with if the route is matched.



14
15
16
17
18
# File 'lib/route.rb', line 14

def add_route(method, input, &block)
    routeHash = {method: method, resource: input, block: block}
    @routes << routeHash
    p "added successfully, @routes are: #{@routes}"
end

#match_route(request) ⇒ Array

Method for matching the incoming requests with the expected routes. Returns a touple with either the matched object and an int 200 representing status or the request and an int 404 representing status

Parameters:

  • request (Request)

    the Request class to find a match for

Returns:

  • (Array)

    the array consisting of the matched method or the request and the status of the match.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/route.rb', line 24

def match_route(request)

    match = @routes.find {|route| (route[:method] == request.method) && (request.resource.match?(route[:resource]))}

    if match != nil
        print("\nMatch: ", match, "\n")
        returner = [match, 200]
        return returner
    else
        if request.resource.match?(@routes[0][:resource]) != true #If the requested resource did not match the expected resource for that method
            p "failed to find: #{request.resource} resource.\nExpected: #{String(@routes[0][:resource])} resource"
        elsif @routes[0][:method] != request.method #If the current method did not match the expected method for that resource
            p "failed to find #{request.method} method.\nExpected: #{@routes[0][:method]} method"
        else
            p "Failed to match, got no reason, just kinda didn't feel like it"
        end
        returner = [request, 404]
        return returner
    end
end