Skip to content

Instantly share code, notes, and snippets.

@adamcrown
Last active February 4, 2019 03:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcrown/91992ab8ec2a79099b8a to your computer and use it in GitHub Desktop.
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.
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'
@xullnn
Copy link

xullnn commented Feb 4, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment