An example of baking our own middleware stack to better understand how Rack middleware works.
class Talk | |
def call(env) | |
"Can I talk to #{env[:name]}!" | |
end | |
end | |
class Shout | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
@app.call(env).upcase | |
end | |
end | |
class Zuul | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
"There is no #{env[:name]}. Only Zuul!" | |
end | |
end | |
def run_the_stack(middleware, app, env) | |
prev_app = app | |
middleware.reverse.each do |part| | |
part = part.new(prev_app) | |
prev_app = part | |
end | |
prev_app.call(env) | |
end | |
puts run_the_stack [Shout, Zuul], Talk.new, name: 'Dana' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
I like your post about Rack, especially the
run_the_stack
method, which helped me a lot to understand the basic concept. And I wonder if I could see the app(which attaches to Rack) as just one of the middlewares? Since its#call(env)
method is the last one get executed , so it needs a different structure as the others. I don't know if this is a proper understanding.