h2. Rails on Rack

This guide covers Rails integration with Rack and interfacing with other Rack components. By referring to this guide, you will be able to:

* Create Rails Metal applications
* Use Rack Middlewares in your Rails applications
* Understand Action Pack's internal Middleware stack
* Define a custom Middleware stack

endprologue.

WARNING: This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares, url maps and +Rack::Builder+.

h3. Introduction to Rack

bq. Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.

- "Rack API Documentation":http://rack.rubyforge.org/doc/

Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the "Resources":#resources section below.

h3. Rails on Rack

h4. Rails Application's Rack Object

<tt>ActionController::Dispatcher.new</tt> is the primary Rack application object of a Rails application. Any Rack compliant web server should be using +ActionController::Dispatcher.new+ object to serve a Rails application.

h4. +rails server+

<tt>rails server</tt> does the basic job of creating a +Rack::Builder+ object and starting the webserver. This is Rails' equivalent of Rack's +rackup+ script.

Here's how +rails server+ creates an instance of +Rack::Builder+

<ruby>
app = Rack::Builder.new {
  use Rails::Rack::LogTailer unless options[:detach]
  use Rails::Rack::Debugger if options[:debugger]
  use ActionDispatch::Static
  run ActionController::Dispatcher.new
}.to_app
</ruby>

Middlewares used in the code above are primarily useful only in the development environment. The following table explains their usage:

|_.Middleware|_.Purpose|
|+Rails::Rack::LogTailer+|Appends log file output to console|
|+ActionDispatch::Static+|Serves static files inside +Rails.root/public+ directory|
|+Rails::Rack::Debugger+|Starts Debugger|

h4. +rackup+

To use +rackup+ instead of Rails' +rails server+, you can put the following inside +config.ru+ of your Rails application's root directory:

<ruby>
# Rails.root/config.ru
require "config/environment"

use Rails::Rack::LogTailer
use ActionDispatch::Static
run ActionController::Dispatcher.new
</ruby>

And start the server:

<shell>
$ rackup config.ru
</shell>

To find out more about different +rackup+ options:

<shell>
$ rackup --help
</shell>

h3. Action Controller Middleware Stack

Many of Action Controller's internal components are implemented as Rack middlewares. +ActionController::Dispatcher+ uses +ActionController::MiddlewareStack+ to combine various internal and external middlewares to form a complete Rails Rack application.

NOTE: +ActionController::MiddlewareStack+ is Rails' equivalent of +Rack::Builder+, but built for better flexibility and more features to meet Rails' requirements.

h4. Inspecting Middleware Stack

Rails has a handy rake task for inspecting the middleware stack in use:

<shell>
$ rake middleware
</shell>

For a freshly generated Rails application, this might produce something like:

<ruby>
use Rack::Lock
use ActionController::Failsafe
use ActionController::Session::CookieStore, , {:secret=>"<secret>", :session_key=>"_<app>_session"}
use Rails::Rack::Metal
use ActionDispatch::RewindableInput
use ActionController::ParamsParser
use Rack::MethodOverride
use Rack::Head
use ActiveRecord::QueryCache
run ActionController::Dispatcher.new
</ruby>

Purpose of each of this middlewares is explained in the "Internal Middlewares":#internal-middleware-stack section.

h4. Configuring Middleware Stack

Rails provides a simple configuration interface +config.middleware+ for adding, removing and modifying the middlewares in the middleware stack via +environment.rb+ or the environment specific configuration file <tt>environments/&lt;environment&gt;.rb</tt>.

h5. Adding a Middleware

You can add a new middleware to the middleware stack using any of the following methods:

* <tt>config.middleware.use(new_middleware, args)</tt> - Adds the new middleware at the bottom of the middleware stack.

* <tt>config.middleware.insert_before(existing_middleware, new_middleware, args)</tt> - Adds the new middleware before the specified existing middleware in the middleware stack.

* <tt>config.middleware.insert_after(existing_middleware, new_middleware, args)</tt> - Adds the new middleware after the specified existing middleware in the middleware stack.

<ruby>
# config/environment.rb

# Push Rack::BounceFavicon at the bottom
config.middleware.use Rack::BounceFavicon

# Add Lifo::Cache after ActiveRecord::QueryCache.
# Pass { :page_cache => false } argument to Lifo::Cache.
config.middleware.insert_after ActiveRecord::QueryCache, Lifo::Cache, :page_cache => false
</ruby>

h5. Swapping a Middleware

You can swap an existing middleware in the middleware stack using +config.middleware.swap+.

<ruby>
# config/environment.rb

# Replace ActionController::Failsafe with Lifo::Failsafe
config.middleware.swap ActionController::Failsafe, Lifo::Failsafe
</ruby>

h5. Middleware Stack is an Array

The middleware stack behaves just like a normal +Array+. You can use any +Array+ methods to insert, reorder, or remove items from the stack. Methods described in the section above are just convenience methods.

For example, the following removes the middleware matching the supplied class name:

<ruby>
config.middleware.delete(middleware)
</ruby>

h4. Internal Middleware Stack

Much of Action Controller's functionality is implemented as Middlewares. The following table explains the purpose of each of them:

|_.Middleware|_.Purpose|
|+Rack::Lock+|Sets <tt>env["rack.multithread"]</tt> flag to +true+ and wraps the application within a Mutex.|
|+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.|
|+ActiveRecord::QueryCache+|Enables the Active Record query cache.|
|+ActionController::Session::CookieStore+|Uses the cookie based session store.|
|+ActionController::Session::MemCacheStore+|Uses the memcached based session store.|
|+ActiveRecord::SessionStore+|Uses the database based session store.|
|+Rack::MethodOverride+|Sets HTTP method based on +_method+ parameter or <tt>env["HTTP_X_HTTP_METHOD_OVERRIDE"]</tt>.|
|+Rack::Head+|Discards the response body if the client sends a +HEAD+ request.|

TIP: It's possible to use any of the above middlewares in your custom Rack stack.

h4. Customizing Internal Middleware Stack

It's possible to replace the entire middleware stack with a custom stack using <tt>ActionController::Dispatcher.middleware=</tt>.

Put the following in an initializer:

<ruby>
# config/initializers/stack.rb
ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new do |m|
  m.use ActionController::Failsafe
  m.use ActiveRecord::QueryCache
  m.use Rack::Head
end
</ruby>

And now inspecting the middleware stack:

<shell>
$ rake middleware
(in /Users/lifo/Rails/blog)
use ActionController::Failsafe
use ActiveRecord::QueryCache
use Rack::Head
run ActionController::Dispatcher.new
</shell>

h4. Using Rack Builder

The following shows how to replace use +Rack::Builder+ instead of the Rails supplied +MiddlewareStack+.

<strong>Clear the existing Rails middleware stack</strong>

<ruby>
# environment.rb
config.middleware.clear
</ruby>

<br />
<strong>Add a +config.ru+ file to +Rails.root+</strong>

<ruby>
# config.ru
use MyOwnStackFromStratch
run ActionController::Dispatcher.new
</ruby>

h3. Resources

h4. Learning Rack

* "Official Rack Website":http://rack.github.com
* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html
* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/ruby-on-rack-1-hello-rack
* "Ruby on Rack #2 - The Builder":http://m.onkey.org/ruby-on-rack-2-the-builder

h4. Understanding Middlewares

* "Railscast on Rack Middlewares":http://railscasts.com/episodes/151-rack-middleware

h3. Changelog

* February 7, 2009: Second version by "Pratik":credits.html#lifo
* January 11, 2009: First version by "Pratik":credits.html#lifo
