Rack Middleware and ActionController Filters are really completely different.
Rack is the standard Ruby web server interface. It is designed to work in such a way that Rack or "Middlewares" applications can be connected together with each other, each of which transforms the request / response in a certain way. If you create / use Rack middleware, you get the opportunity to convert the request before it actually reaches the Rails application.
ActionController filters are just before / after intercepts that run before or after your immediate controller methods in Rails. They will be called immediately before or after your controller method, but after all the rest of the Rails stack.
Therefore, there are significant differences in capabilities with the Rack middleware and the ActionController filter, namely, since the Rack middleware runs before your application code, it will not run in the same area as your application code β for example, you cannot use your application models, etc., unless you explicitly require them and do not perform the necessary initialization (for example, establishing a connection to the database).
If you are looking for rules of thumb from the top of my head, I would tell you:
If you want to do something with the request before the methods only in a specific controller, use the filter in this controller before that.
If you want to do something with a request before all the controller methods in your application, and what you want to do is very specific to your application or depends on your application code, use the filter on your ApplicationController.
If you want to do something in common with a request that is not tied to your application code at all, and you imagine that it would be nice to be able to reuse this in another application, middleware for the rack is better suited.
Hope this helps.
Andrew
source share