SlideShare a Scribd company logo
1 of 45
Download to read offline
Rails Request
&
Middlewares
Santosh Wadghule
@mechanicles
http://www.mechanicles.com/
I do love to take photos
https://www.flickr.com/photos/santoshwadghule/
CASIO F-91W
Coolest watch in the world
That’s it.
Lets talk about the Rails Request
What is a request?
Request is a…
• It is set of instructions that tells a server what
kind of response we want.
• It is a part of HTTP (request/response) protocol.
• HTTP uses one of the verbs like GET, POST, PUT
& DELETE when you perform the request to the
server.
Rails Request Life Cycle
Rails Request Life Cycle
Browser
Web Server
Routes
Controller
Model
View
Database
Rails App
Middlewares
App Server
App Server & Rails
App
Server Rails
Rack
Web Server
What is a Web Server?
• Web Server is strictly HTTP based, it just takes
HTTP requests and sends back HTTP responses
to the clients(browsers).
• It is mostly designed to serve static files.
• It also has other functionality like request
pipeline, load balancing etc. App servers lack
these functionalities.
• E.g. Ngnix, Apache
App Server
What is an App Server?
• App Server actually runs your Rails app.
• App Server is mostly known for to serve dynamic
pages.
• E.g. Webrick, Passenger, Mongrel, Unicorn, Thin,
Puma & etc.
Request to Rails app
• Rails isn’t just one application, it has lots of
independent Rack applications (middlewares).
• When request comes to the Rails app, it goes
through the list of middleware series.
• Last part of that series, sends request to the
routes file.
Request to Rails app
• Based on request, Rails decides which controller
& action need to be executed from the routes file.
• After executing the controller’s action, Rails sends
back response to the the client.
• Web Server & App Server actually handle the job
of sending response back to the proper client.
Middlewares
What is a Middleware?
• Middleware is a Rack application.
• Middleware is basically a filter for request and
response.
Rails Middlewares
App
Server
Rails App
A B C D
Routes
Controller
Models
Views
Here A, B, C & D are middlewares
Each of these does processing on request & response
Why Rails uses Middlewares?
• Before rails 3, Rails was very tightly coupled.
• As Rails was growing, apps built on Rails had more
demanding requirements. For some apps, Rails gave
lots of additional stuffs by default, which was not
required like cookies/flash. For some other apps, to
implement new filter on the the request/response was
not possible.
• In Rails 3 and after, all these issues have got solved by
using a concept of Rack.
Rack - The Webserver Interface
What is a Rack?
• Rack is not Rake.
• Rack is simple but powerful spec. Yes it is just
spec.
• It is not web framework or web server.
• Rack is created by Christian Neukirchen
Rack - Just an Interface
• It is an interface that sits between your web/app
server and your application. It wraps HTTP
requests and responses in the simplest way
possible, it unifies and distills the API for web
servers, web frameworks and software in
between (i.e. middleware) into a single method
call.
Rack Specification
• Specification: A Rack application is a Ruby object
(not a class) that responds to `call`. It takes
exactly one argument, the environment and
returns an Array of three values, The status, the
headers, and the body. That’s it.
Why do we need Rack?
• Rack promotes low coupling.
• If there was’t Rack, then each framework had to
add separate handler for Thin, Mongrel, Unicorn
and etc to run the app on these servers.
• In reality it’s not a job of framework. They should
not need to take care of it.
Let’s see examples of Rack
Simple Rack App
Rack it up
Using Middleware in a Rack app
• Using ‘use’ method of Rack, you can use
middleware component in Rack application.
• You can use multiple middleware components
which help to change request/response as you
need.
• You can add middlewares by using two methods.
By directly adding middleware in config.ru
and using Rack::Builder.
Directly using Middleware
in config.ru
Rack app + Middleware + config.ru
Using Middleware in
Rack::Builder
What is Rack::Builder?
• Rack::Builder implements a small DSL to
iteratively construct Rack applications.
• Rack::Builder is the thing that glues Rack
middlewares and application together and
converts them into single entity/rack application.
• Under the hood, ‘rackup’ command converts
your config.ru script to an instance of
Rack::Builder.
Rack app + Middleware + Rack::Builder
Rails on Rack
Rails on Rack
• Rails application is the primary Rack
application object.
• It has ‘call’ method similar to rack’s ‘call’
method in its source code (i.e. in
Rails::Application).
Rails’ Rack::Builder
• Same like Rack::Builder, we have similar
concept in Rails, it is called as
ActionDispatch::MiddlewareStack.
• Better flexibility and more features to meet Rails’
requirement.
Rails’ Rack::Builder
• Rails::Application uses
ActionDispatch::MiddlewareStack to
combine various internal and external
middlewares to form a complete Rails Rack
application.
Inspecting Rails Middlewares
• Rails provides a task for inspecting the
middleware stack in use.
• $ bin/rake middleware
$ bin/rake middleware
Note: List of the middlewares may be different for your Rails app
Using Middleware in Rails
• Rails provides a simple configuration interface
config.middleware for adding, removing and
modifying the middlewares in the middleware stack via
application.rb or the environment specific configuration
file environments/<environment>.rb.
• Using these methods config.middleware.use,
config.middleware.insert_before,
config.middleware.insert_after, you can add
new middleware to the middleware stack.
• It also provides ‘swap’ and ‘delete’ methods for
swapping and deleting a middleware.
Add this file under config/initializers directory
And under config/application.rb file, add this following line
config.middleware.use "SayHelloMiddlware"
Always Remember That…
• When request comes to your Rails app, it goes
through these middlewares. From top to bottom.
• At the bottom, request enters into the your Rails’
MVC area.
Thanks :)
Santosh Wadghule
@mechanicles
Questions?

