summaryrefslogtreecommitdiff
path: root/lib/router.rb
blob: 3597dfd1d11fa741745cd1eed43a6e832b845eaa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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