提交 bda787e9 编写于 作者: P Pratik Naik

Initial draft of the rack guide

上级 55901d7d
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Rails on Rack</title>
<!--[if lt IE 8]>
<script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
<![endif]-->
<link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
<link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
<link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
<style type="text/css">
div#container {
max-width: 900px;
padding-bottom: 3em;
}
div#content {
margin-left: 200px;
}
div#container.notoc {
max-width: 600px;
}
.notoc div#content {
margin-left: 0;
}
pre {
line-height: 1.4em;
}
#content p tt {
background: #eeeeee;
border: solid 1px #cccccc;
padding: 3px;
}
dt {
font-weight: bold;
}
#content dt tt {
font-size: 10pt;
}
dd {
margin-left: 3em;
}
#content dt tt, #content pre tt {
background: none;
padding: 0;
border: 0;
}
#content .olist ol {
margin-left: 2em;
}
#header {
position: relative;
max-width: 840px;
margin-left: auto;
margin-right: auto;
}
#header.notoc {
max-width: 580px;
}
#logo {
position: absolute;
left: 10px;
top: 10px;
width: 110px;
height: 140px;
}
div#header h1#site_title {
background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
position: absolute;
width: 392px;
height: 55px;
left: 145px;
top: 20px;
margin: 0;
padding: 0;
}
#site_title span {
display: none;
}
#site_title_tagline {
display: none;
}
ul#navMain {
position: absolute;
margin: 0;
padding: 0;
top: 97px;
left: 145px;
}
.left-floaty, .right-floaty {
padding: 15px;
}
.admonitionblock,
.tableblock {
margin-left: 1em;
margin-right: 1em;
margin-top: 0.25em;
margin-bottom: 1em;
}
.admonitionblock .icon {
padding-right: 8px;
}
.admonitionblock .content {
border: solid 1px #ffda78;
background: #fffebd;
padding: 10px;
padding-top: 8px;
padding-bottom: 8px;
}
.admonitionblock .title {
font-size: 140%;
margin-bottom: 0.5em;
}
.tableblock table {
border: solid 1px #aaaaff;
background: #f0f0ff;
}
.tableblock th {
background: #e0e0e0;
}
.tableblock th,
.tableblock td {
padding: 3px;
padding-left: 5px;
padding-right: 5px;
}
.sidebarblock {
margin-top: 0.25em;
margin: 1em;
border: solid 1px #ccccbb;
padding: 8px;
background: #ffffe0;
}
.sidebarblock .sidebar-title {
font-size: 140%;
font-weight: 600;
margin-bottom: 0.3em;
}
.sidebarblock .sidebar-content > .para:last-child > p {
margin-bottom: 0;
}
.sidebarblock .sidebar-title a {
text-decoration: none;
}
.sidebarblock .sidebar-title a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div id="header" >
<div id="logo">
<a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
</div>
<h1 id="site_title"><span>Ruby on Rails</span></h1>
<h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>
<ul id="navMain">
<li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
<li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
</ul>
</div>
<div id="container">
<div id="sidebar">
<h2>Chapters</h2>
<ol>
<li>
<a href="#_introduction_to_rack">Introduction to Rack</a>
</li>
<li>
<a href="#_rails_on_rack">Rails on Rack</a>
<ul>
<li><a href="#_actioncontroller_dispatcher_new">ActionController::Dispatcher.new</a></li>
<li><a href="#_script_server">script/server</a></li>
<li><a href="#_rackup">rackup</a></li>
</ul>
</li>
<li>
<a href="#_action_controller_middleware_stack">Action Controller Middleware Stack</a>
<ul>
<li><a href="#_adding_middlewares">Adding Middlewares</a></li>
<li><a href="#_internal_middleware_stack">Internal Middleware Stack</a></li>
<li><a href="#_custom_internal_middleware_stack">Custom Internal Middleware Stack</a></li>
</ul>
</li>
<li>
<a href="#_rails_metal_applications">Rails Metal Applications</a>
<ul>
<li><a href="#_generating_a_metal_application">Generating a Metal Application</a></li>
</ul>
</li>
<li>
<a href="#_changelog">Changelog</a>
</li>
</ol>
</div>
<div id="content">
<h1>Rails on Rack</h1>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph"><p>This guide covers Rails integration with Rack and interfacing with other Rack components. By referring to this guide, you will be able to:</p></div>
<div class="ulist"><ul>
<li>
<p>
Create Rails Metal applications
</p>
</li>
<li>
<p>
Use Rack Middlewares in your Rails applications
</p>
</li>
<li>
<p>
Understand Action Pack&#8217;s internal Middleware stack
</p>
</li>
<li>
<p>
Define custom internal Middleware stack
</p>
</li>
<li>
<p>
Understand the best practices for developing a middleware aimed at Rails applications
</p>
</li>
</ul></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares</td>
</tr></table>
</div>
</div>
</div>
<h2 id="_introduction_to_rack">1. Introduction to Rack</h2>
<div class="sectionbody">
<div class="sidebarblock">
<div class="sidebar-content">
<div class="paragraph"><p>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.</p></div>
<div class="ulist"><ul>
<li>
<p>
<a href="http://rack.rubyforge.org/doc">Rack API Documentation</a>
</p>
</li>
</ul></div>
</div></div>
<div class="paragraph"><p>Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack&#8217;s basics, you should check out the following links:</p></div>
<div class="ulist"><ul>
<li>
<p>
<a href="http://rack.github.com">Official Rack Website</a>
</p>
</li>
<li>
<p>
<a href="http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html">Introducing Rack</a>
</p>
</li>
<li>
<p>
<a href="http://m.onkey.org/2008/11/17/ruby-on-rack-1">Ruby on Rack #1 - Hello Rack!</a>
</p>
</li>
<li>
<p>
<a href="http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder">Ruby on Rack #2 - The Builder</a>
</p>
</li>
</ul></div>
</div>
<h2 id="_rails_on_rack">2. Rails on Rack</h2>
<div class="sectionbody">
<h3 id="_actioncontroller_dispatcher_new">2.1. ActionController::Dispatcher.new</h3>
<div class="paragraph"><p><tt>ActionController::Dispatcher.new</tt> is the primary Rack application object of a Rails application. It responds to <tt>call</tt> method with a single <tt>env</tt> argument and returns a Rack response. Any Rack compliant web server should be using <tt>ActionController::Dispatcher.new</tt> object to serve a Rails application.</p></div>
<h3 id="_script_server">2.2. script/server</h3>
<div class="paragraph"><p><tt>script/server</tt> does the basic job of creating a <tt>Rack::Builder</tt> object and starting the webserver. This is Rails equivalent of Rack&#8217;s <tt>rackup</tt> script.</p></div>
<div class="paragraph"><p>Here&#8217;s how <tt>script/server</tt> creates an instance of <tt>Rack::Builder</tt></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>app <span style="color: #990000">=</span> Rack<span style="color: #990000">::</span>Builder<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span>
use Rails<span style="color: #990000">::</span>Rack<span style="color: #990000">::</span>LogTailer <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> options<span style="color: #990000">[:</span>detach<span style="color: #990000">]</span>
use Rails<span style="color: #990000">::</span>Rack<span style="color: #990000">::</span>Static
use Rails<span style="color: #990000">::</span>Rack<span style="color: #990000">::</span>Debugger <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> options<span style="color: #990000">[:</span>debugger<span style="color: #990000">]</span>
run ActionController<span style="color: #990000">::</span>Dispatcher<span style="color: #990000">.</span>new
<span style="color: #FF0000">}</span><span style="color: #990000">.</span>to_app</tt></pre></div></div>
<div class="paragraph"><p>Middlewares used in the code above are most useful in development envrionment. The following table explains their usage:</p></div>
<div class="tableblock">
<table rules="all"
width="100%"
frame="border"
cellspacing="0" cellpadding="4">
<col width="50%" />
<col width="50%" />
<thead valign="top">
<tr>
<th align="left">Middleware </th>
<th align="left">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr>
<td align="left"><p class="table">Rails::Rack::LogTailer</p></td>
<td align="left"><p class="table">Appends log file output to console</p></td>
</tr>
<tr>
<td align="left"><p class="table">Rails::Rack::Static</p></td>
<td align="left"><p class="table">Serves static files inside <tt>RAILS_ROOT/public</tt> directory</p></td>
</tr>
<tr>
<td align="left"><p class="table">Rails::Rack::Debugger</p></td>
<td align="left"><p class="table">Starts Debugger</p></td>
</tr>
</tbody>
</table>
</div>
<h3 id="_rackup">2.3. rackup</h3>
<div class="paragraph"><p>To use <tt>rackup</tt> instead of Rails' <tt>script/server</tt>, you can put the following inside <tt>config.ru</tt> of your Rails application&#8217;s root directory:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># RAILS_ROOT/config.ru</span></span>
<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"config/environment"</span>
use Rails<span style="color: #990000">::</span>Rack<span style="color: #990000">::</span>LogTailer
use Rails<span style="color: #990000">::</span>Rack<span style="color: #990000">::</span>Static
run ActionController<span style="color: #990000">::</span>Dispatcher<span style="color: #990000">.</span>new</tt></pre></div></div>
<div class="paragraph"><p>And start the server:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #990000">[</span>lifo@null application<span style="color: #990000">]</span>$ rackup</tt></pre></div></div>
<div class="paragraph"><p>To find out more about different <tt>rackup</tt> options:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #990000">[</span>lifo@null application<span style="color: #990000">]</span>$ rackup --help</tt></pre></div></div>
</div>
<h2 id="_action_controller_middleware_stack">3. Action Controller Middleware Stack</h2>
<div class="sectionbody">
<div class="paragraph"><p>Many of Action Controller&#8217;s internal components are implemented as Rack middlewares. <tt>ActionController::Dispatcher</tt> uses <tt>ActionController::MiddlewareStack</tt> to combine various internal and external middlewares to form a complete Rails Rack application.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">
<div class="title">What is ActionController::MiddlewareStack ?</div><tt>ActionController::MiddlewareStack</tt> is Rails equivalent of <tt>Rack::Builder</tt>, but built for better flexibility and more features to meet Rails' requirements.</td>
</tr></table>
</div>
<h3 id="_adding_middlewares">3.1. Adding Middlewares</h3>
<div class="paragraph"><p>Rails provides a very simple configuration interface for adding generic Rack middlewares to a Rails applications.</p></div>
<div class="paragraph"><p>Here&#8217;s how you can add middlewares via <tt>environment.rb</tt></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># environment.rb</span></span>
config<span style="color: #990000">.</span>middleware<span style="color: #990000">.</span>use Rack<span style="color: #990000">::</span>BounceFavicon</tt></pre></div></div>
<h3 id="_internal_middleware_stack">3.2. Internal Middleware Stack</h3>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>use <span style="color: #FF0000">"ActionController::Lock"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> lambda <span style="color: #FF0000">{</span>
<span style="color: #990000">!</span>ActionController<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>allow_concurrency
<span style="color: #FF0000">}</span>
use <span style="color: #FF0000">"ActionController::Failsafe"</span>
use <span style="color: #FF0000">"ActiveRecord::QueryCache"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> lambda <span style="color: #FF0000">{</span> <span style="font-weight: bold"><span style="color: #0000FF">defined</span></span><span style="color: #990000">?(</span>ActiveRecord<span style="color: #990000">)</span> <span style="color: #FF0000">}</span>
<span style="color: #990000">[</span><span style="color: #FF0000">"ActionController::Session::CookieStore"</span><span style="color: #990000">,</span>
<span style="color: #FF0000">"ActionController::Session::MemCacheStore"</span><span style="color: #990000">,</span>
<span style="color: #FF0000">"ActiveRecord::SessionStore"</span><span style="color: #990000">].</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>store<span style="color: #990000">|</span>
use<span style="color: #990000">(</span>store<span style="color: #990000">,</span> ActionController<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>session_options<span style="color: #990000">,</span>
<span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> lambda <span style="color: #FF0000">{</span>
<span style="font-weight: bold"><span style="color: #0000FF">if</span></span> session_store <span style="color: #990000">=</span> ActionController<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>session_store
session_store<span style="color: #990000">.</span>name <span style="color: #990000">==</span> store
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="color: #FF0000">}</span>
<span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
use ActionController<span style="color: #990000">::</span>VerbPiggybacking</tt></pre></div></div>
<div class="tableblock">
<table rules="all"
width="100%"
frame="border"
cellspacing="0" cellpadding="4">
<col width="50%" />
<col width="50%" />
<thead valign="top">
<tr>
<th align="left">Middleware </th>
<th align="left">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr>
<td align="left"><p class="table">ActionController::Lock</p></td>
<td align="left"><p class="table">Mutex</p></td>
</tr>
<tr>
<td align="left"><p class="table">ActionController::Failsafe</p></td>
<td align="left"><p class="table">Never fail</p></td>
</tr>
<tr>
<td align="left"><p class="table">ActiveRecord::QueryCache</p></td>
<td align="left"><p class="table">Query caching</p></td>
</tr>
<tr>
<td align="left"><p class="table">ActionController::Session::CookieStore</p></td>
<td align="left"><p class="table">Query caching</p></td>
</tr>
<tr>
<td align="left"><p class="table">ActionController::Session::MemCacheStore</p></td>
<td align="left"><p class="table">Query caching</p></td>
</tr>
<tr>
<td align="left"><p class="table">ActiveRecord::SessionStore</p></td>
<td align="left"><p class="table">Query caching</p></td>
</tr>
<tr>
<td align="left"><p class="table">ActionController::VerbPiggybacking</p></td>
<td align="left"><p class="table">_method hax</p></td>
</tr>
</tbody>
</table>
</div>
<h3 id="_custom_internal_middleware_stack">3.3. Custom Internal Middleware Stack</h3>
<div class="paragraph"><p>VERIFY THIS WORKS. Just a code dump at the moment.</p></div>
<div class="paragraph"><p>Put the following in an initializer.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>ActionController<span style="color: #990000">::</span>Dispatcher<span style="color: #990000">.</span>middleware <span style="color: #990000">=</span> ActionController<span style="color: #990000">::</span>MiddlewareStack<span style="color: #990000">.</span>new <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>m<span style="color: #990000">|</span>
m<span style="color: #990000">.</span>use ActionController<span style="color: #990000">::</span>Lock
m<span style="color: #990000">.</span>use ActionController<span style="color: #990000">::</span>Failsafe
m<span style="color: #990000">.</span>use ActiveRecord<span style="color: #990000">::</span>QueryCache
m<span style="color: #990000">.</span>use ActionController<span style="color: #990000">::</span>Session<span style="color: #990000">::</span>CookieStore
m<span style="color: #990000">.</span>use ActionController<span style="color: #990000">::</span>VerbPiggybacking
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
</div>
<h2 id="_rails_metal_applications">4. Rails Metal Applications</h2>
<div class="sectionbody">
<div class="paragraph"><p>Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails applications. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue.</p></div>
<h3 id="_generating_a_metal_application">4.1. Generating a Metal Application</h3>
<div class="paragraph"><p>Rails provides a generator called <tt>performance_test</tt> for creating new performance tests:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>script/generate metal poller</tt></pre></div></div>
<div class="paragraph"><p>This generates <tt>poller.rb</tt> in the <tt>app/metal</tt> directory:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># Allow the metal piece to run in isolation</span></span>
<span style="font-weight: bold"><span style="color: #000080">require</span></span><span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">"/../../config/environment"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> <span style="font-weight: bold"><span style="color: #0000FF">defined</span></span><span style="color: #990000">?(</span>Rails<span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Poller
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>call<span style="color: #990000">(</span>env<span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">if</span></span> env<span style="color: #990000">[</span><span style="color: #FF0000">"PATH_INFO"</span><span style="color: #990000">]</span> <span style="color: #990000">=~</span> <span style="color: #FF6600">/^\/poller/</span>
<span style="color: #990000">[</span><span style="color: #993399">200</span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #FF0000">"Content-Type"</span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"text/html"</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span> <span style="color: #990000">[</span><span style="color: #FF0000">"Hello, World!"</span><span style="color: #990000">]]</span>
<span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
<span style="color: #990000">[</span><span style="color: #993399">404</span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #FF0000">"Content-Type"</span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"text/html"</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span> <span style="color: #990000">[</span><span style="color: #FF0000">"Not Found"</span><span style="color: #990000">]]</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Metal applications are an optimization. You should make sure to <a href="http://weblog.rubyonrails.org/2008/12/20/performance-of-rails-metal">understand the related performance implications</a> before using it.</p></div>
</div>
<h2 id="_changelog">5. Changelog</h2>
<div class="sectionbody">
<div class="paragraph"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/4">Lighthouse ticket</a></p></div>
<div class="ulist"><ul>
<li>
<p>
January 11, 2009: First version by Pratik
</p>
</li>
</ul></div>
</div>
</div>
</div>
</body>
</html>
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 custom internal Middleware stack
* Understand the best practices for developing a middleware aimed at Rails applications
NOTE: This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares, url maps and Rack::Builder.
== Introduction to Rack ==
****
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.
- http://rack.rubyforge.org/doc[Rack API Documentation]
****
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 following links:
* http://rack.github.com[Official Rack Website]
* http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html[Introducing Rack]
* http://m.onkey.org/2008/11/17/ruby-on-rack-1[Ruby on Rack #1 - Hello Rack!]
* http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder[Ruby on Rack #2 - The Builder]
== Rails on Rack ==
=== ActionController::Dispatcher.new ===
+ActionController::Dispatcher.new+ is the primary Rack application object of a Rails application. It responds to +call+ method with a single +env+ argument and returns a Rack response. Any Rack compliant web server should be using +ActionController::Dispatcher.new+ object to serve a Rails application.
=== script/server ===
+script/server+ 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 +script/server+ creates an instance of +Rack::Builder+
[source, ruby]
----------------------------------------------------------------------------
app = Rack::Builder.new {
use Rails::Rack::LogTailer unless options[:detach]
use Rails::Rack::Static
use Rails::Rack::Debugger if options[:debugger]
run ActionController::Dispatcher.new
}.to_app
----------------------------------------------------------------------------
Middlewares used in the code above are most useful in development envrionment. The following table explains their usage:
[options="header"]
|==========================================================================================================
|Middleware |Purpose
|Rails::Rack::LogTailer | Appends log file output to console
|Rails::Rack::Static | Serves static files inside +RAILS_ROOT/public+ directory
|Rails::Rack::Debugger | Starts Debugger
|==========================================================================================================
=== rackup ===
To use +rackup+ instead of Rails' +script/server+, you can put the following inside +config.ru+ of your Rails application's root directory:
[source, ruby]
----------------------------------------------------------------------------
# RAILS_ROOT/config.ru
require "config/environment"
use Rails::Rack::LogTailer
use Rails::Rack::Static
run ActionController::Dispatcher.new
----------------------------------------------------------------------------
And start the server:
[source, shell]
----------------------------------------------------------------------------
[lifo@null application]$ rackup
----------------------------------------------------------------------------
To find out more about different +rackup+ options:
[source, shell]
----------------------------------------------------------------------------
[lifo@null application]$ rackup --help
----------------------------------------------------------------------------
== 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.
.What is ActionController::MiddlewareStack ?
NOTE: +ActionController::MiddlewareStack+ is Rails equivalent of +Rack::Builder+, but built for better flexibility and more features to meet Rails' requirements.
=== Adding Middlewares ===
Rails provides a very simple configuration interface for adding generic Rack middlewares to a Rails applications.
Here's how you can add middlewares via +environment.rb+
[source, ruby]
----------------------------------------------------------------------------
# environment.rb
config.middleware.use Rack::BounceFavicon
----------------------------------------------------------------------------
=== Internal Middleware Stack ===
[source, ruby]
----------------------------------------------------------------------------
use "ActionController::Lock", :if => lambda {
!ActionController::Base.allow_concurrency
}
use "ActionController::Failsafe"
use "ActiveRecord::QueryCache", :if => lambda { defined?(ActiveRecord) }
["ActionController::Session::CookieStore",
"ActionController::Session::MemCacheStore",
"ActiveRecord::SessionStore"].each do |store|
use(store, ActionController::Base.session_options,
:if => lambda {
if session_store = ActionController::Base.session_store
session_store.name == store
end
}
)
end
use ActionController::VerbPiggybacking
----------------------------------------------------------------------------
[options="header"]
|==========================================================================================================
|Middleware |Purpose
|ActionController::Lock | Mutex
|ActionController::Failsafe | Never fail
|ActiveRecord::QueryCache | Query caching
|ActionController::Session::CookieStore | Query caching
|ActionController::Session::MemCacheStore | Query caching
|ActiveRecord::SessionStore | Query caching
|ActionController::VerbPiggybacking | _method hax
|==========================================================================================================
=== Customizing Internal Middleware Stack ===
VERIFY THIS WORKS. Just a code dump at the moment.
Put the following in an initializer.
[source, ruby]
----------------------------------------------------------------------------
ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new do |m|
m.use ActionController::Lock
m.use ActionController::Failsafe
m.use ActiveRecord::QueryCache
m.use ActionController::Session::CookieStore
m.use ActionController::VerbPiggybacking
end
----------------------------------------------------------------------------
== Rails Metal Applications ==
Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails application. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue.
=== Generating a Metal Application ===
Rails provides a generator called +performance_test+ for creating new performance tests:
[source, shell]
----------------------------------------------------------------------------
script/generate metal poller
----------------------------------------------------------------------------
This generates +poller.rb+ in the +app/metal+ directory:
[source, ruby]
----------------------------------------------------------------------------
# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
class Poller
def self.call(env)
if env["PATH_INFO"] =~ /^\/poller/
[200, {"Content-Type" => "text/html"}, ["Hello, World!"]]
else
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
end
end
----------------------------------------------------------------------------
Metal applications are an optimization. You should make sure to http://weblog.rubyonrails.org/2008/12/20/performance-of-rails-metal[understand the related performance implications] before using it.
== Middlewares and Rails ==
== Changelog ==
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/4[Lighthouse ticket]
* January 11, 2009: First version by Pratik
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册