More Related Content

What's hot

Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architectureBishal Khanal
 
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교Amazon Web Services Korea
 
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...IDERA Software
 
Winning Enterprise Cloud Engagements
Winning Enterprise Cloud EngagementsWinning Enterprise Cloud Engagements
Winning Enterprise Cloud EngagementsAmazon Web Services
 
클라우드 비용 최적화 가이드
클라우드 비용 최적화 가이드클라우드 비용 최적화 가이드
클라우드 비용 최적화 가이드OpsNow
 
Cloud computing
Cloud computingCloud computing
Cloud computingcompherals
 
클라우드로 데이터 센터 확장하기 : 하이브리드 환경을 위한 연결 옵션 및 고려사항::강동환::AWS Summit Seoul 2018
클라우드로 데이터 센터 확장하기 : 하이브리드 환경을 위한 연결 옵션 및 고려사항::강동환::AWS Summit Seoul 2018 클라우드로 데이터 센터 확장하기 : 하이브리드 환경을 위한 연결 옵션 및 고려사항::강동환::AWS Summit Seoul 2018
클라우드로 데이터 센터 확장하기 : 하이브리드 환경을 위한 연결 옵션 및 고려사항::강동환::AWS Summit Seoul 2018 Amazon Web Services Korea
 
[Games on AWS 2019] AWS 입문자를 위한 초단기 레벨업 트랙 | AWS 레벨업 하기! : 네트워크 - 권신중 AWS 솔루션...
[Games on AWS 2019] AWS 입문자를 위한 초단기 레벨업 트랙 | AWS 레벨업 하기! : 네트워크 - 권신중 AWS 솔루션...[Games on AWS 2019] AWS 입문자를 위한 초단기 레벨업 트랙 | AWS 레벨업 하기! : 네트워크 - 권신중 AWS 솔루션...
[Games on AWS 2019] AWS 입문자를 위한 초단기 레벨업 트랙 | AWS 레벨업 하기! : 네트워크 - 권신중 AWS 솔루션...Amazon Web Services Korea
 
