Rails & Rack Middleware

by Melvin Ram

Notes from RailsCasts Rack Middleware screencast

  • Rack Middleware = filter which you can use to intercept a request and handle the behavior a little differently as it goes to and from the application
  • Different between middleware & metal = Metal is an endpoint & middleware is designed to be more of a filter (changes behavior if it needs to.)
  • Goes into /lib directory as a .rb file?
  • All middleware takes a initialize(app) method. The app variable will hold the rails application
  • Adding a call(env) method will make it override rails. This needs to return a array with the same 3 elements as a metal.
  • to make rails use your middleware, add this to your environment.rb file inside the Initializer block: config.middleware.use “NameOfClass”
  • ‘rake middleware’ will list out the middlewares used by your app
  • You’ll need to restart the server every time you create/change  a middleware
  • To execute your rails app from your middleware, just run .call on the rails app, ex: @app.call(env)
  • you can assign parts of the response from a rails app to variables using something like this:
  • status, headers, response = @app.call(env)
  • and then you can call return those back to the real response using something like this:
  • [status, headers, "Add stuff" + response.body]
  • response.body assumes that the app is a rails app. this is not best practice.
  • a better approach is to use [status, headers, self] together with def each(&block)

Leave a Comment