Last active
February 4, 2019 03:55
-
-
Save adamcrown/91992ab8ec2a79099b8a to your computer and use it in GitHub Desktop.
An example of baking our own middleware stack to better understand how Rack middleware works.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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.