-
Notifications
You must be signed in to change notification settings - Fork 303
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
task #169
Open
Tobi1246
wants to merge
3
commits into
psylone:master
Choose a base branch
from
Tobi1246:less4
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
task #169
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
log/app.log |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,33 @@ | ||
# Simpler | ||
Создайте на гитхабе форк учебного проекта из скринкаста (ссылки в дополнительных материалах), в полученном новом репозитории, в новой ветке выполните следующие задания: | ||
|
||
**Simpler** is a little web framework written in [Ruby](https://www.ruby-lang.org) language. It's compatible with [Rack](https://rack.github.io) interface and intended to **learn** how web frameworks work in general. | ||
Реализуйте расширенные возможности метода render которые позволят возвращать ответ в других форматах, например: | ||
render plain: "Plain text response" | ||
|
||
Реализуйте возможность устанавливать в методе контроллера статус ответа, например: | ||
status 201 | ||
|
||
Реализуйте возможность устанавливать в методе контроллера заголовки, например: | ||
headers['Content-Type'] = 'text/plain' | ||
|
||
Реализуйте механизм обработки исключения когда маршрут для запрашиваемого URL не был найден. В этом случае клиенту должен отдаваться ответ со статусом 404 | ||
|
||
## The application overview | ||
|
||
Simpler application is a singleton instance of the `Simpler::Application` class. For convenience it can be obtained by calling `Simpler.application` method. This instance holds all the routes and responds to `call` method which is required by the Rack interface. | ||
Напишите механизм разбора route-параметров. Например, при добавлении маршрута | ||
get '/tests/:id', 'tests#show' | ||
|
||
а) Маршрут должен корректно обрабатывать GET запрос | ||
/tests/101 | ||
|
||
b) В методе show контроллера при вызове метода params должен быть доступен параметр :id со значением 101 | ||
|
||
Напишите middleware для логирования HTTP-запросов и ответов: | ||
a) Лог должен записываться в файл log/app.log | ||
b) Для запросов необходимо записывать HTTP-метод запроса, URL, контроллер и метод который будет обрабатывать запрос, хэш параметров который будет доступен при вызове метода params | ||
c) Для ответов необходимо записывать код статуса ответа, тип тела ответа и название шаблона (если ответ рендерился с помощью шаблона представления) | ||
|
||
Пример: | ||
|
||
Request: GET /tests?category=Backend | ||
Handler: TestsController#index | ||
Parameters: {'category' => 'Backend'} | ||
Response: 200 OK [text/html] tests/index.html.erb |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,4 +9,4 @@ | |
|
||
<p><%= @time %></p> | ||
</body> | ||
</html> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
<!DOCTYPE html> | ||
<html> | ||
<head> | ||
<meta charset="utf-8"> | ||
<title>Show | Simpler application</title> | ||
</head> | ||
<body> | ||
<h1>Simpler framework at work!</h1> | ||
<p><%= @id %></p> | ||
</body> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,5 @@ | ||
require_relative 'config/environment' | ||
require_relative 'middleware/logger' | ||
|
||
use AppLogger, logdev: File.expand_path('log/app.log', __dir__) | ||
run Simpler.application |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
require 'rack' | ||
require_relative '../lib/simpler' | ||
|
||
Simpler.application.bootstrap! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
Simpler.application.routes do | ||
get '/tests', 'tests#index' | ||
get '/tests/:id', 'tests#show' | ||
post '/tests', 'tests#create' | ||
end |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,9 +10,14 @@ def initialize(env) | |
end | ||
|
||
def render(binding) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. типов может быть очень много. Лучше тут применить табличный метод. Или хотябы для каждого тим сделать свой метод, а тут вызывать нужный метод |
||
template = File.read(template_path) | ||
|
||
ERB.new(template).result(binding) | ||
plain = Hash(template)[:plain] | ||
if plain | ||
"#{plain}\n" | ||
else | ||
template = File.read(template_path) | ||
|
||
ERB.new(template).result(binding) | ||
end | ||
end | ||
|
||
private | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
require 'logger' | ||
|
||
class AppLogger | ||
|
||
def initialize(app, **options) | ||
@logger = Logger.new(options[:logdev] || STROUT) | ||
@app = app | ||
end | ||
|
||
def call(env) | ||
request_line = "\nRequest: #{env["REQUEST_METHOD"]} " | ||
request_line << env["PATH_INFO"] | ||
request_line << "/?#{env["QUERY_STRING"]}" unless env["QUERY_STRING"].empty? | ||
@logger.info request_line | ||
|
||
status, headers, body = @app.call(env) | ||
|
||
if env['simpler.controller'] | ||
@logger.info "\nParameters: #{env['simpler.controller'].params}" | ||
end | ||
@logger.info "\nHandler: #{env['simpler.handler']}" | ||
|
||
response_line = "\nResponse: #{status} " | ||
response_line << "[#{headers['Content-Type']}]" | ||
response_line << " #{env['simpler.template']}" | ||
@logger.info response_line | ||
|
||
[status, headers, body] | ||
end | ||
|
||
end |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
подтяни регулярные выражения. Пригодится