Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Ignore all logfiles
/log/*
8 changes: 5 additions & 3 deletions app/controllers/tests_controller.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
class TestsController < Simpler::Controller
def index
@time = Time.now
render "tests/index"
end

Choose a reason for hiding this comment

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

согласно REST данный экшен должен отдавать список тестов, а не время


def create
status 201
render plain: "Create method in action!"
end

Choose a reason for hiding this comment

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

тут ведь ни чего не создаётся


def plain
render plain: "plain_option_example"
status 201
render plain: "Plain text responce example"
status 200
end

def show
@id = params[:id]
render plain: "This is an object (show tests method) with id #{@id}"
end

def question
Expand Down
10 changes: 10 additions & 0 deletions app/views/tests/show.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index | Simpler application</title>
</head>
<body>
<h1> This is the test object (show tests method) with id <%= @id %> </h1>
</body>
</html>
4 changes: 3 additions & 1 deletion config.ru
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require_relative 'config/environment'
require_relative "config/environment"
require_relative "lib/simpler/middleware/logger"

use Simpler::AppLogger, logdev: File.expand_path("log/app.log", Simpler.root)
run Simpler.application
14 changes: 13 additions & 1 deletion lib/simpler/application.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

require "yaml"
require "singleton"
require "sequel"
Expand Down Expand Up @@ -27,7 +29,10 @@ def routes(&block)

def call(env)
route = @router.route_for(env)

return not_found unless route
return not_found unless route.params.empty? || db_route_params_exists?(route.params)

env["simpler.route_params"] = route.params
controller = route.controller.new(env)
action = route.action
Expand All @@ -38,7 +43,7 @@ def call(env)
private

def require_app
Dir["#{Simpler.root}/app/**/*.rb"].each { |file| require file }
Dir["#{Simpler.root}/app/**/*.rb"].sort.each { |file| require file }
end

def require_routes
Expand All @@ -58,5 +63,12 @@ def make_response(controller, action)
def not_found
[404, { "Content-Type" => "text/plain" }, ["Not found"]]
end

def db_route_params_exists?(params)
corresponding_record = nil
params.each { |_param_name, param_value| corresponding_record = @db[:tests].first(id: param_value) }

!corresponding_record.nil?
end
end
end
55 changes: 55 additions & 0 deletions lib/simpler/middleware/logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
require "logger"

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

def call(env)
@status, @header, @body = @app.call(env)
@request = Rack::Request.new(env)

@logger.info(create_log)

Rack::Response.new(@body, @status, @header).finish
end

private

def create_log
if @status == 404
%Q(
Request: #{@request.request_method} #{@request.fullpath}
Handler: Nil
Parameters: #{@request.params}
Response: #{full_status}
).delete!("\n")
else
%Q(
Request: #{@request.request_method} #{@request.fullpath}
Handler: #{controller}##{action}
Parameters: #{@request.params}
Response: #{full_status} \[#{@header["Content-Type"]}\] #{view}
).delete!("\n")
end
end

Choose a reason for hiding this comment

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

так как лог файл может быть беконечно большим, то лог каждого запроса лучше писать в 1 строчку


def controller
@request.env["simpler.controller"].class.name
end

def action
@request.env["simpler.action"]
end

def full_status
"#{@status}" + " #{Rack::Utils::HTTP_STATUS_CODES[@status]}"
end

def view
"#{@request.env["simpler.template"] || [controller, action].join("/")}.html.erb" unless @request.env["simpler.text_plain"]
end
end
end
10 changes: 4 additions & 6 deletions lib/simpler/router.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
require_relative 'router/route'
require_relative "router/route"

module Simpler
class Router

def initialize
@routes = []
end
Expand All @@ -16,16 +15,16 @@ def post(path, route_point)
end

def route_for(env)
method = env['REQUEST_METHOD'].downcase.to_sym
path = env['PATH_INFO']
method = env["REQUEST_METHOD"].downcase.to_sym
path = env["PATH_INFO"]

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

private

def add_route(method, path, route_point)
route_point = route_point.split('#')
route_point = route_point.split("#")
controller = controller_from_string(route_point[0])
action = route_point[1]
route = Route.new(method, path, controller, action)
Expand All @@ -36,6 +35,5 @@ def add_route(method, path, route_point)
def controller_from_string(controller_name)
Object.const_get("#{controller_name.capitalize}Controller")
end

end
end
20 changes: 12 additions & 8 deletions lib/simpler/router/route.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@ def initialize(method, path, controller, action)
end

def match?(method, path)
define_params(path)
edited_path = define_edited_path(path) || path
@params = define_params(path)

edited_path = if @params.values.all? && ([email protected]?)
define_edited_path(path)
else
path
end

@method == method && edited_path == @path
end
Expand All @@ -31,16 +36,15 @@ def define_params(path)
path.scan(ROUTE_PARAM_VALUE_REGEXP).each { |param| route_params_values << (param.delete "/") }
@path.scan(ROUTE_PARAM_NAME_REGEXP).each { |param| route_params_names << param.delete(":").delete("/").to_sym }

@params = Hash[route_params_names.zip route_params_values]
Hash[route_params_names.zip route_params_values]
end

def define_edited_path(path)
str = path
@params.each do |param_name, param_value|
str = str.gsub param_value, ":#{param_name.to_s}"
end
edited_path = path

@params.each { |param_name, param_value| edited_path = edited_path.gsub param_value, ":#{param_name.to_s}" }

str
edited_path
end
end
end
Expand Down
11 changes: 11 additions & 0 deletions log/app.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
I, [2021-07-20T21:29:48.157677 #288091] INFO -- : Request: GET /tests/2 Handler: TestsController#show Parameters: {:id=>"2"} Response: 200 OK [text/html] TestsController/show.html.erb
I, [2021-07-20T21:30:01.670387 #288091] INFO -- : Request: GET /tests/6 Handler: Nil Parameters: {} Response: 404 Not Found
I, [2021-07-20T21:30:14.369278 #288091] INFO -- : Request: GET /tests/3/question/25?one=1 Handler: Nil Parameters: {"one"=>"1"} Response: 404 Not Found
I, [2021-07-20T21:30:24.195654 #288091] INFO -- : Request: GET /tests Handler: TestsController#index Parameters: {} Response: 200 OK [text/html] tests/index.html.erb
I, [2021-07-20T21:32:27.196093 #288333] INFO -- : Request: POST /tests Handler: TestsController#create Parameters: {} Response: 201 Created [text/plain]
I, [2021-07-20T21:35:00.585388 #288333] INFO -- : Request: POST /tests Handler: TestsController#create Parameters: {} Response: 201 Created [text/plain]
I, [2021-07-20T21:35:02.896432 #288333] INFO -- : Request: GET /tests Handler: TestsController#index Parameters: {} Response: 200 OK [text/html] tests/index.html.erb
I, [2021-07-20T21:35:07.109826 #288333] INFO -- : Request: GET /tests/3/question/25?one=1 Handler: Nil Parameters: {"one"=>"1"} Response: 404 Not Found
I, [2021-07-20T21:35:10.289813 #288333] INFO -- : Request: GET /tests/6 Handler: Nil Parameters: {} Response: 404 Not Found
I, [2021-07-20T21:35:13.920833 #288333] INFO -- : Request: GET /tests/2 Handler: TestsController#show Parameters: {:id=>"2"} Response: 200 OK [text/html] TestsController/show.html.erb
I, [2021-07-20T21:35:20.181146 #288333] INFO -- : Request: GET /tests/plain Handler: TestsController#plain Parameters: {} Response: 200 OK [text/plain]