Modern Enterprise 여정의 핵심 – SAP on AWS 마이그레이션-장현, AWS SAP Architect / 강병수, AWS...
Modern Enterprise 여정의 핵심 – SAP on AWS 마이그레이션-장현, AWS SAP Architect / 강병수, AWS...Modern Enterprise 여정의 핵심 – SAP on AWS 마이그레이션-장현, AWS SAP Architect / 강병수, AWS...
Modern Enterprise 여정의 핵심 – SAP on AWS 마이그레이션-장현, AWS SAP Architect / 강병수, AWS...Amazon Web Services Korea
 
금융 회사를 위한 클라우드 이용 가이드 – 신은수 AWS 솔루션즈 아키텍트, 김호영 AWS 정책협력 담당:: AWS Cloud Week ...
금융 회사를 위한 클라우드 이용 가이드 –  신은수 AWS 솔루션즈 아키텍트, 김호영 AWS 정책협력 담당:: AWS Cloud Week ...금융 회사를 위한 클라우드 이용 가이드 –  신은수 AWS 솔루션즈 아키텍트, 김호영 AWS 정책협력 담당:: AWS Cloud Week ...
금융 회사를 위한 클라우드 이용 가이드 – 신은수 AWS 솔루션즈 아키텍트, 김호영 AWS 정책협력 담당:: AWS Cloud Week ...Amazon Web Services Korea
 
Cloud service lifecycle management
Cloud service lifecycle managementCloud service lifecycle management
Cloud service lifecycle managementAnimesh Chaturvedi
 
Cloud Computing and Services | PPT
Cloud Computing and Services | PPTCloud Computing and Services | PPT
Cloud Computing and Services | PPTSeminar Links
 
Amazon RDS 살펴보기 (김용우) - AWS 웨비나 시리즈
Amazon RDS 살펴보기 (김용우) - AWS 웨비나 시리즈 Amazon RDS 살펴보기 (김용우) - AWS 웨비나 시리즈
Amazon RDS 살펴보기 (김용우) - AWS 웨비나 시리즈 Amazon Web Services Korea
 
Microservices With Istio Service Mesh
Microservices With Istio Service MeshMicroservices With Istio Service Mesh
Microservices With Istio Service MeshNatanael Fonseca
 
AWS Training For Beginners | AWS Certified Solutions Architect Tutorial | AWS...
AWS Training For Beginners | AWS Certified Solutions Architect Tutorial | AWS...AWS Training For Beginners | AWS Certified Solutions Architect Tutorial | AWS...
AWS Training For Beginners | AWS Certified Solutions Architect Tutorial | AWS...Simplilearn
 
MongoDB- Crud Operation
MongoDB- Crud OperationMongoDB- Crud Operation
MongoDB- Crud OperationEdureka!
 

What's hot (20)

Couch db
Couch dbCouch db
Couch db
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architecture
 
20150115 AWS BlackBelt - Amazon VPC (Korea)
20150115 AWS BlackBelt - Amazon VPC (Korea)20150115 AWS BlackBelt - Amazon VPC (Korea)
20150115 AWS BlackBelt - Amazon VPC (Korea)
 
Introduction to CloudFront
Introduction to CloudFrontIntroduction to CloudFront
Introduction to CloudFront
 
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
 
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...
 
Winning Enterprise Cloud Engagements
Winning Enterprise Cloud EngagementsWinning Enterprise Cloud Engagements
Winning Enterprise Cloud Engagements
 
클라우드 비용 최적화 가이드
클라우드 비용 최적화 가이드클라우드 비용 최적화 가이드
클라우드 비용 최적화 가이드
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
클라우드로 데이터 센터 확장하기 : 하이브리드 환경을 위한 연결 옵션 및 고려사항::강동환::AWS Summit Seoul 2018
클라우드로 데이터 센터 확장하기 : 하이브리드 환경을 위한 연결 옵션 및 고려사항::강동환::AWS Summit Seoul 2018 클라우드로 데이터 센터 확장하기 : 하이브리드 환경을 위한 연결 옵션 및 고려사항::강동환::AWS Summit Seoul 2018
클라우드로 데이터 센터 확장하기 : 하이브리드 환경을 위한 연결 옵션 및 고려사항::강동환::AWS Summit Seoul 2018
 
