require 'debug' # Router class for pairing incoming requests with routes class Router attr_reader :routes def initialize() @routes = [] end # 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. # # @param method [String] A string with the method for the request # @param input [String] A string for the input to match the request with # @param &block [Block] The block to execute and respond with if the route is matched. def add_route(method, input, &block) routeHash = {method: method, resource: input, block: block} @routes << routeHash p "added successfully, @routes are: #{@routes}" end # 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 # # @param request [Request] the Request class to find a match for # @return [Array] the array consisting of the matched method or the request and the status of the match. 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 end