SlideShare a Scribd company logo
1 of 11
1 / 11
Rack
2 / 11
What is rack?
Rack is a webserver interface. It means Rack is an editable list of
components that every request goes through in order to build the
response(HTML page).
3 / 11
How rack works?
4 / 11

When we start (rails s), a web server is launched and receives request
from browser. The web server then submit that request to Rack, which
then processes the request and builds the response that the web server
will send back to the client(browser).

When we create a new rails project, it comes with 23 rack middlewares.
To view - run command (rake middleware) at the root of the rails project.
5 / 11
How to use Rack

To create a middleware, you need an object that responds to (call(env))
function and returns an array that will then be sent to the browser. The
array exactly consists of three things -
1. Status code(200, 302, 404, ...)
2. A hash containing the header.
3. The body(Needs to be enumerable via # each)
6 / 11
Creating a rack middleware
To create your own rack you need to follow these steps:

create a folder in app/ named middleware

create a file called my_middleware.rb and fill it up with these lines of code.

In your application.rb add
class MyMiddleware
def initialize(app)
end
def call(env)
[200, {"Content-Type" => "text/html"}, ["Hello Rack!"]]
end
end

Now start the server and run application in the browser.

You always get the welcome message - "Hello Rack!" whatever
path you hit in the bowser.
config.middleware.insert_before Rack::Sendfile, 'MyMiddleware'
7 / 11

Because Rails builds the middleware list through
ActionDispatch::MiddlewareStack. By doing so, it adds another rule
to the middleware: MiddlewareStack and initializes every middleware by
passing an argument app to the object.

The (env) variable is the current environment built for that request. Its
the glue between middlewares, the only varaible that will be persisted. If
you set something in there, other middlewares will be able to access it,
even the controller.

The app parameter during the initialization is actually the next
middleware in the chain. By not calling (@app.call(env)), rack was
stopped at the very first middleware and returned our value.
8 / 11
Now change your MyMiddleware class by this code.
class MyMiddleware
def initialize(app)
end
@app = app #Store the app to call it down the stack end
def call(env)
# Initialize stuff before entering 'rails'
# Retrieve a connection form a pool (Redis, Memcache, etc.)
# Authentication/authorization/tenancy setup needs to be done before
# Remember, you can set stuff in env and then access it in your controller.
# The response has the same structure as before:
# [200, {"Content-Type" => "text/html"}, ["Hello Rack!"]]
# The header is now fully populated and instead of the "Hello Rack!",
# the body is a full HTML page.
# @app.call will call ActionDispatch::Static which, in turn,
will call ActiveSupport::CacheStrategy which will
# call Rack::Runtime and so on up to your controller/view.
response = @app.call(env)
end
end
9 / 11
And your application starts behaving normally.
Lets better understand the situation with AUTHENTICATION AND
AUTHORIZATION
Now change your middleware code by this:
class MyMiddleware
def initialize(app)
@app = app #the next middleware to be called
@fallback = RestrictedController
end
def call(env)
result = catch(:restricted) do
@app.call(env)
end
if result.nil?
@fallback.call(env)
else
result
end
end
end
10 / 11
Add this method on application controller
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def restrict!
throw :restricted
end
end
Add a controller - (restricted_controller)
class RestrictedController < ActionController::Base
def self.call(env)
action(:respond).call(env)
end
def respond
flash.alert = "Couldn't access the resource"
redirect_to root_url
end
end
The middleware calls the class method RestrictedController.call.
In any of your controller, if you call restrict!, it will throw an error that will
becaught(:restricted) by your rack application. When the error is raised,
the fallback application will be called.
11 / 11
Thank you !!
Ashish Garg
Sonu Kumar
Aakanksha Bhardwaj

More Related Content

What's hot

Create a fake REST API without writing a single line of code
Create a fake REST API without writing a single line of codeCreate a fake REST API without writing a single line of code
Create a fake REST API without writing a single line of codeYashobanta Bai
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life CycleAbhishek Sur
 
Using mule with web services
Using mule with web servicesUsing mule with web services
Using mule with web servicesShanky Gupta
 
Flask & Flask-restx
Flask & Flask-restxFlask & Flask-restx
Flask & Flask-restxammaraslam18
 
Capistrano Deployment By Nyros Developer
Capistrano Deployment By Nyros DeveloperCapistrano Deployment By Nyros Developer
Capistrano Deployment By Nyros DeveloperNyros Technologies
 
Mulesoft Calling Flow of Other Applications
Mulesoft Calling Flow of Other ApplicationsMulesoft Calling Flow of Other Applications
Mulesoft Calling Flow of Other Applicationskumar gaurav
 
Deploying and running in mule standalone
Deploying and running in mule standaloneDeploying and running in mule standalone
Deploying and running in mule standaloneAnirban Sen Chowdhary
 
What's new in Rails 5 - API Mode & Action Cable overview
What's new in Rails 5 - API Mode & Action Cable overviewWhat's new in Rails 5 - API Mode & Action Cable overview
What's new in Rails 5 - API Mode & Action Cable overviewMaxim Veksler
 
Remote Config REST API and Versioning
Remote Config REST API and VersioningRemote Config REST API and Versioning
Remote Config REST API and VersioningJumpei Matsuda
 
Pretenders talk at PyconUK 2012
Pretenders talk at PyconUK 2012Pretenders talk at PyconUK 2012
Pretenders talk at PyconUK 2012txels
 
Salesforce ANT migration
Salesforce ANT migration Salesforce ANT migration
Salesforce ANT migration Cloud Analogy
 
One does not simply "Upgrade to Rails 3"
One does not simply "Upgrade to Rails 3"One does not simply "Upgrade to Rails 3"
One does not simply "Upgrade to Rails 3"testflyjets
 
From Web Developer to Hardware Developer
From Web Developer to Hardware DeveloperFrom Web Developer to Hardware Developer
From Web Developer to Hardware Developeralexshenoy
 
Scatter and gather in mule
Scatter and gather in muleScatter and gather in mule
Scatter and gather in muleRajkattamuri
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T Spatinijava
 
Mule esb add logger to existing flow
Mule esb add logger to existing flowMule esb add logger to existing flow
Mule esb add logger to existing flowGermano Barba
 
Weblogic as a windows service
Weblogic as a windows serviceWeblogic as a windows service
Weblogic as a windows serviceRavi Kumar Lanke
 

What's hot (20)

Create a fake REST API without writing a single line of code
Create a fake REST API without writing a single line of codeCreate a fake REST API without writing a single line of code
Create a fake REST API without writing a single line of code
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life Cycle
 
Using mule with web services
Using mule with web servicesUsing mule with web services
Using mule with web services
 
Flask & Flask-restx
Flask & Flask-restxFlask & Flask-restx
Flask & Flask-restx
 
Capistrano Deployment By Nyros Developer
Capistrano Deployment By Nyros DeveloperCapistrano Deployment By Nyros Developer
Capistrano Deployment By Nyros Developer
 
Mule esb soap_service
Mule esb soap_serviceMule esb soap_service
Mule esb soap_service
 
Mulesoft Calling Flow of Other Applications
Mulesoft Calling Flow of Other ApplicationsMulesoft Calling Flow of Other Applications
Mulesoft Calling Flow of Other Applications
 
Deploying and running in mule standalone
Deploying and running in mule standaloneDeploying and running in mule standalone
Deploying and running in mule standalone
 
What's new in Rails 5 - API Mode & Action Cable overview
What's new in Rails 5 - API Mode & Action Cable overviewWhat's new in Rails 5 - API Mode & Action Cable overview
What's new in Rails 5 - API Mode & Action Cable overview
 
Event Source On Labs
Event Source On LabsEvent Source On Labs
Event Source On Labs
 
Remote Config REST API and Versioning
Remote Config REST API and VersioningRemote Config REST API and Versioning
Remote Config REST API and Versioning
 
Pretenders talk at PyconUK 2012
Pretenders talk at PyconUK 2012Pretenders talk at PyconUK 2012
Pretenders talk at PyconUK 2012
 
Salesforce ANT migration
Salesforce ANT migration Salesforce ANT migration
Salesforce ANT migration
 
One does not simply "Upgrade to Rails 3"
One does not simply "Upgrade to Rails 3"One does not simply "Upgrade to Rails 3"
One does not simply "Upgrade to Rails 3"
 
From Web Developer to Hardware Developer
From Web Developer to Hardware DeveloperFrom Web Developer to Hardware Developer
From Web Developer to Hardware Developer
 
Scatter and gather in mule
Scatter and gather in muleScatter and gather in mule
Scatter and gather in mule
 
Mule message enricher
Mule message enricherMule message enricher
Mule message enricher
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
 
Mule esb add logger to existing flow
Mule esb add logger to existing flowMule esb add logger to existing flow
Mule esb add logger to existing flow
 
Weblogic as a windows service
Weblogic as a windows serviceWeblogic as a windows service
Weblogic as a windows service
 

Similar to Rack

Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails DevsDiacode
 
Web Server and how we can design app in C#
Web Server and how we can design app  in C#Web Server and how we can design app  in C#
Web Server and how we can design app in C#caohansnnuedu
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache TomcatAuwal Amshi
 
Rails Request & Middlewares
Rails Request & MiddlewaresRails Request & Middlewares
Rails Request & MiddlewaresSantosh Wadghule
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Dilouar Hossain
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Example Cosmos SDK Application Tutorial
Example Cosmos SDK Application TutorialExample Cosmos SDK Application Tutorial
Example Cosmos SDK Application TutorialJim Yang
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Railsanides
 
Html servlet example
Html   servlet exampleHtml   servlet example
Html servlet examplervpprash
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices ArchitectureIdan Fridman
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoasZeid Hassan
 
Getting Started with React v16
Getting Started with React v16Getting Started with React v16
Getting Started with React v16Benny Neugebauer
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and ServletsRaghu nath
 

Similar to Rack (20)

Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
 
Web Server and how we can design app in C#
Web Server and how we can design app  in C#Web Server and how we can design app  in C#
Web Server and how we can design app in C#
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Dev streams2
Dev streams2Dev streams2
Dev streams2
 
Rails Request & Middlewares
Rails Request & MiddlewaresRails Request & Middlewares
Rails Request & Middlewares
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Example Cosmos SDK Application Tutorial
Example Cosmos SDK Application TutorialExample Cosmos SDK Application Tutorial
Example Cosmos SDK Application Tutorial
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
RoR guide_p1
RoR guide_p1RoR guide_p1
RoR guide_p1
 
Html servlet example
Html   servlet exampleHtml   servlet example
Html servlet example
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices Architecture
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
 
Getting Started with React v16
Getting Started with React v16Getting Started with React v16
Getting Started with React v16
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
11-DWR-and-JQuery
11-DWR-and-JQuery11-DWR-and-JQuery
11-DWR-and-JQuery
 

Recently uploaded

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 

Recently uploaded (20)

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 

Rack

  • 2. 2 / 11 What is rack? Rack is a webserver interface. It means Rack is an editable list of components that every request goes through in order to build the response(HTML page).
  • 3. 3 / 11 How rack works?
  • 4. 4 / 11  When we start (rails s), a web server is launched and receives request from browser. The web server then submit that request to Rack, which then processes the request and builds the response that the web server will send back to the client(browser).  When we create a new rails project, it comes with 23 rack middlewares. To view - run command (rake middleware) at the root of the rails project.
  • 5. 5 / 11 How to use Rack  To create a middleware, you need an object that responds to (call(env)) function and returns an array that will then be sent to the browser. The array exactly consists of three things - 1. Status code(200, 302, 404, ...) 2. A hash containing the header. 3. The body(Needs to be enumerable via # each)
  • 6. 6 / 11 Creating a rack middleware To create your own rack you need to follow these steps:  create a folder in app/ named middleware  create a file called my_middleware.rb and fill it up with these lines of code.  In your application.rb add class MyMiddleware def initialize(app) end def call(env) [200, {"Content-Type" => "text/html"}, ["Hello Rack!"]] end end  Now start the server and run application in the browser.  You always get the welcome message - "Hello Rack!" whatever path you hit in the bowser. config.middleware.insert_before Rack::Sendfile, 'MyMiddleware'
  • 7. 7 / 11  Because Rails builds the middleware list through ActionDispatch::MiddlewareStack. By doing so, it adds another rule to the middleware: MiddlewareStack and initializes every middleware by passing an argument app to the object.  The (env) variable is the current environment built for that request. Its the glue between middlewares, the only varaible that will be persisted. If you set something in there, other middlewares will be able to access it, even the controller.  The app parameter during the initialization is actually the next middleware in the chain. By not calling (@app.call(env)), rack was stopped at the very first middleware and returned our value.
  • 8. 8 / 11 Now change your MyMiddleware class by this code. class MyMiddleware def initialize(app) end @app = app #Store the app to call it down the stack end def call(env) # Initialize stuff before entering 'rails' # Retrieve a connection form a pool (Redis, Memcache, etc.) # Authentication/authorization/tenancy setup needs to be done before # Remember, you can set stuff in env and then access it in your controller. # The response has the same structure as before: # [200, {"Content-Type" =&gt; "text/html"}, ["Hello Rack!"]] # The header is now fully populated and instead of the "Hello Rack!", # the body is a full HTML page. # @app.call will call ActionDispatch::Static which, in turn, will call ActiveSupport::CacheStrategy which will # call Rack::Runtime and so on up to your controller/view. response = @app.call(env) end end
  • 9. 9 / 11 And your application starts behaving normally. Lets better understand the situation with AUTHENTICATION AND AUTHORIZATION Now change your middleware code by this: class MyMiddleware def initialize(app) @app = app #the next middleware to be called @fallback = RestrictedController end def call(env) result = catch(:restricted) do @app.call(env) end if result.nil? @fallback.call(env) else result end end end
  • 10. 10 / 11 Add this method on application controller class ApplicationController < ActionController::Base protect_from_forgery with: :exception def restrict! throw :restricted end end Add a controller - (restricted_controller) class RestrictedController < ActionController::Base def self.call(env) action(:respond).call(env) end def respond flash.alert = "Couldn't access the resource" redirect_to root_url end end The middleware calls the class method RestrictedController.call. In any of your controller, if you call restrict!, it will throw an error that will becaught(:restricted) by your rack application. When the error is raised, the fallback application will be called.
  • 11. 11 / 11 Thank you !! Ashish Garg Sonu Kumar Aakanksha Bhardwaj