Update router to handle method matching

This commit is contained in:
sdogruyol 2016-01-13 15:22:50 +02:00
parent 54f25c5880
commit b37dd29d4b
2 changed files with 31 additions and 5 deletions

View file

@ -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

View file

@ -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)