From b37dd29d4b244721b459ac4d420b9b5a88fdf1f6 Mon Sep 17 00:00:00 2001 From: sdogruyol Date: Wed, 13 Jan 2016 15:22:50 +0200 Subject: [PATCH] Update router to handle method matching --- src/kemal/handler.cr | 3 +-- src/kemal/route.cr | 33 ++++++++++++++++++++++++++++++--- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/kemal/handler.cr b/src/kemal/handler.cr index 4b4e813..c5a8ac4 100644 --- a/src/kemal/handler.cr +++ b/src/kemal/handler.cr @@ -25,8 +25,7 @@ class Kemal::Handler < HTTP::Handler def process_request(request) url = request.path.not_nil! @routes.each do |route| - url.match(route.pattern as Regex) do |url_params| - request.url_params = url_params + if route.match?(request) context = Context.new(request, route) begin body = route.handler.call(context).to_s diff --git a/src/kemal/route.cr b/src/kemal/route.cr index 4a0437d..f8741b4 100644 --- a/src/kemal/route.cr +++ b/src/kemal/route.cr @@ -3,10 +3,37 @@ # what action to be done if the route is matched. class Kemal::Route getter handler - getter pattern + getter method - def initialize(@method, path, &@handler : Kemal::Context -> _) - @pattern = pattern_to_regex path + def initialize(@method, @path, &@handler : Kemal::Context -> _) + end + + def match?(request) + check_for_method_override!(request) + return nil unless request.override_method == @method + return true if request.path.not_nil!.includes?(':') && request.path.not_nil! == @path + request.path.not_nil!.match(pattern_to_regex(@path)) do |url_params| + request.url_params = url_params + return true + end + end + + # Checks if request params contain _method param to override request incoming method + def check_for_method_override!(request) + request.override_method = request.method + if request.method == "POST" + params = Kemal::ParamParser.new(self, request).parse_request + if params.has_key?("_method") && self.override_method_valid?(params["_method"]) + request.override_method = params["_method"] + end + end + end + + # Checks if method contained in _method param is valid one + def override_method_valid?(override_method) + return false unless override_method.is_a?(String) + override_method = override_method.upcase + return (override_method == "PUT" || override_method == "PATCH" || override_method == "DELETE") end private def pattern_to_regex(pattern)