Skip to content

Instantly share code, notes, and snippets.

@v2e4lisp
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save v2e4lisp/9416556 to your computer and use it in GitHub Desktop.

Select an option

Save v2e4lisp/9416556 to your computer and use it in GitHub Desktop.
How rack works
# Pseudo app
use M1
use M2
use M3
run app
# middle ware are stored in order
[M1, M2, M3]
# Then Rack call #to_app method to make a rack app containing
# all middleware as a whole
# Two steps.
# First, reverse the middleware array
[M3, M2, M1]
# Then pass the app down to initialize every middleware
rack_app = M1.new M2.new M3.new app
# There, you got a complete rack app
# Rack_app will handle the request
# and return the response which orignally returned by your app in most case.
# That is to say
# 1. M1 call app.call(env) which will trigger M2 and get the response, return a new one.
# 2. M2 call app.call(env) which will trigger M3 and get the response, return a new one.
# 3. M3 call app.call(env) which will trigger app and get the response, return a new one.
# 4. app return the response.
# Pseudo app
use M1
use M2
map "/sub" do
use M3
run subapp
end
use M4
run app
# map itself will create a middleware
# this middleware has only one responsibility
# dispatching the request.
#
# it checks the request's url
# if url not matched it passes the request down to
# the next global middleware or your app
# otherwise passs the request to the next inner minddle.
# So at last you get a rack app like the following
rack_app = M4.new Msub.new M2.new M1.new app
# request to "/"
# M1 -> M2 -> M4 -> app
# request to "/sub"
# M1 -> M2 -> M3 -> subapp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment