Skip to content
Open

hw #168

Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions app/controllers/tests_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,19 @@ class TestsController < Simpler::Controller

def index
@time = Time.now
# render plain: 'Plain text response', status: 404

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

такой комментарий ни какой пользы не несёт и должен быть удалён

render 'tests/index', status: 201
end

def create

end

def show
@test_id = params[:id]
@time = Time.now
render 'tests/show'
# render plain: 'Show', status: 201
end

end
2 changes: 1 addition & 1 deletion app/views/tests/index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@

<p><%= @time %></p>
</body>
</html>
</html>
12 changes: 12 additions & 0 deletions app/views/tests/show.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Show | Simpler application</title>
</head>
<body>
<h1>Simpler framework at work!</h1>

<p><%= @test_id %></p>
</body>
</html>
2 changes: 2 additions & 0 deletions config.ru
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require_relative 'middleware/custom_logger'
require_relative 'config/environment'

use CustomLogger, logdev: File.expand_path('log/app.log', __dir__)
run Simpler.application
1 change: 1 addition & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
Simpler.application.routes do
get '/tests', 'tests#index'
post '/tests', 'tests#create'
get '/tests/:id', 'tests#show'
end
24 changes: 21 additions & 3 deletions lib/simpler/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,32 @@ def routes(&block)

def call(env)
route = @router.route_for(env)
controller = route.controller.new(env)
action = route.action
# begin
# controller = route.controller.new(env)
# action = route.action

make_response(controller, action)
# make_response(controller, action)
# rescue
# @response = Rack::Response.new
# @response = [404, {}, []]
# end

if route
controller = route.controller.new(env)
action = route.action

make_response(controller, action)
else
not_found_response
end
end

private

def not_found_response
[404, {'Content-Type' => 'text/plain'}, ['Not found (404 Error)']]
end

def require_app
Dir["#{Simpler.root}/app/**/*.rb"].each { |file| require file }
end
Expand Down
28 changes: 24 additions & 4 deletions lib/simpler/controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
module Simpler
class Controller

attr_reader :name, :request, :response
attr_reader :name, :request, :response, :status

def initialize(env)
@name = extract_name
Expand Down Expand Up @@ -32,8 +32,14 @@ def set_default_headers
@response['Content-Type'] = 'text/html'
end

def set_headers
@response.headers
end

def write_response
body = render_body
@request.env['simpler.response.status'] = @response.status
@request.env['simpler.response.header'] = set_headers['Content-Type']

@response.write(body)
end
Expand All @@ -43,11 +49,25 @@ def render_body
end

def params
@request.params
@request.env['simpler.params'].merge!(@request.params)
end

def render(template)
@request.env['simpler.template'] = template
# def render(template, status = {})
# case template
# when String
# set_headers['Content-Type'] = 'text/html'
# when Hash
# if template.has_key?(:plain)
# set_headers['Content-Type'] = 'text/plain'
# end
# end

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это тоже мусор в коде


def render(template, status = {})
@request.env['simpler.template'] = template
if status.is_a?(Integer) && status >= 100
status = status[:status] || template[:status]
@response.status = status
end
end

end
Expand Down
2 changes: 1 addition & 1 deletion lib/simpler/router.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def route_for(env)
method = env['REQUEST_METHOD'].downcase.to_sym
path = env['PATH_INFO']

@routes.find { |route| route.match?(method, path) }
@routes.find { |route| route.match?(method, path, env) }
end

private
Expand Down
28 changes: 26 additions & 2 deletions lib/simpler/router/route.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,32 @@ def initialize(method, path, controller, action)
@action = action
end

def match?(method, path)
@method == method && path.match(@path)
def match?(method, path, env)
@method == method && parse_path(path, env)
end

private

def parse_path(path, env)
params = {}
router_parts = @path.split('/') # ["", "tests", ":id"]
request_parts = path.split('/') # ["", "tests", "1"]

return false if router_parts.size != request_parts.size # false

router_parts.each_index do |index|
unless router_parts[index] == request_parts[index] # если части не совпадают полностью
match_data = router_parts[index].match(/^:(.+)/) # ["", "tests", ":id"] поочередно проверяются на соответствие /^:(.+)/
# выбирается часть с :id
# match_data = [':id']

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

такие комментарии не пишут
https://rubystyle.guide/#refactor-dont-comment

return false if match_data.nil?

params[match_data[1].to_sym] = request_parts[index] # params[:id] = 1 (соответствующая часть пути)
end
end

env['simpler.params'] = params
end

end
Expand Down
8 changes: 6 additions & 2 deletions lib/simpler/view.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ def initialize(env)
end

def render(binding)
template = File.read(template_path)
if template.is_a?(Hash)
template[:plain]
else
template = File.read(template_path)

ERB.new(template).result(binding)
ERB.new(template).result(binding)
end
end

private
Expand Down
14 changes: 14 additions & 0 deletions log/app.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
I, [2023-10-01T20:28:44.252388 #6864] INFO -- :
********************************************************
Request: GET /tests/1
Handler: TestsController#show
Parameters: {:id=>"1"}
Response: 200 [text/html] tests/show

I, [2023-10-01T20:28:50.838787 #6864] INFO -- :
********************************************************
Request: GET /tests
Handler: TestsController#index
Parameters: {}
Response: 200 [text/html] tests/index

36 changes: 36 additions & 0 deletions middleware/custom_logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
require 'logger'

class CustomLogger

def initialize(app, **options)
@logger = Logger.new(options[:logdev] || STDOUT)
@app = app
end

def call(env)
response = @app.call(env)
@logger.info(message(env))
response
end

def message(env)
controller = env['simpler.controller']

if controller
<<~LOGGER

********************************************************
Request: #{env['REQUEST_METHOD']} #{env['PATH_INFO']}
Handler: #{controller.name.capitalize}Controller##{env['simpler.action']}
Parameters: #{env['simpler.params']}
Response: #{env['simpler.response.status']} [#{env['simpler.response.header']}] #{env['simpler.template']}
LOGGER
else
<<~LOGGER

Request: #{env['REQUEST_METHOD']} #{env['PATH_INFO']}
Response: #{}
LOGGER
end
end
end