Skip to content

task_20 #136

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
5 changes: 5 additions & 0 deletions app/controllers/tests_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@ class TestsController < Simpler::Controller

def index
@time = Time.now
render plain: "Plain text response"
end


def create
end

def show
@test_id = @request.params[:id]
end

end
11 changes: 11 additions & 0 deletions app/views/tests/create.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Post | Simpler application</title>
</head>
<body>
<h1>Post request was sent</h1>

</body>
</html>
11 changes: 11 additions & 0 deletions app/views/tests/show.html.erb
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>Test: <%= @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 'config/environment'
require_relative 'middleware/logger'

use AppLogger, 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
23 changes: 20 additions & 3 deletions lib/simpler/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,18 @@ def routes(&block)

def call(env)
route = @router.route_for(env)
controller = route.controller.new(env)
action = route.action
if route.nil?
self.not_found
else
controller = route.controller.new(env)
action = route.action

make_response(controller, action)
route.add_params(env['PATH_INFO'])
env['simpler.params'] = route.params


make_response(controller, action)
end
end

private
Expand All @@ -44,6 +52,15 @@ def require_routes
require Simpler.root.join('config/routes')
end

def not_found
response = Rack::Response.new(
['404 Not Found'],
404,
{ 'Content-Type' => 'text/plain' }
)
response.finish
end

def setup_database
database_config = YAML.load_file(Simpler.root.join('config/database.yml'))
database_config['database'] = Simpler.root.join(database_config['database'])
Expand Down
23 changes: 22 additions & 1 deletion lib/simpler/controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,20 @@ class Controller

attr_reader :name, :request, :response


def initialize(env)
@name = extract_name
@request = Rack::Request.new(env)
@response = Rack::Response.new
@request_type = env['REQUEST_METHOD']
end

def make_response(action)
@request.env['simpler.controller'] = self
@request.env['simpler.action'] = action


set_params
set_default_headers
send(action)
write_response
Expand All @@ -36,19 +40,36 @@ def write_response
body = render_body

@response.write(body)
status_201
end

def render_body
View.new(@request.env).render(binding)
end

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

def params
@request.params
end

def render(template)
@request.env['simpler.template'] = template
if template.is_a?(Hash)
@response['CONTENT_TYPE'] = 'text/plain'
@request.env['simpler.plain_text'] = template[:plain]
else
@request.env['simpler.template'] = template
end
end

def status_201
if @request_type == "POST"
@response.status == 201
end
end


end
end
2 changes: 2 additions & 0 deletions lib/simpler/router.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ def route_for(env)
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('#')
controller = controller_from_string(route_point[0])
Expand Down
17 changes: 15 additions & 2 deletions lib/simpler/router/route.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,30 @@ module Simpler
class Router
class Route

attr_reader :controller, :action
attr_reader :controller, :action, :path, :params

def initialize(method, path, controller, action)
@method = method
@path = path
@controller = controller
@action = action
@params = {}
end

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

def path_to_route
Regexp.new("^#{@path.gsub(/:id/, '\d+')}$")
end

def add_params(path)
value = path.scan(/\w+\/\d+/).join('/')
return if value.empty?

value = value.split('/')
@params[:id] = value[-1].to_i
end

end
Expand Down
15 changes: 12 additions & 3 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)

ERB.new(template).result(binding)
if plain_text
ERB.new(plain_text).result(binding)
else
template = File.read(template_path)

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

private
Expand All @@ -29,6 +33,10 @@ def template
@env['simpler.template']
end

def plain_text
@env['simpler.plain_text']
end

def template_path
path = template || [controller.name, action].join('/')

Expand All @@ -37,3 +45,4 @@ def template_path

end
end

14 changes: 14 additions & 0 deletions log/app.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Logfile created on 2022-03-14 22:04:39 +0300 by logger.rb/v1.4.2

Choose a reason for hiding this comment

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

логи всегда помещаем в гитигнор

