Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is middleware when referenced in the context of Ruby on Rails?

Tags:

I often hear the term 'middleware' in the context of Ruby on Rails. What exactly is it? Can you provide specific examples?

like image 618
randombits Avatar asked Jul 09 '10 23:07

randombits


People also ask

What is middleware in Ruby on Rails?

A middleware component sits between the client and the server, processing inbound requests and outbound responses, but it's more than interface that can be used to talk to web server. It's used to group and order modules, which are usually Ruby classes, and specify dependency between them.

What is the purpose of Ruby on Rails?

Rails is a development tool which gives web developers a framework, providing structure for all the code they write. The Rails framework helps developers to build websites and applications, because it abstracts and simplifies common repetitive tasks.

Is Ruby on Rails a backend framework?

Ruby on Rails is used as a backend framework for web applications. It's known for efficiency and scalability. You can write rich functionality with much fewer lines of code as opposed to what you'd need in Java or Node.

Is Ruby on Rails a library or framework?

Ruby on Rails (or "Rails") is an open-source web application development framework written in the Ruby programming language. It's one of the most popular Ruby libraries and one of the top reasons developers choose to learn Ruby.


1 Answers

Middleware is related to Rack, the standard Ruby API for web applications. Since Rails applications are Rack applications these days, they apply to both.

Rack middleware is everything between application servers (Webrick, Thin, Unicorn, Passenger, ...) and the actual application, such as your Rails application. It is the pipeline between the web application server and the application itself.

The input to a Rack application is an "environment" which contains all the HTTP request details (and more). The output is a HTTP response. Middleware layers are like filters which can modify the input, the output or both. Rails uses middleware to implement some of its features (query caching, cookie stores, http method expansion), but you can add your own.

Rack middleware is an effective way to reuse simple web-related behavior across web applications that use Rack, regardless of the underlying framework. If a part of your application adds functionality, but is not responsible for a HTTP response, it qualifies as Rack middleware.

Some examples of things you could implement as Rack middleware include:

  • HTTP caching (server side and client side)
  • Logging
  • Authentication
  • Monitoring
  • HTTP header filtering

See also this SO question.

like image 51
molf Avatar answered Oct 18 '22 20:10

molf