-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.rb
64 lines (55 loc) · 1.69 KB
/
router.rb
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
61
62
63
64
class Router
# TODO: Use specific ErrorController?
NOT_FOUND = {controller: ErrorController, action: :missing_endpoint}
BAD_REQUEST = {controller: ErrorController, action: :bad_request}
class << self
def config(&block)
@routes_hash = {}
instance_eval(&block)
end
def route(request)
method = request.method
path = request.path&.chomp("/")
return BAD_REQUEST if method.nil? || path.nil?
@routes_hash.dig(path, method) || NOT_FOUND
end
private
# define methods for http methods to allow for expressive route definitions
[:get, :post, :put, :patch, :delete].each do |method|
define_method(method) do |route_name, controller:, action: nil|
default_or_custom_action = action.nil? ? route_name.split("/").last : action
# TODO: add some default controller name (and change current controller names)
add_route(
route_name,
controller: controller,
action: default_or_custom_action,
method: method.to_s.upcase
)
end
end
# builds routes hash like thie:
# {
# "" => {
# "GET" => {
# controller: GetController,
# action: :root
# },
# "POST" => {
# controller: PostController,
# action: :root
# }
# },
# "/endpoint" => {
# "GET" => {
# controller: GetController,
# action: :time
# }
# }
# }
def add_route(route_name, controller:, action:, method:)
# TODO: split("/") nested routes
@routes_hash[route_name] ||= {}
@routes_hash[route_name][method] = {controller: controller, action: action}
end
end
end