summaryrefslogtreecommitdiff
path: root/lib/router.rb
diff options
context:
space:
mode:
Diffstat (limited to 'lib/router.rb')
-rw-r--r--lib/router.rb60
1 files changed, 60 insertions, 0 deletions
diff --git a/lib/router.rb b/lib/router.rb
new file mode 100644
index 0000000..3597dfd
--- /dev/null
+++ b/lib/router.rb
@@ -0,0 +1,60 @@
+require 'pry'
+
+class Router
+ def initialize
+ @routes = []
+ end
+
+ def call(env)
+ path = env["REQUEST_PATH"]
+ method = env["REQUEST_METHOD"]
+ @routes.each do |route|
+ next if method != route[:method]
+ params = match_route(path, route[:path])
+ if params
+ return respond_html(route[:block].call(params))
+ end
+ end
+ respond_html("not found", status: 404)
+ end
+
+ def match_route(incoming_path, path)
+ params = {}
+ incoming_parts = incoming_path.split("/")
+ path_parts = path.split("/")
+
+ incoming_parts.each_with_index do |incoming_part, index|
+ path_part = path_parts[index]
+ if path_part&.start_with?(":")
+ params[path_part[1..-1]] = incoming_part
+ else
+ if path_part != incoming_part
+ return false
+ end
+ end
+ end
+ params
+ end
+
+ def get(path, &block)
+ @routes.push({ method: "GET", path: path, block: block })
+ end
+
+ def post(path, &block)
+ @routes.push({ method: "POST", path: path, block: block })
+ end
+
+ def put(path, &block)
+ @routes.push({ method: "PUT", path: path, block: block })
+ end
+
+ def delete(path, &block)
+ @routes.push({ method: "DELETE", path: path, block: block })
+ end
+
+ private
+
+ def respond_html(content, status: 200)
+ [status, {'Content-Type' => 'text/html'}, [content]]
+ end
+end