Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails middleware: add middleware to config.ru or to the config.middleware array?

I want to clarify the config.ru file to specify rack middleware as opposed to using the config.middleware array.

If a config.ru typically looks like this:

require ::File.expand_path('../config/environment',  __FILE__)
use Rack::Deflater
run TestApp::Application

Am I correct in saying that when I run TestApp::Application, I enter into Rails internal middleware? That is, does it begins the chain of middleware defined in config.middleware?

So the effective use of specifying middleware outside the rails application is to do things with the request (or response) external to rails itself? So in this example Deflator acts on the request before the rails app middleware begins?

And the effective use of using config.middelware is to specify more rails specific middleware that can be placed anywhere within that chain?

Also, when the rack application begins, what is the app? (That is passed into the initialize for a rack application?). I always thought app was the rails app itself, but it seems that the rails app is just another middelware in the chain.

like image 367
stantona Avatar asked Nov 12 '22 19:11

stantona


1 Answers

The rails app is not a Rails middleware but a Rack app. It's the bottom of the middleware chain (denoted by the run instead of use).

I'm not quite sure about the order in which the app.config.middleware array gets run vs whatever you put in the config.ru file, but I expect that the require ::File.expand_path('../config/environment', __FILE__) line requires a file somewhere that loops through the middleware array and calls use on all of them to add them to rack's list. I'd specify middleware in the config.middleware array to ensure it gets placed where you want.

I don't think there's a difference between "Rails-specific" and "rack" middleware, either. It all gets run in one giant chain until you hit the rails app. In fact, a lot of Rails's functionality is in the form of middleware (you can see the entire list if you type in rake middleware into the command line).

like image 146
hurshagrawal Avatar answered Nov 15 '22 10:11

hurshagrawal