Difference on handling a HTTP request using middlewares and controllers
I am using Ruby on Rails 3 and I would like to know what difference there is on handling a HTTP request using middlewares (intercepting the request URL request and performing the response) than controllers flow (using respond_to
).
Inspecting the log file, I can see that middlewares load and query almost as if you were calling controller methods. This is 开发者_如何学运维because, in the latter case (calling controllers), RoR does not render template files (it is a "automatic process"?!) if the HTTP request is for JSON data.
So, what do you think about?
One of the biggest advantages to using Rack Middleware is that you can filter the response--e.g., modify it in some way and then let it take its normal course. Take a look at rake middleware
in a standard Rails 3 application to see all the middleware stack Rails uses to do things like sessions, flash storage, and even routing based on your application's own routes.rb
. Of course, a middleware may also terminate the response filtering and act as a request endpoint, if necessary.
A feature similar to middleware, but that acts as an endpoint, is Rails Metal, allowing you to get some extra performance out of your app if necessary (assuming you don't need the full Rails stack).
I recommend you check out the following Railscasts:
- Episode 150: Rails Metal: Railscast | ASCIIcast
- Episode 151: Rack Middleware: Railscast | ASCIIcast
精彩评论