[Games on AWS 2019] AWS 입문자를 위한 초단기 레벨업 트랙 | AWS 레벨업 하기! : 네트워크 - 권신중 AWS 솔루션...
[Games on AWS 2019] AWS 입문자를 위한 초단기 레벨업 트랙 | AWS 레벨업 하기! : 네트워크 - 권신중 AWS 솔루션...[Games on AWS 2019] AWS 입문자를 위한 초단기 레벨업 트랙 | AWS 레벨업 하기! : 네트워크 - 권신중 AWS 솔루션...
[Games on AWS 2019] AWS 입문자를 위한 초단기 레벨업 트랙 | AWS 레벨업 하기! : 네트워크 - 권신중 AWS 솔루션...
 
Modern Enterprise 여정의 핵심 – SAP on AWS 마이그레이션-장현, AWS SAP Architect / 강병수, AWS...
Modern Enterprise 여정의 핵심 – SAP on AWS 마이그레이션-장현, AWS SAP Architect / 강병수, AWS...Modern Enterprise 여정의 핵심 – SAP on AWS 마이그레이션-장현, AWS SAP Architect / 강병수, AWS...
Modern Enterprise 여정의 핵심 – SAP on AWS 마이그레이션-장현, AWS SAP Architect / 강병수, AWS...
 
금융 회사를 위한 클라우드 이용 가이드 – 신은수 AWS 솔루션즈 아키텍트, 김호영 AWS 정책협력 담당:: AWS Cloud Week ...
금융 회사를 위한 클라우드 이용 가이드 –  신은수 AWS 솔루션즈 아키텍트, 김호영 AWS 정책협력 담당:: AWS Cloud Week ...금융 회사를 위한 클라우드 이용 가이드 –  신은수 AWS 솔루션즈 아키텍트, 김호영 AWS 정책협력 담당:: AWS Cloud Week ...
금융 회사를 위한 클라우드 이용 가이드 – 신은수 AWS 솔루션즈 아키텍트, 김호영 AWS 정책협력 담당:: AWS Cloud Week ...
 
AWS Tagging Strategy
AWS Tagging StrategyAWS Tagging Strategy
AWS Tagging Strategy
 
Cloud service lifecycle management
Cloud service lifecycle managementCloud service lifecycle management
Cloud service lifecycle management
 
Cloud Computing and Services | PPT
Cloud Computing and Services | PPTCloud Computing and Services | PPT
Cloud Computing and Services | PPT
 
Amazon RDS 살펴보기 (김용우) - AWS 웨비나 시리즈
Amazon RDS 살펴보기 (김용우) - AWS 웨비나 시리즈 Amazon RDS 살펴보기 (김용우) - AWS 웨비나 시리즈
Amazon RDS 살펴보기 (김용우) - AWS 웨비나 시리즈
 
Microservices With Istio Service Mesh
Microservices With Istio Service MeshMicroservices With Istio Service Mesh
Microservices With Istio Service Mesh
 
AWS Training For Beginners | AWS Certified Solutions Architect Tutorial | AWS...
AWS Training For Beginners | AWS Certified Solutions Architect Tutorial | AWS...AWS Training For Beginners | AWS Certified Solutions Architect Tutorial | AWS...
AWS Training For Beginners | AWS Certified Solutions Architect Tutorial | AWS...
 
MongoDB- Crud Operation
MongoDB- Crud OperationMongoDB- Crud Operation
MongoDB- Crud Operation
 

Similar to Rails request & middlewares

Rails in the bowels
Rails in the bowelsRails in the bowels
Rails in the bowelsCreditas
 