I, [2022-03-14T22:05:01.588418 #396276] INFO -- : {"rack.version"=>[1, 3], "rack.errors"=>#<Rack::Lint::ErrorWrapper:0x000055a6da02a388 @error=#<IO:<STDERR>>>, "rack.multithread"=>true, "rack.multiprocess"=>false, "rack.run_once"=>false, "SCRIPT_NAME"=>"", "QUERY_STRING"=>"", "SERVER_PROTOCOL"=>"HTTP/1.1", "SERVER_SOFTWARE"=>"puma 3.12.6 Llamas in Pajamas", "GATEWAY_INTERFACE"=>"CGI/1.2", "REQUEST_METHOD"=>"GET", "REQUEST_PATH"=>"/tests/1", "REQUEST_URI"=>"/tests/1", "HTTP_VERSION"=>"HTTP/1.1", "HTTP_HOST"=>"localhost:9292", "HTTP_USER_AGENT"=>"curl/7.68.0", "HTTP_ACCEPT"=>"*/*", "SERVER_NAME"=>"localhost", "SERVER_PORT"=>"9292", "PATH_INFO"=>"/tests/1", "REMOTE_ADDR"=>"127.0.0.1", "puma.socket"=>#<TCPSocket:fd 13, AF_INET, 127.0.0.1, 9292>, "rack.hijack?"=>true, "rack.hijack"=>#<Proc:0x000055a6da02a4a0 /var/lib/gems/2.7.0/gems/rack-2.2.3/lib/rack/lint.rb:567>, "rack.input"=>#<Rack::Lint::InputWrapper:0x000055a6da02a3b0 @input=#<Puma::NullIO:0x000055a6da186f10>>, "rack.url_scheme"=>"http", "rack.after_reply"=>[], "puma.config"=>#<Puma::Configuration:0x000055a6da05dff8 @options=#<Puma::UserFileDefaultOptions:0x000055a6da05de68 @user_options={:environment=>"development", :pid=>nil, :Port=>9292, :Host=>"localhost", :AccessLog=>[], :config=>"/home/user/Документы/simpler/config.ru", :log_requests=>false, :binds=>["tcp://localhost:9292"], :app=>#<Rack::ContentLength:0x000055a6d9fb64d8 @app=#<Rack::CommonLogger:0x000055a6d9fb6550 @app=#<Rack::ShowExceptions:0x000055a6d9f7bd38 @app=#<Rack::Lint:0x000055a6d9f7bdb0 @app=#<Rack::TempfileReaper:0x000055a6d9f7be28 @app=#<AppLogger:0x000055a6d9a8e280 @logger=#<Logger:0x000055a6d9a8e230 @level=0, @progname=nil, @default_formatter=#<Logger::Formatter:0x000055a6d9a8e208 @datetime_format=nil>, @formatter=nil, @logdev=#<Logger::LogDevice:0x000055a6d9a8e168 @shift_period_suffix="%Y%m%d", @shift_size=1048576, @shift_age=0, @filename="/home/user/Документы/simpler/log/app.log", @dev=#<File:/home/user/Документы/simpler/log/app.log>, @binmode=false, @mon_data=#<Monitor:0x000055a6d9a8e118>, @mon_data_owner_object_id=800>>, @app=#<Simpler::Application:0x000055a6d9c2f738 @router=#<Simpler::Router:0x000055a6d9c2f710 @routes=[#<Simpler::Router::Route:0x000055a6d9b04f48 @method=:get, @path="/tests", @controller=TestsController, @action="index">, #<Simpler::Router::Route:0x000055a6d9b04d90 @method=:post, @path="/tests", @controller=TestsController, @action="create">, #<Simpler::Router::Route:0x000055a6d9b04b88 @method=:get, @path="/tests/:id", @controller=TestsController, @action="show">]>, @db=#<Sequel::SQLite::Database: {"adapter"=>"sqlite", "database"=>#<Pathname:/home/user/Документы/simpler/db/test_guru.sqlite>}>>>>, @content_length=nil>>, @logger=#<IO:<STDERR>>>>}, @file_options={}, @default_options={:min_threads=>0, :max_threads=>16, :log_requests=>false, :debug=>false, :binds=>["tcp://0.0.0.0:9292"], :workers=>0, :daemon=>false, :mode=>:http, :worker_timeout=>60, :worker_boot_timeout=>60, :worker_shutdown_timeout=>30, :remote_address=>:socket, :tag=>"simpler", :environment=>"development", :rackup=>"config.ru", :logger=>#<IO:<STDOUT>>, :persistent_timeout=>20, :first_data_timeout=>30, :Verbose=>false, :Silent=>false}>, @plugins=#<Puma::PluginLoader:0x000055a6da05de18 @instances=[]>, @user_dsl=#<Puma::DSL:0x000055a6da05ddc8 @config=#<Puma::Configuration:0x000055a6da05dff8 ...>, @options={:environment=>"development", :pid=>nil, :Port=>9292, :Host=>"localhost", :AccessLog=>[], :config=>"/home/user/Документы/simpler/config.ru", :log_requests=>false, :binds=>["tcp://localhost:9292"], :app=>#<Rack::ContentLength:0x000055a6d9fb64d8 @app=#<Rack::CommonLogger:0x000055a6d9fb6550 @app=#<Rack::ShowExceptions:0x000055a6d9f7bd38 @app=#<Rack::Lint:0x000055a6d9f7bdb0 @app=#<Rack::TempfileReaper:0x000055a6d9f7be28 @app=#<AppLogger:0x000055a6d9a8e280 @logger=#<Logger:0x000055a6d9a8e230 @level=0, @progname=nil, @default_formatter=#<Logger::Formatter:0x000055a6d9a8e208 @datetime_format=nil>, @formatter=nil, @logdev=#<Logger::LogDevice:0x000055a6d9a8e168 @shift_period_suffix="%Y%m%d", @shift_size=1048576, @shift_age=0, @filename="/home/user/Документы/simpler/log/app.log", @dev=#<File:/home/user/Документы/simpler/log/app.log>, @binmode=false, @mon_data=#<Monitor:0x000055a6d9a8e118>, @mon_data_owner_object_id=800>>, @app=#<Simpler::Application:0x000055a6d9c2f738 @router=#<Simpler::Router:0x000055a6d9c2f710 @routes=[#<Simpler::Router::Route:0x000055a6d9b04f48 @method=:get, @path="/tests", @controller=TestsController, @action="index">, #<Simpler::Router::Route:0x000055a6d9b04d90 @method=:post, @path="/tests", @controller=TestsController, @action="create">, #<Simpler::Router::Route:0x000055a6d9b04b88 @method=:get, @path="/tests/:id", @controller=TestsController, @action="show">]>, @db=#<Sequel::SQLite::Database: {"adapter"=>"sqlite", "database"=>#<Pathname:/home/user/Документы/simpler/db/test_guru.sqlite>}>>>>, @content_length=nil>>, @logger=#<IO:<STDERR>>>>}, @plugins=[]>, @file_dsl=#<Puma::DSL:0x000055a6da05dd50 @config=#<Puma::Configuration:0x000055a6da05dff8 ...>, @options={}, @plugins=[]>, @default_dsl=#<Puma::DSL:0x000055a6da05dd00 @config=#<Puma::Configuration:0x000055a6da05dff8 ...>, @options={:min_threads=>0, :max_threads=>16, :log_requests=>false, :debug=>false, :binds=>["tcp://0.0.0.0:9292"], :workers=>0, :daemon=>false, :mode=>:http, :worker_timeout=>60, :worker_boot_timeout=>60, :worker_shutdown_timeout=>30, :remote_address=>:socket, :tag=>"simpler", :environment=>"development", :rackup=>"config.ru", :logger=>#<IO:<STDOUT>>, :persistent_timeout=>20, :first_data_timeout=>30, :Verbose=>false, :Silent=>false}, @plugins=[]>>, "rack.tempfiles"=>[]}
I, [2022-03-22T10:58:19.108764 #207019] INFO -- :

Request: GET /tests/1
Handler: TestsController#show
Parameters: {:id=>1}
Response: 200 text/html tests/show.html.erb
I, [2022-03-22T11:03:11.991545 #207019] INFO -- :

Request: POST /tests
Handler: TestsController#create
Parameters: {}
Response: 200 text/html tests/create.html.erb
26 changes: 26 additions & 0 deletions middleware/logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
require 'logger'

class AppLogger

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

def call(env)
status, headers, response = @app.call(env)
@logger.info(create_log(env, status, headers))

[status, headers, response]
end

def create_log(env, status, headers)
action = "#{env['simpler.action']}"

"\n
Request: #{env['REQUEST_METHOD']} #{env['REQUEST_URI']}
Handler: #{env['simpler.controller'].class}##{action}
Parameters: #{env['simpler.params']}
Response: #{status} #{headers['Content-Type']} #{env['simpler.controller'].name}/#{action}.html.erb"
end
end