Skip to content

Commit ea6c5d6

Browse files
committed
Klass methods controller base
1 parent 05dfcd7 commit ea6c5d6

3 files changed

Lines changed: 62 additions & 6 deletions

File tree

app/controllers/base_controller.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class BaseController
2+
attr_reader :request
3+
4+
def initialize(request)
5+
@request = request
6+
end
7+
8+
def index
9+
build_response <<-HTML
10+
<html>
11+
<head><title>Ruby Funicular</title></head>
12+
<body>
13+
<h1>Welcome to Ruby Funicular</h1>
14+
<p>It's a fun ride!</p>
15+
</body>
16+
</html>
17+
HTML
18+
end
19+
20+
private
21+
22+
def build_response(body, status: 200)
23+
[status, { "Content-Type" => "text/html" }, [body]]
24+
end
25+
26+
def redirect_to(uri)
27+
build_response("", 302, "Location" => uri)
28+
end
29+
30+
def params
31+
@request.params
32+
end
33+
34+
end

app/router.rb

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,37 @@ def initialize(request)
44
end
55

66
def route!
7-
if @request.path == "/"
8-
[200, {"Content-Type" => "text/plain"}, ["Welcome home!"]]
9-
else
10-
not_found
11-
end
12-
end
7+
if klass = controller_class
8+
add_route_info_to_request_params!
9+
10+
controller = klass.new(@request)
11+
action = route_info[:action]
12+
13+
if controller.respond_to?(action)
14+
puts "\nRouting to #{klass}##{action}"
15+
return controller.public_send(action)
16+
end
17+
end
18+
19+
not_found
20+
end
1321

1422
private
1523

24+
def add_route_info_to_request_params!
25+
@request.params.merge!(route_info)
26+
end
27+
28+
def controller_name
29+
"#{route_info[:resource].capitalize}Controller"
30+
end
31+
32+
def controller_class
33+
Object.const_get(controller_name)
34+
rescue NameError
35+
nil
36+
end
37+
1638
def route_info
1739
@route_info ||= begin
1840
resource = path_fragments[0] || "base"

screenshot.png

43 KB
Loading

0 commit comments

Comments
 (0)