An Overview of the React Ecosystem
An Overview of the React EcosystemAn Overview of the React Ecosystem
An Overview of the React EcosystemFITC
 
Rails
RailsRails
RailsSHC
 
Lecture #5 Introduction to rails
Lecture #5 Introduction to railsLecture #5 Introduction to rails
Lecture #5 Introduction to railsEvgeniy Hinyuk
 
Introduction to Rails by Evgeniy Hinyuk
Introduction to Rails by Evgeniy HinyukIntroduction to Rails by Evgeniy Hinyuk
Introduction to Rails by Evgeniy HinyukPivorak MeetUp
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails SiddheshSiddhesh Bhobe
 
Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010arif44
 
React on rails v6.1 at LA Ruby, November 2016
React on rails v6.1 at LA Ruby, November 2016React on rails v6.1 at LA Ruby, November 2016
React on rails v6.1 at LA Ruby, November 2016Justin Gordon
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on RailsAlessandro DS
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Railshasan2000
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Railsanides
 
Web Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureWeb Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureToru Kawamura
 
How to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless EditionHow to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless Editionecobold
 
How to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless EditionHow to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless EditionLecole Cole
 

Similar to Rails request & middlewares (20)

Rails in the bowels
Rails in the bowelsRails in the bowels
Rails in the bowels
 
12 Introduction to Rails
12 Introduction to Rails12 Introduction to Rails
12 Introduction to Rails
 
An Overview of the React Ecosystem
An Overview of the React EcosystemAn Overview of the React Ecosystem
An Overview of the React Ecosystem
 
Rails
RailsRails
Rails
 
Lecture #5 Introduction to rails
Lecture #5 Introduction to railsLecture #5 Introduction to rails
Lecture #5 Introduction to rails
 
Introduction to Rails by Evgeniy Hinyuk
Introduction to Rails by Evgeniy HinyukIntroduction to Rails by Evgeniy Hinyuk
Introduction to Rails by Evgeniy Hinyuk
 
Rack
RackRack
Rack
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails Siddhesh
 
Aspose pdf
Aspose pdfAspose pdf
Aspose pdf
 
TorqueBox
TorqueBoxTorqueBox
TorqueBox
 
React on rails v4
React on rails v4React on rails v4
React on rails v4
 
Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010
 
RoR guide_p1
RoR guide_p1RoR guide_p1
RoR guide_p1
 
React on rails v6.1 at LA Ruby, November 2016
React on rails v6.1 at LA Ruby, November 2016React on rails v6.1 at LA Ruby, November 2016
React on rails v6.1 at LA Ruby, November 2016
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Web Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureWeb Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the future
 
How to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless EditionHow to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless Edition
 
How to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless EditionHow to Build a Big Data Application: Serverless Edition
How to Build a Big Data Application: Serverless Edition
 

Recently uploaded

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Recently uploaded (20)

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

