Rails Controller-Specific Middleware

Rails Controller-Specific Middleware

Did you know you can set controller-specific middleware in your Rails controller with the use method? I found this while looking through the docs for ActionController::Metal.

https://api.rubyonrails.org/classes/ActionController/Metal.html#method-c-use

An example of usage might look like this (from the docs):

class PostsController < ApplicationController
  use AuthenticationMiddleware, except: [:index, :show]
end

You can also see what a controller’s middleware stack looks like with the middleware method: https://api.rubyonrails.org/classes/ActionController/Metal.html#method-c-middleware

Of course, using a bunch of custom middleware all over the place is probably not a good idea, but this feels like one of those things that’s good to have filed away for when you might come across a case for it.