Skip to content

Task20 #143

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 6 commits 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
./log
8 changes: 6 additions & 2 deletions app/controllers/tests_controller.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
class TestsController < Simpler::Controller

def index
@time = Time.now
# render plain: "#{@time} This is text from Plain"
end

def create

render plain: 'This is text from Plain create'
end

def show
@test = Test.where(id: params[:id])
render plain: "Action Show: params: #{params}, @test = #{@test} "
end
end
1 change: 0 additions & 1 deletion app/models/test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,4 @@
# Integer :level, default: 0
# end
class Test < Sequel::Model

end
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><%= @time %></p>
</body>
</html>
1 change: 1 addition & 0 deletions config.ru
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require_relative 'config/environment'

use Logger
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
Binary file modified db/test_guru.sqlite
Binary file not shown.
39 changes: 39 additions & 0 deletions lib/logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Logger
def initialize(app)
@app = app
end

def call(env)
log_file = File.open('log/app.log', 'a+')
request = Rack::Request.new(env)
status, headers, body = @app.call(env)
response = Rack::Response.new(body, status, headers)
write_log(log_file, request, status, headers)

response.finish
end

private

def write_log(file, request, status, headers)
log_body = log_form(request, status, headers)
file.write(log_body)

file.close
end

def log_form(request, status, headers)
method = request.request_method
url = request.fullpath
controller = request.env['simpler.controller']
action = request.env['simpler.action']
pattern = request.env['simpler.pattern']
params = request.env['simpler.route_params']

"#{Time.now}
Request: #{method} #{url}
Handler: #{controller.class.name}##{action}
Parameters: #{params}
Response: #{status} [#{headers['Content-Type']}] #{pattern} \n\n"
end
end
2 changes: 0 additions & 2 deletions lib/simpler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
require_relative 'simpler/application'

module Simpler

class << self
def application
Application.instance
Expand All @@ -12,5 +11,4 @@ def root
Pathname.new(File.expand_path('..', __dir__))
end
end

end
23 changes: 17 additions & 6 deletions lib/simpler/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

module Simpler
class Application

include Singleton

attr_reader :db
Expand All @@ -20,22 +19,31 @@ def bootstrap!
setup_database
require_app
require_routes
require_logger
end

def routes(&block)
@router.instance_eval(&block)
end

def call(env)
route = @router.route_for(env)
controller = route.controller.new(env)
action = route.action
if (route = @router.route_for(env))
env['simpler.route_params'] = route.params
controller = route.controller.new(env)
action = route.action

make_response(controller, action)
make_response(controller, action)
else
not_found
end
end

private

def not_found
Rack::Response.new("Resource not exist!\n", 404, {}).finish
end

def require_app
Dir["#{Simpler.root}/app/**/*.rb"].each { |file| require file }
end
Expand All @@ -44,6 +52,10 @@ def require_routes
require Simpler.root.join('config/routes')
end

def require_logger
require_relative '../logger'
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 All @@ -53,6 +65,5 @@ def setup_database
def make_response(controller, action)
controller.make_response(action)
end

end
end
32 changes: 24 additions & 8 deletions lib/simpler/controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

module Simpler
class Controller

attr_reader :name, :request, :response

def initialize(env)
Expand All @@ -15,7 +14,8 @@ def make_response(action)
@request.env['simpler.controller'] = self
@request.env['simpler.action'] = action

set_default_headers
set_headers
set_status
send(action)
write_response

Expand All @@ -24,12 +24,25 @@ def make_response(action)

private

def extract_name
self.class.name.match('(?<name>.+)Controller')[:name].downcase
def set_status(status = nil)
case @request.request_method
when 'GET'
@response.status = Rack::Utils::SYMBOL_TO_STATUS_CODE[:ok]
when 'POST'
@response.status = Rack::Utils::SYMBOL_TO_STATUS_CODE[:created]
when 'PATCH'
@response.status = Rack::Utils::SYMBOL_TO_STATUS_CODE[:no_content]
end

@response.status = status unless status.nil?
end

def set_default_headers
@response['Content-Type'] = 'text/html'
def set_headers(type = 'text/html')
@response['Content-Type'] = type
end

def extract_name
self.class.name.match('(?<name>.+)Controller')[:name].downcase
end

def write_response
Expand All @@ -43,12 +56,15 @@ def render_body
end

def params
@request.params
@request.params.merge(form_param)
end

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

def render(template)
@request.env['simpler.template'] = template
end

end
end
2 changes: 0 additions & 2 deletions lib/simpler/router.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

module Simpler
class Router

def initialize
@routes = []
end
Expand Down Expand Up @@ -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
29 changes: 26 additions & 3 deletions lib/simpler/router/route.rb
Original file line number Diff line number Diff line change
@@ -1,20 +1,43 @@
module Simpler
class Router
class Route

attr_reader :controller, :action
attr_reader :controller, :action, :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)
end

private

def path_match?(path)
path_request = path.split('/')
path_router = @path.split('/')
compare(path_request, path_router)
end

def compare(path_request, path_router)
return false if path_request.size != path_router.size

path_router.each_with_index do |item, index|
if item =~ /^:[\d\w]+$/
save_params(item, path_request[index])
next
end
return false if item != path_request[index]
end
end

def save_params(key, value)
@params[key] = value
end
end
end
end
15 changes: 15 additions & 0 deletions lib/simpler/tmp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
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
25 changes: 22 additions & 3 deletions lib/simpler/view.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,39 @@

module Simpler
class View

VIEW_BASE_PATH = 'app/views'.freeze

def initialize(env)
@env = env
end

def render(binding)
extend? ? extending_render : file_render(binding)
end

private

def extending_render
send(key_hash)
end

def key_hash
@env['simpler.template'].keys[0]
end

def plain
@env['simpler.template'].values[0] + "\n"
end

def file_render(binding)
template = File.read(template_path)

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

private
def extend?
@env['simpler.template'].instance_of?(Hash)
end

def controller
@env['simpler.controller']
Expand All @@ -31,9 +50,9 @@ def template

def template_path
path = template || [controller.name, action].join('/')
@env['simpler.pattern'] = "#{path}.html.erb"

Simpler.root.join(VIEW_BASE_PATH, "#{path}.html.erb")
end

end
end
Loading