Rails request & middlewares

  • 3.
  • 4. I do love to take photos https://www.flickr.com/photos/santoshwadghule/
  • 6. That’s it. Lets talk about the Rails Request
  • 7. What is a request?
  • 8. Request is a… • It is set of instructions that tells a server what kind of response we want. • It is a part of HTTP (request/response) protocol. • HTTP uses one of the verbs like GET, POST, PUT & DELETE when you perform the request to the server.
  • 10. Rails Request Life Cycle Browser Web Server Routes Controller Model View Database Rails App Middlewares App Server
  • 11. App Server & Rails App Server Rails Rack
  • 13. What is a Web Server? • Web Server is strictly HTTP based, it just takes HTTP requests and sends back HTTP responses to the clients(browsers). • It is mostly designed to serve static files. • It also has other functionality like request pipeline, load balancing etc. App servers lack these functionalities. • E.g. Ngnix, Apache
  • 15. What is an App Server? • App Server actually runs your Rails app. • App Server is mostly known for to serve dynamic pages. • E.g. Webrick, Passenger, Mongrel, Unicorn, Thin, Puma & etc.
  • 16. Request to Rails app • Rails isn’t just one application, it has lots of independent Rack applications (middlewares). • When request comes to the Rails app, it goes through the list of middleware series. • Last part of that series, sends request to the routes file.
  • 17. Request to Rails app • Based on request, Rails decides which controller & action need to be executed from the routes file. • After executing the controller’s action, Rails sends back response to the the client. • Web Server & App Server actually handle the job of sending response back to the proper client.
  • 19. What is a Middleware? • Middleware is a Rack application. • Middleware is basically a filter for request and response.
  • 20. Rails Middlewares App Server Rails App A B C D Routes Controller Models Views Here A, B, C & D are middlewares Each of these does processing on request & response
  • 21. Why Rails uses Middlewares? • Before rails 3, Rails was very tightly coupled. • As Rails was growing, apps built on Rails had more demanding requirements. For some apps, Rails gave lots of additional stuffs by default, which was not required like cookies/flash. For some other apps, to implement new filter on the the request/response was not possible. • In Rails 3 and after, all these issues have got solved by using a concept of Rack.
  • 22. Rack - The Webserver Interface
  • 23. What is a Rack? • Rack is not Rake. • Rack is simple but powerful spec. Yes it is just spec. • It is not web framework or web server. • Rack is created by Christian Neukirchen
  • 24. Rack - Just an Interface • It is an interface that sits between your web/app server and your application. It wraps HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks and software in between (i.e. middleware) into a single method call.
  • 25. Rack Specification • Specification: A Rack application is a Ruby object (not a class) that responds to `call`. It takes exactly one argument, the environment and returns an Array of three values, The status, the headers, and the body. That’s it.
  • 26. Why do we need Rack? • Rack promotes low coupling. • If there was’t Rack, then each framework had to add separate handler for Thin, Mongrel, Unicorn and etc to run the app on these servers. • In reality it’s not a job of framework. They should not need to take care of it.
  • 30. Using Middleware in a Rack app • Using ‘use’ method of Rack, you can use middleware component in Rack application. • You can use multiple middleware components which help to change request/response as you need. • You can add middlewares by using two methods. By directly adding middleware in config.ru and using Rack::Builder.
  • 32. Rack app + Middleware + config.ru
  • 34. What is Rack::Builder? • Rack::Builder implements a small DSL to iteratively construct Rack applications. • Rack::Builder is the thing that glues Rack middlewares and application together and converts them into single entity/rack application. • Under the hood, ‘rackup’ command converts your config.ru script to an instance of Rack::Builder.
  • 35. Rack app + Middleware + Rack::Builder
  • 37. Rails on Rack • Rails application is the primary Rack application object. • It has ‘call’ method similar to rack’s ‘call’ method in its source code (i.e. in Rails::Application).
  • 38. Rails’ Rack::Builder • Same like Rack::Builder, we have similar concept in Rails, it is called as ActionDispatch::MiddlewareStack. • Better flexibility and more features to meet Rails’ requirement.
  • 39. Rails’ Rack::Builder • Rails::Application uses ActionDispatch::MiddlewareStack to combine various internal and external middlewares to form a complete Rails Rack application.
  • 40. Inspecting Rails Middlewares • Rails provides a task for inspecting the middleware stack in use. • $ bin/rake middleware
  • 41. $ bin/rake middleware Note: List of the middlewares may be different for your Rails app
  • 42. Using Middleware in Rails • Rails provides a simple configuration interface config.middleware for adding, removing and modifying the middlewares in the middleware stack via application.rb or the environment specific configuration file environments/<environment>.rb. • Using these methods config.middleware.use, config.middleware.insert_before, config.middleware.insert_after, you can add new middleware to the middleware stack. • It also provides ‘swap’ and ‘delete’ methods for swapping and deleting a middleware.
  • 43. Add this file under config/initializers directory And under config/application.rb file, add this following line config.middleware.use "SayHelloMiddlware"
  • 44. Always Remember That… • When request comes to your Rails app, it goes through these middlewares. From top to bottom. • At the bottom, request enters into the your Rails’ MVC area.

Editor's Notes

  1. I’m a software developer.
  2. I’m a great fan of this watch, Casio f-91W.
  3. In simple way, when we hit any url in the browser for some file, that browser converts that url into the request message and sends to the server and that request message is your actual request :) When you want to get some data from the server, you use GET method. When we want to create new data on the server, we use POST method. When we want to update data like username we use PUT method. For destroying the data we use DELETE verb. There are also other methods like, HEAD, PATCH, OPTIONS, CONNECT & ETC which HTTP protocol provides.
  4. This is a basic and standard diagram of Rails Request Life Cycle. You can see here, When browser initiates the requests it goes to Web Server, From the Web Server It goes through the App server, From App Server, request enters into the Rails app. Now if you see in the Rails app, request goes through the series of middlewares, From there request goes to the routes file and Based on request, Rails decides which controller & action need to be executed from the routes file. Now in controller if there is any business logic, it goes to model and from there it will fetch data from database or store the data in the database. If there any view like html, then request goes to view. After processing it, controller sends back the response to Browser.
  5. In this diagram, I’m showing how app server and rails app communicate with each other. Communications between App Server and Rails app happen using Rack. Rack is a gem and acts as an interface between them. We will see more on rack in next slides.
  6. It recognises Ruby application request and then it forwards its request to app server.
  7. Web Server forwards its request to the App Server, and App Server in turn forwards that request to the Rails app. In development mode, App Server can play role of web server too. In production it does not scale too much so we need web server in between.
  8. This is all about basics of Rails request life cycle. Now lets see how rails handles the request under the hood.
  9. You can think of middlewares isolate the different stages of processing on the request and response. One of the best things of Rack, you customise request/response very easily, by chaining middleware components in between the app server and the rails app.
  10. Before Rails 3, handling of session, parsing for parameters and etc were too difficult.
  11. Rake is “Make for Ruby” and it is task runner for Ruby.
  12. Argument environment is nothing but environmental variables hash like PATH_INFO, QURY_STRING, REMOTE_ADDR, REQUEST_URI and all that junk. You can say this environment variable has all information of the request.
  13. Using low coupling, you can replace any component with another one without having to reimplement code.
  14. Here is a simple example of rack application.
  15. This is another way to write rack application using rackup command which is given by Rack. The only thing you need is, to write your code in config.ru and run it using rackup config.ru.
  16. In this code, I have defined rack application using MyRackApp and I have defined one middleware using MyMiddleware class. When you want to apply middleware to your rack application you have use ‘use’ method of Rack. When request comes, it comes from top to bottom. Means from the middleware to the actual rack application. Always remember that, middleware’s initialize method always takes an argument i.e. app that app is nothing but your next middleware or next rack application.
  17. Think of Rack::Builder object as stack in which your actual rack application is at bottom and all middlewares on top of it. The whole stack you can call it as rack application too.
  18. Many of Action Dispatcher’s internal components are implemented as Rack middleware.
  19. You can inspect middleware stack of your rails application by using
  20. This list is quite big, So I’m not going to explain what each of these middleware does here. But there is one middleware, I think most of you have seen it, that is CheckPending. Anyone knows what it does?
  21. Lets write one middleware in the rails app. I mostly prefer to write middleware in config/initializers folder. In this middleware, mostly in call method, if request_path is ‘say_hello’, then this middleware will send this response back to the client. So here, our rails app will get called. If request_path ‘say_hello’ then our rails app gets called. To add this middleware in rails’s middleware stack, we need to set middleware to config.middleware.use or….config.middleware.insert_after But when we use this config.middleware.use then that middleware will get applied at the bottom of rails middleware series.