diff options
author | Hongli Lai (Phusion) <hongli@phusion.nl> | 2008-12-03 19:30:35 +0100 |
---|---|---|
committer | Hongli Lai (Phusion) <hongli@phusion.nl> | 2008-12-03 19:30:35 +0100 |
commit | ccb96f2297e8783165cba764e9b5d51e1a15ff87 (patch) | |
tree | 3229e6fdddc42054615514d843c555e341003033 /railties/doc/guides/html | |
parent | fb2325e35855d62abd2c76ce03feaa3ca7992e4f (diff) | |
parent | 761a633a9c0a45d76ef3ed10da97e3696c3ded79 (diff) | |
download | rails-ccb96f2297e8783165cba764e9b5d51e1a15ff87.tar.gz rails-ccb96f2297e8783165cba764e9b5d51e1a15ff87.tar.bz2 rails-ccb96f2297e8783165cba764e9b5d51e1a15ff87.zip |
Merge commit 'origin/master' into savepoints
Conflicts:
activerecord/lib/active_record/fixtures.rb
activerecord/test/cases/defaults_test.rb
Diffstat (limited to 'railties/doc/guides/html')
17 files changed, 3484 insertions, 1066 deletions
diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html index c68f10ad5a..68b8188f7c 100644 --- a/railties/doc/guides/html/2_2_release_notes.html +++ b/railties/doc/guides/html/2_2_release_notes.html @@ -243,6 +243,8 @@ ul#navMain { <li><a href="#_method_arrays_for_member_or_collection_routes">Method Arrays for Member or Collection Routes</a></li> + <li><a href="#_resources_with_specific_actions">Resources With Specific Actions</a></li> + <li><a href="#_other_action_controller_changes">Other Action Controller Changes</a></li> </ul> @@ -407,7 +409,7 @@ More information : </li>
</ul></div>
<div class="para"><p>All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers.</p></div>
-<div class="para"><p>If you want to these generate guides locally, inside your application:</p></div>
+<div class="para"><p>If you want to generate these guides locally, inside your application:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -525,7 +527,7 @@ More information : <div class="sectionbody">
<div class="para"><p>There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements.</p></div>
<h3 id="_transactional_migrations">5.1. Transactional Migrations</h3>
-<div class="para"><p>Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by <tt>rake db:migrate:redo</tt> after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported <strong>on PostgreSQL only</strong>. The code is extensible to other database types in the future.</p></div>
+<div class="para"><p>Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by <tt>rake db:migrate:redo</tt> after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter.</p></div>
<div class="ilist"><ul>
<li>
<p>
@@ -542,6 +544,11 @@ More information: <a href="http://adam.blog.heroku.com/past/2008/9/3/ddl_transactions/">DDL Transactions</a>
</p>
</li>
+<li>
+<p>
+<a href="http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/">A major milestone for DB2 on Rails</a>
+</p>
+</li>
</ul></div>
</li>
</ul></div>
@@ -693,9 +700,9 @@ Counter cache columns (for associations declared with <tt>:counter_cache ⇒ </div>
<h2 id="_action_controller">6. Action Controller</h2>
<div class="sectionbody">
-<div class="para"><p>On the controller side, there are a couple of changes that will help tidy up your routes.</p></div>
+<div class="para"><p>On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.</p></div>
<h3 id="_shallow_route_nesting">6.1. Shallow Route Nesting</h3>
-<div class="para"><p>Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you <em>can</em> supply more information.</p></div>
+<div class="para"><p>Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -756,8 +763,24 @@ Lead Contributor: <a href="http://brennandunn.com/">Brennan Dunn</a> </p>
</li>
</ul></div>
-<div class="para"><p>Action Controller now offers good support for HTTP conditional GET requests, as well as some other additions.</p></div>
-<h3 id="_other_action_controller_changes">6.3. Other Action Controller Changes</h3>
+<h3 id="_resources_with_specific_actions">6.3. Resources With Specific Actions</h3>
+<div class="para"><p>By default, when you use <tt>map.resources</tt> to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the <tt>:only</tt> and <tt>:except</tt> options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special <tt>:all</tt> or <tt>:none</tt> options. These options are inherited by nested resources.</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>map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>photos<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=></span> <span style="color: #990000">[:</span>index<span style="color: #990000">,</span> <span style="color: #990000">:</span>show<span style="color: #990000">]</span>
+map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>except <span style="color: #990000">=></span> <span style="color: #990000">:</span>destroy
+</tt></pre></div></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Lead Contributor: <a href="http://experthuman.com/">Tom Stuart</a>
+</p>
+</li>
+</ul></div>
+<h3 id="_other_action_controller_changes">6.4. Other Action Controller Changes</h3>
<div class="ilist"><ul>
<li>
<p>
@@ -789,6 +812,16 @@ Rails now supports HTTP-only cookies (and uses them for sessions), which help mi <tt>render</tt> now supports a <tt>:js</tt> option to render plain vanilla javascript with the right mime type.
</p>
</li>
+<li>
+<p>
+Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
+</p>
+</li>
+<li>
+<p>
+Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling <tt>polymorphic_path([@project, @date, @area])</tt> with a nil date will give you <tt>project_area_path</tt>.
+</p>
+</li>
</ul></div>
</div>
<h2 id="_action_view">7. Action View</h2>
@@ -833,6 +866,7 @@ More information: </ul></div>
</li>
</ul></div>
+<div class="para"><p>Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed.</p></div>
</div>
<h2 id="_active_support">9. Active Support</h2>
<div class="sectionbody">
@@ -1071,7 +1105,7 @@ Wrapped <tt>Rails.env</tt> in <tt>StringInquirer</tt> so you can do <tt>Rails.en </li>
<li>
<p>
-<tt>script/generate</tt> works without deprecation warnings when RubyGems 1.3.0 is present
+To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher.
</p>
</li>
</ul></div>
diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html index 32ddbe1f60..66563bf1a3 100644 --- a/railties/doc/guides/html/actioncontroller_basics.html +++ b/railties/doc/guides/html/actioncontroller_basics.html @@ -199,18 +199,20 @@ ul#navMain { <h2>Chapters</h2> <ol> <li> - <a href="#_what_does_a_controller_do">What does a controller do?</a> + <a href="#_what_does_a_controller_do">What Does a Controller do?</a> </li> <li> - <a href="#_methods_and_actions">Methods and actions</a> + <a href="#_methods_and_actions">Methods and Actions</a> </li> <li> <a href="#_parameters">Parameters</a> <ul> - <li><a href="#_hash_and_array_parameters">Hash and array parameters</a></li> + <li><a href="#_hash_and_array_parameters">Hash and Array Parameters</a></li> - <li><a href="#_routing_parameters">Routing parameters</a></li> + <li><a href="#_routing_parameters">Routing Parameters</a></li> + + <li><a href="#_tt_default_url_options_tt"><tt>default_url_options</tt></a></li> </ul> </li> @@ -218,9 +220,9 @@ ul#navMain { <a href="#_session">Session</a> <ul> - <li><a href="#_disabling_the_session">Disabling the session</a></li> + <li><a href="#_disabling_the_session">Disabling the Session</a></li> - <li><a href="#_accessing_the_session">Accessing the session</a></li> + <li><a href="#_accessing_the_session">Accessing the Session</a></li> <li><a href="#_the_flash">The flash</a></li> @@ -233,9 +235,9 @@ ul#navMain { <a href="#_filters">Filters</a> <ul> - <li><a href="#_after_filters_and_around_filters">After filters and around filters</a></li> + <li><a href="#_after_filters_and_around_filters">After Filters and Around Filters</a></li> - <li><a href="#_other_ways_to_use_filters">Other ways to use filters</a></li> + <li><a href="#_other_ways_to_use_filters">Other Ways to Use Filters</a></li> </ul> </li> @@ -243,12 +245,15 @@ ul#navMain { <a href="#_verification">Verification</a> </li> <li> - <a href="#_the_request_and_response_objects">The request and response objects</a> + <a href="#_request_forgery_protection">Request Forgery Protection</a> + </li> + <li> + <a href="#_the_tt_request_tt_and_tt_response_tt_objects">The <tt>request</tt> and <tt>response</tt> Objects</a> <ul> - <li><a href="#_the_request">The request</a></li> + <li><a href="#_the_tt_request_tt_object">The <tt>request</tt> Object</a></li> - <li><a href="#_the_response">The response</a></li> + <li><a href="#_the_tt_response_tt_object">The <tt>response</tt> Object</a></li> </ul> </li> @@ -256,28 +261,31 @@ ul#navMain { <a href="#_http_basic_authentication">HTTP Basic Authentication</a> </li> <li> - <a href="#_streaming_and_file_downloads">Streaming and file downloads</a> + <a href="#_streaming_and_file_downloads">Streaming and File Downloads</a> <ul> - <li><a href="#_sending_files">Sending files</a></li> + <li><a href="#_sending_files">Sending Files</a></li> - <li><a href="#_restful_downloads">RESTful downloads</a></li> + <li><a href="#_restful_downloads">RESTful Downloads</a></li> </ul> </li> <li> - <a href="#_parameter_filtering">Parameter filtering</a> + <a href="#_parameter_filtering">Parameter Filtering</a> </li> <li> <a href="#_rescue">Rescue</a> <ul> - <li><a href="#_the_default_500_and_404_templates">The default 500 and 404 templates</a></li> + <li><a href="#_the_default_500_and_404_templates">The Default 500 and 404 Templates</a></li> <li><a href="#_tt_rescue_from_tt"><tt>rescue_from</tt></a></li> </ul> </li> + <li> + <a href="#_changelog">Changelog</a> + </li> </ol> </div> @@ -285,30 +293,75 @@ ul#navMain { <h1>Action Controller basics</h1> <div id="preamble">
<div class="sectionbody">
-<div class="para"><p>In this guide you will learn how controllers work and how they fit into the request cycle in your application. You will learn how to make use of the many tools provided by Action Controller to work with the session, cookies and filters and how to use the built-in HTTP authentication and data streaming facilities. In the end, we will take a look at some tools that will be useful once your controllers are ready and working, like how to filter sensitive parameters from the log and how to rescue and deal with exceptions that may be raised during the request.</p></div>
+<div class="para"><p>In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Follow the flow of a request through a controller
+</p>
+</li>
+<li>
+<p>
+Understand why and how to store data in the session or cookies
+</p>
+</li>
+<li>
+<p>
+Work with filters to execute code during request processing
+</p>
+</li>
+<li>
+<p>
+Use Action Controller's built-in HTTP authentication
+</p>
+</li>
+<li>
+<p>
+Stream data directly to the user's browser
+</p>
+</li>
+<li>
+<p>
+Filter sensitive parameters so they do not appear in the application's log
+</p>
+</li>
+<li>
+<p>
+Deal with exceptions that may be raised during request processing
+</p>
+</li>
+</ul></div>
</div>
</div>
-<h2 id="_what_does_a_controller_do">1. What does a controller do?</h2>
+<h2 id="_what_does_a_controller_do">1. What Does a Controller do?</h2>
<div class="sectionbody">
<div class="para"><p>Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.</p></div>
<div class="para"><p>For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.</p></div>
-<div class="para"><p>A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display it to the user, and it saves or updates data from the user to the model.</p></div>
+<div class="para"><p>A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">For more details on the routing process, see <a href="../routing_outside_in.html">Rails Routing from the Outside In</a>.</td>
+</tr></table>
+</div>
</div>
-<h2 id="_methods_and_actions">2. Methods and actions</h2>
+<h2 id="_methods_and_actions">2. Methods and Actions</h2>
<div class="sectionbody">
-<div class="para"><p>A controller is a Ruby class which inherits from ActionController::Base and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then an instance of that controller will be created and the method corresponding to the action (the method with the same name as the action) gets run.</p></div>
+<div class="para"><p>A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the public method with the same name as the action.</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-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000"><</span> ActionController<span style="color: #990000">::</span>Base
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000"><</span> ApplicationController
<span style="font-style: italic"><span style="color: #9A1900"># Actions are public methods</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> new
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># These methods are responsible for producing output</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># Action methods are responsible for producing output</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> edit
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -320,8 +373,8 @@ private <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Private methods in a controller are also used as filters, which will be covered later in this guide.</p></div>
-<div class="para"><p>As an example, if the user goes to <tt>/clients/new</tt> in your application to add a new client, a ClientsController instance will be created and the <tt>new</tt> method will be run. Note that the empty method from the example above could work just fine because Rails will by default render the <tt>new.html.erb</tt> view unless the action says otherwise. The <tt>new</tt> method could make available to the view a <tt>@client</tt> instance variable by creating a new Client:</p></div>
+<div class="para"><p>There's no rule saying a method on a controller has to be an action; they may well be used for other purposes such as filters, which will be covered later in this guide.</p></div>
+<div class="para"><p>As an example, if a user goes to <tt>/clients/new</tt> in your application to add a new client, Rails will create an instance of ClientsController and run the <tt>new</tt> method. Note that the empty method from the example above could work just fine because Rails will by default render the <tt>new.html.erb</tt> view unless the action says otherwise. The <tt>new</tt> method could make available to the view a <tt>@client</tt> instance variable by creating a new Client:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -332,10 +385,11 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <a href="../layouts_and_rendering.html">Layouts & rendering guide</a> explains this in more detail.</p></div>
+<div class="para"><p>ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.</p></div>
</div>
<h2 id="_parameters">3. Parameters</h2>
<div class="sectionbody">
-<div class="para"><p>You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the <tt>params</tt> hash in your controller:</p></div>
+<div class="para"><p>You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the <tt>params</tt> hash in your controller:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -343,9 +397,10 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000"><</span> ActionController<span style="color: #990000">::</span>Base
- <span style="font-style: italic"><span style="color: #9A1900"># This action uses query string parameters because it gets run by a HTTP GET request,</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># but this does not make any difference to the way in which the parameters are accessed.</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># The URL for this action would look like this in order to list activated clients: /clients?status=activated</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># This action uses query string parameters because it gets run by a HTTP</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># GET request, but this does not make any difference to the way in which</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># the parameters are accessed. The URL for this action would look like this</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># in order to list activated clients: /clients?status=activated</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> index
<span style="font-weight: bold"><span style="color: #0000FF">if</span></span> params<span style="color: #990000">[:</span>status<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"activated"</span>
<span style="color: #009900">@clients</span> <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>activated
@@ -370,12 +425,20 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<h3 id="_hash_and_array_parameters">3.1. Hash and array parameters</h3>
+<h3 id="_hash_and_array_parameters">3.1. Hash and Array Parameters</h3>
<div class="para"><p>The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>GET /clients?ids[]=1&ids[2]&ids[]=3</tt></pre>
+<pre><tt>GET /clients?ids[]=1&ids[]=2&ids[]=3</tt></pre>
</div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.</td>
+</tr></table>
+</div>
<div class="para"><p>The value of <tt>params[:ids]</tt> will now be <tt>["1", "2", "3"]</tt>. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.</p></div>
<div class="para"><p>To send a hash you include the key name inside the brackets:</p></div>
<div class="listingblock">
@@ -387,13 +450,38 @@ http://www.gnu.org/software/src-highlite --> <input type="text" name="client[address][city]" value="Carrot City" />
</form></tt></pre>
</div></div>
-<div class="para"><p>The value of <tt>params[:client]</tt> when this form is submitted will be <tt>{:name ⇒ "Acme", :phone ⇒ "12345", :address ⇒ {:postcode ⇒ "12345", :city ⇒ "Carrot City"}}</tt>. Note the nested hash in <tt>params[:client][:address]</tt>.</p></div>
-<h3 id="_routing_parameters">3.2. Routing parameters</h3>
-<div class="para"><p>The <tt>params</tt> hash will always contain the <tt>:controller</tt> and <tt>:action</tt> keys, but you should use the methods <tt>controller_name</tt> and <tt>action_name</tt> instead to access these values. Any other parameters defined by the routing, such as <tt>:id</tt> will also be available.</p></div>
+<div class="para"><p>The value of <tt>params[:client]</tt> when this form is submitted will be <tt>{"name" ⇒ "Acme", "phone" ⇒ "12345", "address" ⇒ {"postcode" ⇒ "12345", "city" ⇒ "Carrot City"}}</tt>. Note the nested hash in <tt>params[:client][:address]</tt>.</p></div>
+<div class="para"><p>Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support which is a subclass of Hash which lets you use symbols and strings interchangeably as keys.</p></div>
+<h3 id="_routing_parameters">3.2. Routing Parameters</h3>
+<div class="para"><p>The <tt>params</tt> hash will always contain the <tt>:controller</tt> and <tt>:action</tt> keys, but you should use the methods <tt>controller_name</tt> and <tt>action_name</tt> instead to access these values. Any other parameters defined by the routing, such as <tt>:id</tt> will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the <tt>:status</tt> parameter in a "pretty" URL:</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"># ...</span></span>
+map<span style="color: #990000">.</span>connect <span style="color: #FF0000">"/clients/:status"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">"clients"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">"index"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>foo <span style="color: #990000">=></span> <span style="color: #FF0000">"bar"</span>
+<span style="font-style: italic"><span style="color: #9A1900"># ...</span></span>
+</tt></pre></div></div>
+<div class="para"><p>In this case, when a user opens the URL <tt>/clients/active</tt>, <tt>params[:status]</tt> will be set to "active". When this route is used, <tt>params[:foo]</tt> will also be set to "bar" just like it was passed in the query string in the same way <tt>params[:action]</tt> will contain "index".</p></div>
+<h3 id="_tt_default_url_options_tt">3.3. <tt>default_url_options</tt></h3>
+<div class="para"><p>You can set global default parameters that will be used when generating URLs with <tt>default_url_options</tt>. To do this, define a method with that name in your controller:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>class ApplicationController < ActionController::Base
+
+ #The options parameter is the hash passed in to +url_for+
+ def default_url_options(options)
+ {:locale => I18n.locale}
+ end
+
+end</tt></pre>
+</div></div>
+<div class="para"><p>These options will be used as a starting-point when generating, so it's possible they'll be overridden by <tt>url_for</tt>. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.</p></div>
</div>
<h2 id="_session">4. Session</h2>
<div class="sectionbody">
-<div class="para"><p>Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and can use one of a number of different storage mechanisms:</p></div>
+<div class="para"><p>Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:</p></div>
<div class="ilist"><ul>
<li>
<p>
@@ -402,12 +490,12 @@ CookieStore - Stores everything on the client. </li>
<li>
<p>
-DRBStore - Stores the data on a DRb client.
+DRbStore - Stores the data on a DRb server.
</p>
</li>
<li>
<p>
-MemCacheStore - Stores the data in MemCache.
+MemCacheStore - Stores the data in a memcache.
</p>
</li>
<li>
@@ -416,8 +504,9 @@ ActiveRecordStore - Stores the data in a database using Active Record. </p>
</li>
</ul></div>
-<div class="para"><p>All session stores store the session id in a cookie - there is no other way of passing it to the server. Most stores also use this key to locate the session data on the server.</p></div>
-<div class="para"><p>The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects, the primary example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.</p></div>
+<div class="para"><p>All session stores use a cookie - this is required and Rails does not allow any part of the session to be passed in any other way (e.g. you can't use the query string to pass a session ID) because of security concerns (it's easier to hijack a session when the ID is part of the URL).</p></div>
+<div class="para"><p>Most stores use a cookie to store the session ID which is then used to look up the session data on the server. The default and recommended store, the CookieStore, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited). It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The CookieStore has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.</p></div>
+<div class="para"><p>Read more about session storage in the <a href="../security.html">Security Guide</a>.</p></div>
<div class="para"><p>If you need a different session storage mechanism, you can change it in the <tt>config/environment.rb</tt> file:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -427,8 +516,8 @@ http://www.gnu.org/software/src-highlite --> <pre><tt><span style="font-style: italic"><span style="color: #9A1900"># Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]</span></span>
config<span style="color: #990000">.</span>action_controller<span style="color: #990000">.</span>session_store <span style="color: #990000">=</span> <span style="color: #990000">:</span>active_record_store
</tt></pre></div></div>
-<h3 id="_disabling_the_session">4.1. Disabling the session</h3>
-<div class="para"><p>Sometimes you don't need a session, and you can turn it off to avoid the unnecessary overhead. To do this, use the <a href="http://api.rubyonrails.org/classes/ActionController/SessionManagement/ClassMethods.html#M000649">session</a> class method in your controller:</p></div>
+<h3 id="_disabling_the_session">4.1. Disabling the Session</h3>
+<div class="para"><p>Sometimes you don't need a session. In this case, you can turn it off to avoid the unnecessary overhead. To do this, use the <tt>session</tt> class method in your controller:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -450,7 +539,7 @@ http://www.gnu.org/software/src-highlite --> session <span style="color: #990000">:</span>on
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Or even a single action:</p></div>
+<div class="para"><p>Or even for specified actions:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -460,14 +549,14 @@ http://www.gnu.org/software/src-highlite --> session <span style="color: #990000">:</span>on<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=></span> <span style="color: #990000">[:</span>create<span style="color: #990000">,</span> <span style="color: #990000">:</span>update<span style="color: #990000">]</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<h3 id="_accessing_the_session">4.2. Accessing the session</h3>
+<h3 id="_accessing_the_session">4.2. Accessing the Session</h3>
<div class="para"><p>In your controller you can access the session through the <tt>session</tt> instance method.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
-<td class="content">There are two <tt>session</tt> methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values. The class method is used outside of method definitions while the instance methods is used inside methods, in actions or filters.</td>
+<td class="content">There are two <tt>session</tt> methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values.</td>
</tr></table>
</div>
<div class="para"><p>Session values are stored using key/value pairs like a hash:</p></div>
@@ -481,7 +570,7 @@ http://www.gnu.org/software/src-highlite --> private
<span style="font-style: italic"><span style="color: #9A1900"># Finds the User with the ID stored in the session with the key :current_user_id</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># This is a common way to do user login in a Rails application; logging in sets the</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># This is a common way to handle user login in a Rails application; logging in sets the</span></span>
<span style="font-style: italic"><span style="color: #9A1900"># session value and logging out removes it.</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> current_user
<span style="color: #009900">@_current_user</span> <span style="color: #990000">||=</span> session<span style="color: #990000">[:</span>current_user_id<span style="color: #990000">]</span> <span style="color: #990000">&&</span> User<span style="color: #990000">.</span>find<span style="color: #990000">(</span>session<span style="color: #990000">[:</span>current_user_id<span style="color: #990000">])</span>
@@ -525,9 +614,9 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>To reset the entire session, use <a href="http://api.rubyonrails.org/classes/ActionController/Base.html#M000855">reset_session</a>.</p></div>
+<div class="para"><p>To reset the entire session, use <tt>reset_session</tt>.</p></div>
<h3 id="_the_flash">4.3. The flash</h3>
-<div class="para"><p>The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can set a message which will be displayed to the user on the next request:</p></div>
+<div class="para"><p>The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -543,7 +632,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>The <tt>destroy</tt> action redirects to the application's <tt>root_url</tt>, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to a display eventual errors or notices from the flash in the application's layout:</p></div>
+<div class="para"><p>The <tt>destroy</tt> action redirects to the application's <tt>root_url</tt>, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt><html>
@@ -578,7 +667,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<h4 id="_flash_now">4.3.1. flash.now</h4>
+<h4 id="_tt_flash_now_tt">4.3.1. <tt>flash.now</tt></h4>
<div class="para"><p>By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the <tt>create</tt> action fails to save a resource and you render the <tt>new</tt> template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use <tt>flash.now</tt> in the same way you use the normal <tt>flash</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -634,11 +723,11 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Note that while for session values, you set the key to <tt>nil</tt>, to delete a cookie value, you use <tt>cookies.delete(:key)</tt>.</p></div>
+<div class="para"><p>Note that while for session values, you set the key to <tt>nil</tt>, to delete a cookie value, you should use <tt>cookies.delete(:key)</tt>.</p></div>
</div>
<h2 id="_filters">6. Filters</h2>
<div class="sectionbody">
-<div class="para"><p>Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. Let's define the filter method first:</p></div>
+<div class="para"><p>Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -666,7 +755,7 @@ private <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the <a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704">before_filter</a> method:</p></div>
+<div class="para"><p>The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering or redirecting filter, they are also cancelled. To use this filter in a controller, use the <tt>before_filter</tt> method:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -678,7 +767,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this, so to prevent this filter from running you can use <a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711">skip_before_filter</a> :</p></div>
+<div class="para"><p>In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with <tt>skip_before_filter</tt> :</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -690,8 +779,8 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The <tt>:only</tt> option is used to only skip this filter for these actions, and there is also an <tt>:except</tt> option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.</p></div>
-<h3 id="_after_filters_and_around_filters">6.1. After filters and around filters</h3>
+<div class="para"><p>Now, the <tt>LoginsController</tt>'s "new" and "create" actions will work as before without requiring the user to be logged in. The <tt>:only</tt> option is used to only skip this filter for these actions, and there is also an <tt>:except</tt> option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.</p></div>
+<h3 id="_after_filters_and_around_filters">6.1. After Filters and Around Filters</h3>
<div class="para"><p>In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -715,9 +804,9 @@ private <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<h3 id="_other_ways_to_use_filters">6.2. Other ways to use filters</h3>
+<h3 id="_other_ways_to_use_filters">6.2. Other Ways to Use Filters</h3>
<div class="para"><p>While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.</p></div>
-<div class="para"><p>The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the <tt>require_login</tt> filter from above could be rewritte to use a block:</p></div>
+<div class="para"><p>The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the <tt>require_login</tt> filter from above could be rewritten to use a block:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -730,7 +819,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Note that the filter in this case uses <tt>send</tt> because the <tt>logged_in?</tt> method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.</p></div>
-<div class="para"><p>The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, we will rewrite the login filter again to use a class:</p></div>
+<div class="para"><p>The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -753,13 +842,13 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets it passed as an argument. The filter class has a class method <tt>filter</tt> which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same <tt>filter</tt> method, which will get run in the same way. The method must <tt>yield</tt> to execute the action. Alternatively, it can have both a <tt>before</tt> and an <tt>after</tt> method that are run before and after the action.</p></div>
+<div class="para"><p>Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method <tt>filter</tt> which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same <tt>filter</tt> method, which will get run in the same way. The method must <tt>yield</tt> to execute the action. Alternatively, it can have both a <tt>before</tt> and an <tt>after</tt> method that are run before and after the action.</p></div>
<div class="para"><p>The Rails API documentation has <a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html">more information on using filters</a>.</p></div>
</div>
<h2 id="_verification">7. Verification</h2>
<div class="sectionbody">
-<div class="para"><p>Verifications make sure certain criterias are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the <tt>params</tt>, <tt>session</tt> or <tt>flash</tt> hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criterias are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the <a href="http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html">API codumentation</a> as "essentially a special kind of before_filter".</p></div>
-<div class="para"><p>Let's see how we can use verification to make sure the user supplies a username and a password in order to log in:</p></div>
+<div class="para"><p>Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the <tt>params</tt>, <tt>session</tt> or <tt>flash</tt> hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the <a href="http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html">API documentation</a> as "essentially a special kind of before_filter".</p></div>
+<div class="para"><p>Here's an example of using verification to make sure the user supplies a username and a password in order to log in:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -794,16 +883,49 @@ http://www.gnu.org/software/src-highlite --> verify <span style="color: #990000">:</span>params <span style="color: #990000">=></span> <span style="color: #990000">[:</span>username<span style="color: #990000">,</span> <span style="color: #990000">:</span>password<span style="color: #990000">],</span>
<span style="color: #990000">:</span>render <span style="color: #990000">=></span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">"new"</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span>
<span style="color: #990000">:</span>add_flash <span style="color: #990000">=></span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>error <span style="color: #990000">=></span> <span style="color: #FF0000">"Username and password required to log in"</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span>
- <span style="color: #990000">:</span>only <span style="color: #990000">=></span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900">#Only run this verification for the "create" action</span></span>
+ <span style="color: #990000">:</span>only <span style="color: #990000">=></span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900"># Only run this verification for the "create" action</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_the_request_and_response_objects">8. The request and response objects</h2>
+<h2 id="_request_forgery_protection">8. Request Forgery Protection</h2>
+<div class="sectionbody">
+<div class="para"><p>Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.</p></div>
+<div class="para"><p>If you generate a form like this:</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: #FF0000"><% form_for @user do |f| -%></span>
+ <span style="color: #FF0000"><%= f.text_field :username %></span>
+ <span style="color: #FF0000"><%= f.text_field :password -%></span>
+<span style="color: #FF0000"><% end -%></span>
+</tt></pre></div></div>
+<div class="para"><p>You will see how the token gets added as a hidden field:</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-weight: bold"><span style="color: #0000FF"><form</span></span> <span style="color: #009900">action</span><span style="color: #990000">=</span><span style="color: #FF0000">"/users/1"</span> <span style="color: #009900">method</span><span style="color: #990000">=</span><span style="color: #FF0000">"post"</span><span style="font-weight: bold"><span style="color: #0000FF">></span></span>
+<span style="font-weight: bold"><span style="color: #0000FF"><div></span></span><span style="font-style: italic"><span style="color: #9A1900"><!-- ... --></span></span><span style="font-weight: bold"><span style="color: #0000FF"><input</span></span> <span style="color: #009900">type</span><span style="color: #990000">=</span><span style="color: #FF0000">"hidden"</span> <span style="color: #009900">value</span><span style="color: #990000">=</span><span style="color: #FF0000">"67250ab105eb5ad10851c00a5621854a23af5489"</span> <span style="color: #009900">name</span><span style="color: #990000">=</span><span style="color: #FF0000">"authenticity_token"</span><span style="font-weight: bold"><span style="color: #0000FF">/></div></span></span>
+<span style="font-style: italic"><span style="color: #9A1900"><!-- Fields --></span></span>
+<span style="font-weight: bold"><span style="color: #0000FF"></form></span></span>
+</tt></pre></div></div>
+<div class="para"><p>Rails adds this token to every form that's generated using the <a href="../form_helpers.html">form helpers</a>, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method <tt>form_authenticity_token</tt>:</p></div>
+<div class="listingblock">
+<div class="title">Example: Add a JavaScript variable containing the token for use with Ajax</div>
+<div class="content">
+<pre><tt><%= javascript_tag "MyApp.authenticity_token = '#{form_authenticity_token}'" %></tt></pre>
+</div></div>
+<div class="para"><p>The <a href="../security.html">Security Guide</a> has more about this and a lot of other security-related issues that you should be aware of when developing a web application.</p></div>
+</div>
+<h2 id="_the_tt_request_tt_and_tt_response_tt_objects">9. The <tt>request</tt> and <tt>response</tt> Objects</h2>
<div class="sectionbody">
-<div class="para"><p>In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The <tt>request</tt> method contains an instance of <a href="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html">AbstractRequest</a> and the <tt>response</tt> method contains the <a href="http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/response.rb">response object</a> representing what is going to be sent back to the client.</p></div>
-<h3 id="_the_request">8.1. The request</h3>
-<div class="para"><p>The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the <a href="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html">API documentation</a>.</p></div>
+<div class="para"><p>In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The <tt>request</tt> method contains an instance of AbstractRequest and the <tt>response</tt> method returns a <tt>response</tt> object representing what is going to be sent back to the client.</p></div>
+<h3 id="_the_tt_request_tt_object">9.1. The <tt>request</tt> Object</h3>
+<div class="para"><p>The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the <a href="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html">API documentation</a>. Among the properties that you can access on this object are:</p></div>
<div class="ilist"><ul>
<li>
<p>
@@ -812,7 +934,7 @@ host - The hostname used for this request. </li>
<li>
<p>
-domain - The hostname without the first part (usually "www").
+domain - The hostname without the first segment (usually "www").
</p>
</li>
<li>
@@ -861,11 +983,10 @@ url - The entire URL used for the request. </p>
</li>
</ul></div>
-<h4 id="_path_parameters_query_parameters_and_request_parameters">8.1.1. path_parameters, query_parameters and request_parameters</h4>
-<div class="para"><p>TODO: Does this belong here?</p></div>
-<div class="para"><p>Rails collects all of the parameters sent along with the request in the <tt>params</tt> hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The <tt>query_parameters</tt> hash contains parameters that were sent as part of the query string while the <tt>request_parameters</tt> hash contains parameters sent as part of the post body. The <tt>path_parameters</tt> hash contains parameters that were recognised by the routing as being part of the path leading to this particular controller and action.</p></div>
-<h3 id="_the_response">8.2. The response</h3>
-<div class="para"><p>The response objects is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.</p></div>
+<h4 id="_tt_path_parameters_tt_tt_query_parameters_tt_and_tt_request_parameters_tt">9.1.1. <tt>path_parameters</tt>, <tt>query_parameters</tt> and <tt>request_parameters</tt></h4>
+<div class="para"><p>Rails collects all of the parameters sent along with the request in the <tt>params</tt> hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The <tt>query_parameters</tt> hash contains parameters that were sent as part of the query string while the <tt>request_parameters</tt> hash contains parameters sent as part of the post body. The <tt>path_parameters</tt> hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.</p></div>
+<h3 id="_the_tt_response_tt_object">9.2. The <tt>response</tt> Object</h3>
+<div class="para"><p>The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.</p></div>
<div class="ilist"><ul>
<li>
<p>
@@ -892,11 +1013,25 @@ content_type - The content type of the response. charset - The character set being used for the response. Default is "utf8".
</p>
</li>
+<li>
+<p>
+headers - Headers used for the response.
+</p>
+</li>
</ul></div>
+<h4 id="_setting_custom_headers">9.2.1. Setting Custom Headers</h4>
+<div class="para"><p>If you want to set custom headers for a response then <tt>response.headers</tt> is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them - like "Content-Type" - automatically. If you want to add or change a header, just assign it to <tt>headers</tt> with the name and value:</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>response<span style="color: #990000">.</span>headers<span style="color: #990000">[</span><span style="color: #FF0000">"Content-Type"</span><span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"application/pdf"</span>
+</tt></pre></div></div>
</div>
-<h2 id="_http_basic_authentication">9. HTTP Basic Authentication</h2>
+<h2 id="_http_basic_authentication">10. HTTP Basic Authentication</h2>
<div class="sectionbody">
-<div class="para"><p>Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, <a href="http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610">authenticate_or_request_with_http_basic</a>.</p></div>
+<div class="para"><p>Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, <tt>authenticate_or_request_with_http_basic</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -904,7 +1039,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AdminController <span style="color: #990000"><</span> ApplicationController
- USERNAME<span style="color: #990000">,</span> PASSWORD <span style="color: #990000">=</span> <span style="color: #FF0000">"humbaba"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"f59a4805511bf4bb61978445a5380c6c"</span>
+ USERNAME<span style="color: #990000">,</span> PASSWORD <span style="color: #990000">=</span> <span style="color: #FF0000">"humbaba"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"</span>
before_filter <span style="color: #990000">:</span>authenticate
@@ -912,7 +1047,7 @@ private <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> authenticate
authenticate_or_request_with_http_basic <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>username<span style="color: #990000">,</span> password<span style="color: #990000">|</span>
- username <span style="color: #990000">==</span> USERNAME <span style="color: #990000">&&</span> Digest<span style="color: #990000">::</span>MD5<span style="color: #990000">.</span>hexdigest<span style="color: #990000">(</span>password<span style="color: #990000">)</span> <span style="color: #990000">==</span> PASSWORD
+ username <span style="color: #990000">==</span> USERNAME <span style="color: #990000">&&</span> Digest<span style="color: #990000">::</span>SHA1<span style="color: #990000">.</span>hexdigest<span style="color: #990000">(</span>password<span style="color: #990000">)</span> <span style="color: #990000">==</span> PASSWORD
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -920,9 +1055,9 @@ private </tt></pre></div></div>
<div class="para"><p>With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication.</p></div>
</div>
-<h2 id="_streaming_and_file_downloads">10. Streaming and file downloads</h2>
+<h2 id="_streaming_and_file_downloads">11. Streaming and File Downloads</h2>
<div class="sectionbody">
-<div class="para"><p>Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the <a href="http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000624">send_data</a> and the <a href="http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000623">send_file</a> methods, that will both stream data to the client. <tt>send_file</tt> is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.</p></div>
+<div class="para"><p>Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the <tt>send_data</tt> and the <tt>send_file</tt> methods, that will both stream data to the client. <tt>send_file</tt> is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.</p></div>
<div class="para"><p>To stream data to the client, use <tt>send_data</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -952,7 +1087,7 @@ private <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>download_pdf</tt> action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the <tt>:disposition</tt> option to "inline". The opposite and default value for this option is "attachment".</p></div>
-<h3 id="_sending_files">10.1. Sending files</h3>
+<h3 id="_sending_files">11.1. Sending Files</h3>
<div class="para"><p>If you want to send a file that already exists on disk, use the <tt>send_file</tt> method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -969,13 +1104,13 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the <tt>stream</tt> option or adjust the block size with the <tt>buffer_size</tt> option.</p></div>
+<div class="para"><p>This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the <tt>:stream</tt> option or adjust the block size with the <tt>:buffer_size</tt> option.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
-<td class="content">Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk as someone could gain access to files they are not meant to have access to.</td>
+<td class="content">Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.</td>
</tr></table>
</div>
<div class="admonitionblock">
@@ -986,8 +1121,8 @@ http://www.gnu.org/software/src-highlite --> <td class="content">It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.</td>
</tr></table>
</div>
-<h3 id="_restful_downloads">10.2. RESTful downloads</h3>
-<div class="para"><p>While <tt>send_data</tt> works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the <tt>show</tt> action:</p></div>
+<h3 id="_restful_downloads">11.2. RESTful Downloads</h3>
+<div class="para"><p>While <tt>send_data</tt> works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the <tt>show</tt> action, without any streaming:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1007,7 +1142,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>In order for this example to work, we have to add the PDF MIME type to Rails. This can be done by adding the following line to the file <tt>config/initializers/mime_types.rb</tt>:</p></div>
+<div class="para"><p>In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file <tt>config/initializers/mime_types.rb</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1029,9 +1164,9 @@ http://www.gnu.org/software/src-highlite --> <pre><tt>GET /clients/1.pdf</tt></pre>
</div></div>
</div>
-<h2 id="_parameter_filtering">11. Parameter filtering</h2>
+<h2 id="_parameter_filtering">12. Parameter Filtering</h2>
<div class="sectionbody">
-<div class="para"><p>Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The <a href="http://api.rubyonrails.org/classes/ActionController/Base.html#M000837">filter_parameter_logging</a> method can be used to filter out sensitive information from the log. It works by replacing certain keys in the <tt>params</tt> hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":</p></div>
+<div class="para"><p>Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The <tt>filter_parameter_logging</tt> method can be used to filter out sensitive information from the log. It works by replacing certain values in the <tt>params</tt> hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1045,14 +1180,14 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.</p></div>
</div>
-<h2 id="_rescue">12. Rescue</h2>
+<h2 id="_rescue">13. Rescue</h2>
<div class="sectionbody">
<div class="para"><p>Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:</p></div>
-<h3 id="_the_default_500_and_404_templates">12.1. The default 500 and 404 templates</h3>
+<h3 id="_the_default_500_and_404_templates">13.1. The Default 500 and 404 Templates</h3>
<div class="para"><p>By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the <tt>public</tt> folder, in <tt>404.html</tt> and <tt>500.html</tt> respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.</p></div>
-<h3 id="_tt_rescue_from_tt">12.2. <tt>rescue_from</tt></h3>
-<div class="para"><p>If you want to do something a bit more elaborate when catching errors, you can use <a href=":http://api.rubyonrails.org/classes/ActionController/Rescue/ClassMethods.html#M000620">rescue_from</a>, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the <tt>:with</tt> option. You can also use a block directly instead of an explicit Proc object.</p></div>
-<div class="para"><p>Let's see how we can use rescue_from to intercept all ActiveRecord::RecordNotFound errors and do something with them.</p></div>
+<h3 id="_tt_rescue_from_tt">13.2. <tt>rescue_from</tt></h3>
+<div class="para"><p>If you want to do something a bit more elaborate when catching errors, you can use <tt>rescue_from</tt>, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a <tt>rescue_from</tt> directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the <tt>:with</tt> option. You can also use a block directly instead of an explicit Proc object.</p></div>
+<div class="para"><p>Here's how you can use <tt>rescue_from</tt> to intercept all ActiveRecord::RecordNotFound errors and do something with them.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1070,7 +1205,7 @@ private <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Of course, this example is anything but elaborate and doesn't improve the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:</p></div>
+<div class="para"><p>Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1117,6 +1252,17 @@ private </tr></table>
</div>
</div>
+<h2 id="_changelog">14. Changelog</h2>
+<div class="sectionbody">
+<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17">Lighthouse ticket</a></p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+November 4, 2008: First release version by Tore Darrell
+</p>
+</li>
+</ul></div>
+</div>
</div> </div> diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html new file mode 100644 index 0000000000..0aa507a9b9 --- /dev/null +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -0,0 +1,749 @@ +<!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>Active Record Validations and Callbacks</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="#_motivations_to_validate_your_active_record_objects">Motivations to validate your Active Record objects</a> + </li> + <li> + <a href="#_how_it_works">How it works</a> + <ul> + + <li><a href="#_when_does_validation_happens">When does validation happens?</a></li> + + <li><a href="#_the_meaning_of_em_valid_em">The meaning of <em>valid</em></a></li> + + </ul> + </li> + <li> + <a href="#_the_declarative_validation_helpers">The declarative validation helpers</a> + <ul> + + <li><a href="#_the_tt_validates_acceptance_of_tt_helper">The <tt>validates_acceptance_of</tt> helper</a></li> + + <li><a href="#_the_tt_validates_associated_tt_helper">The <tt>validates_associated</tt> helper</a></li> + + <li><a href="#_the_tt_validates_confirmation_of_tt_helper">The <tt>validates_confirmation_of</tt> helper</a></li> + + <li><a href="#_the_tt_validates_each_tt_helper">The <tt>validates_each</tt> helper</a></li> + + <li><a href="#_the_tt_validates_exclusion_of_tt_helper">The <tt>validates_exclusion_of</tt> helper</a></li> + + <li><a href="#_the_tt_validates_format_of_tt_helper">The <tt>validates_format_of</tt> helper</a></li> + + <li><a href="#_the_tt_validates_inclusion_of_tt_helper">The <tt>validates_inclusion_of</tt> helper</a></li> + + <li><a href="#_the_tt_validates_length_of_tt_helper">The <tt>validates_length_of</tt> helper</a></li> + + <li><a href="#_the_tt_validates_numericallity_of_tt_helper">The <tt>validates_numericallity_of</tt> helper</a></li> + + <li><a href="#_the_tt_validates_presence_of_tt_helper">The <tt>validates_presence_of</tt> helper</a></li> + + <li><a href="#_the_tt_validates_uniqueness_of_tt_helper">The <tt>validates_uniqueness_of</tt> helper</a></li> + + </ul> + </li> + <li> + <a href="#_common_validation_options">Common validation options</a> + <ul> + + <li><a href="#_the_tt_allow_nil_tt_option">The <tt>:allow_nil</tt> option</a></li> + + <li><a href="#_the_tt_message_tt_option">The <tt>:message</tt> option</a></li> + + <li><a href="#_the_tt_on_tt_option">The <tt>:on</tt> option</a></li> + + </ul> + </li> + <li> + <a href="#_conditional_validation">Conditional validation</a> + <ul> + + <li><a href="#_using_a_symbol_with_the_tt_if_tt_and_tt_unless_tt_options">Using a symbol with the <tt>:if</tt> and <tt>:unless</tt> options</a></li> + + <li><a href="#_using_a_string_with_the_tt_if_tt_and_tt_unless_tt_options">Using a string with the <tt>:if</tt> and <tt>:unless</tt> options</a></li> + + <li><a href="#_using_a_proc_object_with_the_tt_if_tt_and_tt_unless_tt_options">Using a Proc object with the <tt>:if</tt> and :<tt>unless</tt> options</a></li> + + </ul> + </li> + <li> + <a href="#_writing_your_own_validation_methods">Writing your own validation methods</a> + </li> + <li> + <a href="#_changelog">Changelog</a> + </li> + </ol> + </div> + + <div id="content"> + <h1>Active Record Validations and Callbacks</h1> + <div id="preamble">
+<div class="sectionbody">
+<div class="para"><p>This guide teaches you how to work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles.</p></div>
+<div class="para"><p>After reading this guide and trying out the presented concepts, we hope that you'll be able to:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Correctly use all the built-in Active Record validation helpers
+</p>
+</li>
+<li>
+<p>
+Create your own custom validation methods
+</p>
+</li>
+<li>
+<p>
+Work with the error messages generated by the validation proccess
+</p>
+</li>
+<li>
+<p>
+Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved.
+</p>
+</li>
+<li>
+<p>
+Create special classes that encapsulate common behaviour for your callbacks
+</p>
+</li>
+<li>
+<p>
+Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations.
+</p>
+</li>
+</ul></div>
+</div>
+</div>
+<h2 id="_motivations_to_validate_your_active_record_objects">1. Motivations to validate your Active Record objects</h2>
+<div class="sectionbody">
+<div class="para"><p>The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.</p></div>
+<div class="para"><p>There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level.
+</p>
+</li>
+<li>
+<p>
+Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data.
+</p>
+</li>
+<li>
+<p>
+Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods.
+</p>
+</li>
+</ul></div>
+</div>
+<h2 id="_how_it_works">2. How it works</h2>
+<div class="sectionbody">
+<h3 id="_when_does_validation_happens">2.1. When does validation happens?</h3>
+<div class="para"><p>There are two kinds of Active Record objects: those that correspond to a row inside your database and those who do not. When you create a fresh object, using the <tt>new</tt> method, that object does not belong to the database yet. Once you call <tt>save</tt> upon that object it'll be recorded to it's table. Active Record uses the <tt>new_record?</tt> instance method to discover if an object is already in the database or not. Consider the following simple and very creative Active Record class:</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>We can see how it works by looking at the following script/console output:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>>> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979"))
+=> #<Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil>
+>> p.new_record?
+=> true
+>> p.save
+=> true
+>> p.new_record?
+=> false</tt></pre>
+</div></div>
+<div class="para"><p>Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either <tt>save</tt>, <tt>update_attribute</tt> or <tt>update_attributes</tt>) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.</p></div>
+<h3 id="_the_meaning_of_em_valid_em">2.2. The meaning of <em>valid</em></h3>
+<div class="para"><p>For verifying if an object is valid, Active Record uses the <tt>valid?</tt> method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the <tt>errors</tt> instance method. The proccess is really simple: If the <tt>errors</tt> method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the <tt>errors</tt> collection.</p></div>
+</div>
+<h2 id="_the_declarative_validation_helpers">3. The declarative validation helpers</h2>
+<div class="sectionbody">
+<div class="para"><p>Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you'll write, so you don't need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object's <tt>errors</tt> collection, this message being associated with the field being validated.</p></div>
+<div class="para"><p>Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes.</p></div>
+<div class="para"><p>All these helpers accept the <tt>:on</tt> and <tt>:message</tt> options, which define when the validation should be applied and what message should be added to the <tt>errors</tt> collection when it fails, respectively. The <tt>:on</tt> option takes one the values <tt>:save</tt> (it's the default), <tt>:create</tt> or <tt>:update</tt>. There is a default error message for each one of the validation helpers. These messages are used when the <tt>:message</tt> option isn't used. Let's take a look at each one of the available helpers, listed in alphabetic order.</p></div>
+<h3 id="_the_tt_validates_acceptance_of_tt_helper">3.1. The <tt>validates_acceptance_of</tt> helper</h3>
+<div class="para"><p>Validates that a checkbox has been checked for agreement purposes. It's normally used when the user needs to agree with your application's terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this <em>acceptance</em> does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_acceptance_of <span style="color: #990000">:</span>terms_of_service
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The default error message for <tt>validates_acceptance_of</tt> is "<em>must be accepted</em>"</p></div>
+<div class="para"><p><tt>validates_acceptance_of</tt> can receive an <tt>:accept</tt> option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it.</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_acceptance_of <span style="color: #990000">:</span>terms_of_service<span style="color: #990000">,</span> <span style="color: #990000">:</span>accept <span style="color: #990000">=></span> <span style="color: #FF0000">'yes'</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_the_tt_validates_associated_tt_helper">3.2. The <tt>validates_associated</tt> helper</h3>
+<div class="para"><p>You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, <tt>valid?</tt> will be called upon each one of the associated objects.</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-weight: bold"><span style="color: #0000FF">class</span></span> Library <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ has_many <span style="color: #990000">:</span>books
+ validates_associated <span style="color: #990000">:</span>books
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>This validation will work with all the association types.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/caution.png" alt="Caution" />
+</td>
+<td class="content">Pay attention not to use <tt>validates_associated</tt> on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.</td>
+</tr></table>
+</div>
+<div class="para"><p>The default error message for <tt>validates_associated</tt> is "<em>is invalid</em>". Note that the errors for each failed validation in the associated objects will be set there and not in this model.</p></div>
+<h3 id="_the_tt_validates_confirmation_of_tt_helper">3.3. The <tt>validates_confirmation_of</tt> helper</h3>
+<div class="para"><p>You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with <em>_confirmation</em> appended.</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_confirmation_of <span style="color: #990000">:</span>email
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>In your view template you could use something like</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt><%= text_field :person, :email %>
+<%= text_field :person, :email_confirmation %></tt></pre>
+</div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">This check is performed only if <tt>email_confirmation</tt> is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at <tt>validates_presence_of</tt> later on this guide):</td>
+</tr></table>
+</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_confirmation_of <span style="color: #990000">:</span>email
+ validates_presence_of <span style="color: #990000">:</span>email_confirmation
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The default error message for <tt>validates_confirmation_of</tt> is "<em>doesn't match confirmation</em>"</p></div>
+<h3 id="_the_tt_validates_each_tt_helper">3.4. The <tt>validates_each</tt> helper</h3>
+<div class="para"><p>This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to <tt>validates_each</tt> will be tested against it. In the following example, we don't want names and surnames to begin with lower case.</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_each <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>surname <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>model<span style="color: #990000">,</span> attr<span style="color: #990000">,</span> value<span style="color: #990000">|</span>
+ model<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>add<span style="color: #990000">(</span>attr<span style="color: #990000">,</span> <span style="color: #FF0000">'Must start with upper case'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> value <span style="color: #990000">=~</span> <span style="color: #FF6600">/^[a-z]/</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="para"><p>The block receives the model, the attribute's name and the attribute's value. If your validation fails, you can add an error message to the model, therefore making it invalid.</p></div>
+<h3 id="_the_tt_validates_exclusion_of_tt_helper">3.5. The <tt>validates_exclusion_of</tt> helper</h3>
+<div class="para"><p>This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.</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-weight: bold"><span style="color: #0000FF">class</span></span> MovieFile <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_exclusion_of <span style="color: #990000">:</span>format<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=></span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>mov avi<span style="color: #990000">),</span> <span style="color: #990000">:</span>message <span style="color: #990000">=></span> <span style="color: #FF0000">"Extension %s is not allowed"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The <tt>validates_exclusion_of</tt> helper has an option <tt>:in</tt> that receives the set of values that will not be accepted for the validated attributes. The <tt>:in</tt> option has an alias called <tt>:within</tt> that you can use for the same purpose, if you'd like to. In the previous example we used the <tt>:message</tt> option to show how we can personalize it with the current attribute's value, through the <tt>%s</tt> format mask.</p></div>
+<div class="para"><p>The default error message for <tt>validates_exclusion_of</tt> is "<em>is not included in the list</em>".</p></div>
+<h3 id="_the_tt_validates_format_of_tt_helper">3.6. The <tt>validates_format_of</tt> helper</h3>
+<div class="para"><p>This helper validates the attributes's values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the <tt>:with</tt> option.</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-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_format_of <span style="color: #990000">:</span>description<span style="color: #990000">,</span> <span style="color: #990000">:</span>with <span style="color: #990000">=></span> <span style="color: #FF6600">/^[a-zA-Z]+$/</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=></span> <span style="color: #FF0000">"Only letters allowed"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The default error message for <tt>validates_format_of</tt> is "<em>is invalid</em>".</p></div>
+<h3 id="_the_tt_validates_inclusion_of_tt_helper">3.7. The <tt>validates_inclusion_of</tt> helper</h3>
+<div class="para"><p>This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.</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-weight: bold"><span style="color: #0000FF">class</span></span> Coffee <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=></span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span> <span style="color: #990000">:</span>message <span style="color: #990000">=></span> <span style="color: #FF0000">"%s is not a valid size"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The <tt>validates_inclusion_of</tt> helper has an option <tt>:in</tt> that receives the set of values that will be accepted. The <tt>:in</tt> option has an alias called <tt>:within</tt> that you can use for the same purpose, if you'd like to. In the previous example we used the <tt>:message</tt> option to show how we can personalize it with the current attribute's value, through the <tt>%s</tt> format mask.</p></div>
+<div class="para"><p>The default error message for <tt>validates_inclusion_of</tt> is "<em>is not included in the list</em>".</p></div>
+<h3 id="_the_tt_validates_length_of_tt_helper">3.8. The <tt>validates_length_of</tt> helper</h3>
+<div class="para"><p>This helper validates the length of your attribute's value. It can receive a variety of different options, so you can specify length contraints in different ways.</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_length_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>minimum <span style="color: #990000">=></span> <span style="color: #993399">2</span>
+ validates_length_of <span style="color: #990000">:</span>bio<span style="color: #990000">,</span> <span style="color: #990000">:</span>maximum <span style="color: #990000">=></span> <span style="color: #993399">500</span>
+ validates_length_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=></span> <span style="color: #993399">6</span><span style="color: #990000">..</span><span style="color: #993399">20</span>
+ validates_length_of <span style="color: #990000">:</span>registration_number<span style="color: #990000">,</span> <span style="color: #990000">:</span>is <span style="color: #990000">=></span> <span style="color: #993399">6</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The possible length constraint options are:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>:minimum</tt> - The attribute cannot have less than the specified length.
+</p>
+</li>
+<li>
+<p>
+<tt>:maximum</tt> - The attribute cannot have more than the specified length.
+</p>
+</li>
+<li>
+<p>
+<tt>:in</tt> (or <tt>:within</tt>) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
+</p>
+</li>
+<li>
+<p>
+<tt>:is</tt> - The attribute length must be equal to a given value.
+</p>
+</li>
+</ul></div>
+<div class="para"><p>The default error messages depend on the type of length validation being performed. You can personalize these messages, using the <tt>:wrong_length</tt>, <tt>:too_long</tt> and <tt>:too_short</tt> options and the <tt>%d</tt> format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the <tt>:message</tt> option to specify an error message.</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_length_of <span style="color: #990000">:</span>bio<span style="color: #990000">,</span> <span style="color: #990000">:</span>too_long <span style="color: #990000">=></span> <span style="color: #FF0000">"you're writing too much. %d characters is the maximum allowed."</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>This helper has an alias called <tt>validates_size_of</tt>, it's the same helper with a different name. You can use it if you'd like to.</p></div>
+<h3 id="_the_tt_validates_numericallity_of_tt_helper">3.9. The <tt>validates_numericallity_of</tt> helper</h3>
+<div class="para"><p>This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the <tt>:integer_only</tt> option set to true, you can specify that only integral numbers are allowed.</p></div>
+<div class="para"><p>If you use <tt>:integer_only</tt> set to <tt>true</tt>, then it will use the <tt><span>/\A[+\-]?\d+\Z/</span></tt> regular expression to validate the attribute's value. Otherwise, it will try to convert the value using <tt>Kernel.Float</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-weight: bold"><span style="color: #0000FF">class</span></span> Player <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_numericallity_of <span style="color: #990000">:</span>points
+ validates_numericallity_of <span style="color: #990000">:</span>games_played<span style="color: #990000">,</span> <span style="color: #990000">:</span>integer_only <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The default error message for <tt>validates_numericallity_of</tt> is "<em>is not a number</em>".</p></div>
+<h3 id="_the_tt_validates_presence_of_tt_helper">3.10. The <tt>validates_presence_of</tt> helper</h3>
+<div class="para"><p>This helper validates that the attributes are not empty. It uses the <tt>blank?</tt> method to check if the value is either <tt>nil</tt> or an empty string (if the string has only spaces, it will still be considered empty).</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>login<span style="color: #990000">,</span> <span style="color: #990000">:</span>email
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">If you want to be sure that an association is present, you'll need to test if the foreign key used to map the association is present, and not the associated object itself.</td>
+</tr></table>
+</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-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ belongs_to <span style="color: #990000">:</span>order
+ validates_presence_of <span style="color: #990000">:</span>order_id
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in ⇒ [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # ⇒ true</td>
+</tr></table>
+</div>
+<div class="para"><p>The default error message for <tt>validates_presence_of</tt> is "<em>can't be empty</em>".</p></div>
+<h3 id="_the_tt_validates_uniqueness_of_tt_helper">3.11. The <tt>validates_uniqueness_of</tt> helper</h3>
+<div class="para"><p>This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database.</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-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_uniqueness_of <span style="color: #990000">:</span>email
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The validation happens by performing a SQL query into the model's table, searching for a record where the attribute that must be validated is equal to the value in the object being validated.</p></div>
+<div class="para"><p>There is a <tt>:scope</tt> option that you can use to specify other attributes that must be used to define uniqueness:</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-weight: bold"><span style="color: #0000FF">class</span></span> Holiday <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=></span> <span style="color: #990000">:</span>year<span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=></span> <span style="color: #FF0000">"Should happen once per year"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>There is also a <tt>:case_sensitive</tt> option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>case_sensitive <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The default error message for <tt>validates_uniqueness_of</tt> is "<em>has already been taken</em>".</p></div>
+</div>
+<h2 id="_common_validation_options">4. Common validation options</h2>
+<div class="sectionbody">
+<div class="para"><p>There are some common options that all the validation helpers can use. Here they are, except for the <tt>:if</tt> and <tt>:unless</tt> options, which we'll cover right at the next topic.</p></div>
+<h3 id="_the_tt_allow_nil_tt_option">4.1. The <tt>:allow_nil</tt> option</h3>
+<div class="para"><p>You may use the <tt>:allow_nil</tt> option everytime you just want to trigger a validation if the value being validated is not <tt>nil</tt>. You may be asking yourself if it makes any sense to use <tt>:allow_nil</tt> and <tt>validates_presence_of</tt> together. Well, it does. Remember, validation will be skipped only for <tt>nil</tt> attributes, but empty strings are not considered <tt>nil</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-weight: bold"><span style="color: #0000FF">class</span></span> Coffee <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=></span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span>
+ <span style="color: #990000">:</span>message <span style="color: #990000">=></span> <span style="color: #FF0000">"%s is not a valid size"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>allow_nil <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_the_tt_message_tt_option">4.2. The <tt>:message</tt> option</h3>
+<div class="para"><p>As stated before, the <tt>:message</tt> option lets you specify the message that will be added to the <tt>errors</tt> collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.</p></div>
+<h3 id="_the_tt_on_tt_option">4.3. The <tt>:on</tt> option</h3>
+<div class="para"><p>As stated before, the <tt>:on</tt> option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use <tt>:on =<span>></span> :create</tt> to run the validation only when a new record is created or <tt>:on =<span>></span> :update</tt> to run the validation only when a record is updated.</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_uniqueness_of <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=></span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900"># => it will be possible to update email with a duplicated value</span></span>
+ validates_numericallity_of <span style="color: #990000">:</span>age<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=></span> <span style="color: #990000">:</span>update <span style="font-style: italic"><span style="color: #9A1900"># => it will be possible to create the record with a 'non-numerical age'</span></span>
+ validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=></span> <span style="color: #990000">:</span>save <span style="font-style: italic"><span style="color: #9A1900"># => that's the default</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_conditional_validation">5. Conditional validation</h2>
+<div class="sectionbody">
+<div class="para"><p>Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the <tt>:if</tt> and <tt>:unless</tt> options, which can take a symbol, a string or a Ruby Proc. You may use the <tt>:if</tt> option when you want to specify when the validation <strong>should</strong> happen. If you want to specify when the validation <strong>should not</strong> happen, then you may use the <tt>:unless</tt> option.</p></div>
+<h3 id="_using_a_symbol_with_the_tt_if_tt_and_tt_unless_tt_options">5.1. Using a symbol with the <tt>:if</tt> and <tt>:unless</tt> options</h3>
+<div class="para"><p>You can associated the <tt>:if</tt> and <tt>:unless</tt> options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.</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-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>card_number<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">=></span> <span style="color: #990000">:</span>paid_with_card?
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> paid_with_card?
+ payment_type <span style="color: #990000">==</span> <span style="color: #FF0000">"card"</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>
+<h3 id="_using_a_string_with_the_tt_if_tt_and_tt_unless_tt_options">5.2. Using a string with the <tt>:if</tt> and <tt>:unless</tt> options</h3>
+<div class="para"><p>You can also use a string that will be evaluated using <tt>:eval</tt> and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.</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-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>surname<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">=></span> <span style="color: #FF0000">"name.nil?"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_using_a_proc_object_with_the_tt_if_tt_and_tt_unless_tt_options">5.3. Using a Proc object with the <tt>:if</tt> and :<tt>unless</tt> options</h3>
+<div class="para"><p>Finally, it's possible to associate <tt>:if</tt> and <tt>:unless</tt> with a Ruby Proc object which will be called. Using a Proc object can give you the hability to write a condition that will be executed only when the validation happens and not when your code is loaded by the Ruby interpreter. This option is best suited when writing short validation methods, usually one-liners.</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-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_confirmation_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> <span style="color: #990000">=></span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>a<span style="color: #990000">|</span> a<span style="color: #990000">.</span>password<span style="color: #990000">.</span>blank? <span style="color: #FF0000">}</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_writing_your_own_validation_methods">6. Writing your own validation methods</h2>
+<div class="sectionbody">
+<div class="para"><p>When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's <tt>errors</tt> collection.</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-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> validate_on_create
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000"><</span> Date<span style="color: #990000">.</span>today
+ <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="para"><p>If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> methods, passing it the symbols for the methods' names.</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-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validate <span style="color: #990000">:</span>expiration_date_cannot_be_in_the_past<span style="color: #990000">,</span> <span style="color: #990000">:</span>discount_cannot_be_more_than_total_value
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> expiration_date_cannot_be_in_the_past
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000"><</span> Date<span style="color: #990000">.</span>today
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> discount_cannot_be_greater_than_total_value
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>discount<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be greater than total value"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> discount <span style="color: #990000"><=</span> total_value
+ <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>
+<h2 id="_changelog">7. Changelog</h2>
+<div class="sectionbody">
+<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks">http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks</a></p></div>
+</div>
+ + </div> + </div> +</body> +</html> diff --git a/railties/doc/guides/html/authors.html b/railties/doc/guides/html/authors.html index 973cf7cd2e..a54135b14d 100644 --- a/railties/doc/guides/html/authors.html +++ b/railties/doc/guides/html/authors.html @@ -218,6 +218,19 @@ work with Rails. His near-daily links and other blogging can be found at <a href Cofounder of <a href="http://www.eventioz.com">Eventioz</a>. He has been using Rails since 2006 and contributing since early 2008.
Can be found at gmail, twitter, freenode, everywhere as miloops.</p></div>
</div></div>
+<div class="sidebarblock" id="hawe">
+<div class="sidebar-content">
+<div class="sidebar-title">Heiko Webers</div>
+<div class="para"><p>Heiko Webers is the founder of <a href="http://www.bauland42.de">bauland42</a>, a German web application security consulting and development
+company focused on Ruby on Rails. He blogs at <a href="http://www.rorsecurity.info">http://www.rorsecurity.info</a>. After 10 years of desktop application development,
+Heiko has rarely looked back.</p></div>
+</div></div>
+<div class="sidebarblock" id="toretore">
+<div class="sidebar-content">
+<div class="sidebar-title">Tore Darell</div>
+<div class="para"><p>Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails
+and unobtrusive JavaScript. His home on the internet is his blog <a href="http://tore.darell.no/">Sneaky Abstractions</a>.</p></div>
+</div></div>
</div>
</div>
diff --git a/railties/doc/guides/html/caching_with_rails.html b/railties/doc/guides/html/caching_with_rails.html index df30c46c35..7aa5999e1a 100644 --- a/railties/doc/guides/html/caching_with_rails.html +++ b/railties/doc/guides/html/caching_with_rails.html @@ -235,48 +235,54 @@ need to return to those hungry web clients in the shortest time possible.</p></d <div class="sectionbody">
<div class="para"><p>This is an introduction to the three types of caching techniques that Rails
provides by default without the use of any third party plugins.</p></div>
-<div class="para"><p>To get started make sure Base.perform_caching is set to true for your
-environment.</p></div>
+<div class="para"><p>To get started make sure config.action_controller.perform_caching is set
+to true for your environment. This flag is normally set in the
+corresponding config/environments/*.rb and caching is disabled by default
+there for development and test, and enabled for production.</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>Base<span style="color: #990000">.</span>perform_caching <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+<pre><tt>config<span style="color: #990000">.</span>action_controller<span style="color: #990000">.</span>perform_caching <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
</tt></pre></div></div>
<h3 id="_page_caching">1.1. Page Caching</h3>
<div class="para"><p>Page caching is a Rails mechanism which allows the request for a generated
page to be fulfilled by the webserver, without ever having to go through the
-Rails stack at all. Obviously, this is super fast. Unfortunately, it can't be
+Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be
applied to every situation (such as pages that need authentication) and since
the webserver is literally just serving a file from the filesystem, cache
expiration is an issue that needs to be dealt with.</p></div>
<div class="para"><p>So, how do you enable this super-fast cache behavior? Simple, let's say you
-have a controller called ProductController and a <em>list</em> action that lists all
+have a controller called ProductsController and a <em>list</em> action that lists all
the products</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-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000"><</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000"><</span> ActionController
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>index
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> list<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">def</span></span> index<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>
</tt></pre></div></div>
-<div class="para"><p>The first time anyone requestsion products/list, Rails will generate a file
-called list.html and the webserver will then look for that file before it
-passes the next request for products/list to your Rails application.</p></div>
+<div class="para"><p>The first time anyone requests products/index, Rails will generate a file
+called index.html and the webserver will then look for that file before it
+passes the next request for products/index to your Rails application.</p></div>
<div class="para"><p>By default, the page cache directory is set to Rails.public_path (which is
-usually set to RAILS_ROOT + "/public") and this can be configured by changing
-the configuration setting Base.cache_public_directory</p></div>
-<div class="para"><p>The page caching mechanism will automatically add a .html exxtension to
+usually set to RAILS_ROOT + "/public") and this can be configured by
+changing the configuration setting ActionController::Base.page_cache_directory. Changing the
+default from /public helps avoid naming conflicts, since you may want to
+put other static html in /public, but changing this will require web
+server reconfiguration to let the web server know where to serve the
+cached files from.</p></div>
+<div class="para"><p>The Page Caching mechanism will automatically add a .html exxtension to
requests for pages that do not have an extension to make it easy for the
webserver to find those pages and this can be configured by changing the
-configuration setting Base.page_cache_extension</p></div>
+configuration setting ActionController::Base.page_cache_extension.</p></div>
<div class="para"><p>In order to expire this page when a new product is added we could extend our
example controler like this:</p></div>
<div class="listingblock">
@@ -284,9 +290,9 @@ example controler like this:</p></div> by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000"><</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000"><</span> ActionController
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> list<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -299,11 +305,11 @@ http://www.gnu.org/software/src-highlite --> <div class="para"><p>If you want a more complicated expiration scheme, you can use cache sweepers
to expire cached objects when things change. This is covered in the section on Sweepers.</p></div>
<h3 id="_action_caching">1.2. Action Caching</h3>
-<div class="para"><p>One of the issues with page caching is that you cannot use it for pages that
+<div class="para"><p>One of the issues with Page Caching is that you cannot use it for pages that
require to restrict access somehow. This is where Action Caching comes in.
Action Caching works like Page Caching except for the fact that the incoming
web request does go from the webserver to the Rails stack and Action Pack so
-that before_filters can be run on it before the cache is served, so that
+that before filters can be run on it before the cache is served, so that
authentication and other restrictions can be used while still serving the
result of the output from a cached copy.</p></div>
<div class="para"><p>Clearing the cache works in the exact same way as with Page Caching.</p></div>
@@ -314,10 +320,10 @@ object, but still cache those pages:</p></div> by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000"><</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000"><</span> ActionController
before_filter <span style="color: #990000">:</span>authenticate<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=></span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>edit<span style="color: #990000">,</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
caches_action <span style="color: #990000">:</span>edit
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> list<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -336,7 +342,7 @@ action should be cached. Also, you can use :layout ⇒ false to cache withou layout so that dynamic information in the layout such as logged in user info
or the number of items in the cart can be left uncached. This feature is
available as of Rails 2.2.</p></div>
-<div class="para"><p>[More: more examples? Walk-through of action caching from request to response?
+<div class="para"><p>[More: more examples? Walk-through of Action Caching from request to response?
Description of Rake tasks to clear cached files? Show example of
subdomain caching? Talk about :cache_path, :if and assing blocks/Procs
to expire_action?]</p></div>
@@ -346,13 +352,13 @@ a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which
have the same caching characteristics. In order to address such a dynamically
created page where different parts of the page need to be cached and expired
-differently Rails provides a mechanism called Fragment caching.</p></div>
-<div class="para"><p>Fragment caching allows a fragment of view logic to be wrapped in a cache
+differently Rails provides a mechanism called Fragment Caching.</p></div>
+<div class="para"><p>Fragment Caching allows a fragment of view logic to be wrapped in a cache
block and served out of the cache store when the next request comes in.</p></div>
-<div class="para"><p>As an example, if you wanted to show all the orders placed on your website in
-real time and didn't want to cache that part of the page, but did want to
-cache the part of the page which lists all products available, you could use
-this piece of code:</p></div>
+<div class="para"><p>As an example, if you wanted to show all the orders placed on your website
+in real time and didn't want to cache that part of the page, but did want
+to cache the part of the page which lists all products available, you
+could use this piece of code:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -371,7 +377,7 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>The cache block in our example will bind to the action that called it and is
written out to the same place as the Action Cache, which means that if you
-want to cache multiple fragments per action, you should provide an action_path to the cache call:</p></div>
+want to cache multiple fragments per action, you should provide an action_suffix to the cache call:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -439,10 +445,10 @@ following:</p></div> by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000"><</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000"><</span> ActionController
before_filter <span style="color: #990000">:</span>authenticate<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=></span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>edit<span style="color: #990000">,</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
caches_action <span style="color: #990000">:</span>edit
cache_sweeper <span style="color: #990000">:</span>store_sweeper<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=></span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
@@ -468,10 +474,10 @@ database again.</p></div> by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000"><</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000"><</span> ActionController
before_filter <span style="color: #990000">:</span>authenticate<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=></span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>edit<span style="color: #990000">,</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
caches_action <span style="color: #990000">:</span>edit
cache_sweeper <span style="color: #990000">:</span>store_sweeper<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=></span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
diff --git a/railties/doc/guides/html/command_line.html b/railties/doc/guides/html/command_line.html new file mode 100644 index 0000000000..2add20446e --- /dev/null +++ b/railties/doc/guides/html/command_line.html @@ -0,0 +1,434 @@ +<!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>A Guide to The Rails Command Line</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="#_command_line_basics">Command Line Basics</a> + <ul> + + <li><a href="#_rails">rails</a></li> + + <li><a href="#_server">server</a></li> + + <li><a href="#_generate">generate</a></li> + + </ul> + </li> + </ol> + </div> + + <div id="content"> + <h1>A Guide to The Rails Command Line</h1> + <div id="preamble">
+<div class="sectionbody">
+<div class="para"><p>Rails comes with every command line tool you'll need to</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Create a Rails application
+</p>
+</li>
+<li>
+<p>
+Generate models, controllers, database migrations, and unit tests
+</p>
+</li>
+<li>
+<p>
+Start a development server
+</p>
+</li>
+<li>
+<p>
+Mess with objects through an interactive shell
+</p>
+</li>
+<li>
+<p>
+Profile and benchmark your new creation
+</p>
+</li>
+</ul></div>
+<div class="para"><p>… and much, much more! (Buy now!)</p></div>
+<div class="para"><p>This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.</p></div>
+</div>
+</div>
+<h2 id="_command_line_basics">1. Command Line Basics</h2>
+<div class="sectionbody">
+<div class="para"><p>There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+console
+</p>
+</li>
+<li>
+<p>
+server
+</p>
+</li>
+<li>
+<p>
+rake
+</p>
+</li>
+<li>
+<p>
+generate
+</p>
+</li>
+<li>
+<p>
+rails
+</p>
+</li>
+</ul></div>
+<div class="para"><p>Let's create a simple Rails application to step through each of these commands in context.</p></div>
+<h3 id="_rails">1.1. rails</h3>
+<div class="para"><p>The first thing we'll want to do is create a new Rails application by running the <tt>rails</tt> command after installing Rails.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">You know you need the rails gem installed by typing <tt>gem install rails</tt> first, right? Okay, okay, just making sure.</td>
+</tr></table>
+</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>$ rails commandsapp
+
+ create
+ create app/controllers
+ create app/helpers
+ create app/models
+ <span style="color: #990000">...</span>
+ <span style="color: #990000">...</span>
+ create log/production<span style="color: #990000">.</span>log
+ create log/development<span style="color: #990000">.</span>log
+ create log/test<span style="color: #990000">.</span>log
+</tt></pre></div></div>
+<div class="para"><p>Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">This output will seem very familiar when we get to the <tt>generate</tt> command. Creepy foreshadowing!</td>
+</tr></table>
+</div>
+<h3 id="_server">1.2. server</h3>
+<div class="para"><p>Let's try it! The <tt>server</tt> command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section]</td>
+</tr></table>
+</div>
+<div class="para"><p>Here we'll flex our <tt>server</tt> command, which without any prodding of any kind will run our new shiny Rails app:</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>$ cd commandsapp
+$ <span style="color: #990000">.</span>/script/server
+<span style="color: #990000">=></span> Booting WEBrick<span style="color: #990000">...</span>
+<span style="color: #990000">=></span> Rails <span style="color: #993399">2.2</span><span style="color: #990000">.</span><span style="color: #993399">0</span> application started on http<span style="color: #990000">://</span><span style="color: #993399">0.0</span><span style="color: #990000">.</span><span style="color: #993399">0.0</span><span style="color: #990000">:</span><span style="color: #993399">3000</span>
+<span style="color: #990000">=></span> Ctrl-C to shutdown server<span style="color: #990000">;</span> call with --help <span style="font-weight: bold"><span style="color: #0000FF">for</span></span> options
+<span style="color: #990000">[</span><span style="color: #993399">2008</span>-<span style="color: #993399">11</span>-<span style="color: #993399">04</span> <span style="color: #993399">10</span><span style="color: #990000">:</span><span style="color: #993399">11</span><span style="color: #990000">:</span><span style="color: #993399">38</span><span style="color: #990000">]</span> INFO WEBrick <span style="color: #993399">1.3</span><span style="color: #990000">.</span><span style="color: #993399">1</span>
+<span style="color: #990000">[</span><span style="color: #993399">2008</span>-<span style="color: #993399">11</span>-<span style="color: #993399">04</span> <span style="color: #993399">10</span><span style="color: #990000">:</span><span style="color: #993399">11</span><span style="color: #990000">:</span><span style="color: #993399">38</span><span style="color: #990000">]</span> INFO ruby <span style="color: #993399">1.8</span><span style="color: #990000">.</span><span style="color: #993399">5</span> <span style="color: #990000">(</span><span style="color: #993399">2006</span>-<span style="color: #993399">12</span>-<span style="color: #993399">04</span><span style="color: #990000">)</span> <span style="color: #990000">[</span>i486-linux<span style="color: #990000">]</span>
+<span style="color: #990000">[</span><span style="color: #993399">2008</span>-<span style="color: #993399">11</span>-<span style="color: #993399">04</span> <span style="color: #993399">10</span><span style="color: #990000">:</span><span style="color: #993399">11</span><span style="color: #990000">:</span><span style="color: #993399">38</span><span style="color: #990000">]</span> INFO WEBrick<span style="color: #990000">::</span>HTTPServer<span style="font-style: italic"><span style="color: #9A1900">#start: pid=18994 port=3000</span></span>
+</tt></pre></div></div>
+<div class="para"><p>WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to <a href="http://localhost:3000">http://localhost:3000</a>. I'll wait.</p></div>
+<div class="para"><p>See? Cool! It doesn't do much yet, but we'll change that.</p></div>
+<h3 id="_generate">1.3. generate</h3>
+<div class="para"><p>The <tt>generate</tt> command uses templates to create a whole lot of things. You can always find out what's available by running <tt>generate</tt> by itself. Let's do that:</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>/script/generate
+Usage<span style="color: #990000">:</span> <span style="color: #990000">.</span>/script/generate generator <span style="color: #990000">[</span>options<span style="color: #990000">]</span> <span style="color: #990000">[</span>args<span style="color: #990000">]</span>
+
+<span style="color: #990000">...</span>
+<span style="color: #990000">...</span>
+
+Installed Generators
+ Builtin<span style="color: #990000">:</span> controller<span style="color: #990000">,</span> integration_test<span style="color: #990000">,</span> mailer<span style="color: #990000">,</span> migration<span style="color: #990000">,</span> model<span style="color: #990000">,</span> observer<span style="color: #990000">,</span> performance_test<span style="color: #990000">,</span> plugin<span style="color: #990000">,</span> resource<span style="color: #990000">,</span> scaffold<span style="color: #990000">,</span> session_migration
+
+<span style="color: #990000">...</span>
+<span style="color: #990000">...</span>
+</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!</td>
+</tr></table>
+</div>
+<div class="para"><p>Using generators will save you a large amount of time by writing <strong>boilerplate code</strong> for you — necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right?</p></div>
+<div class="para"><p>Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like <tt>rails</tt> or <tt>./script/generate</tt>). For others, you can try adding <tt>—help</tt> or <tt>-h</tt> to the end, as in <tt>./script/server —help</tt>.</td>
+</tr></table>
+</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>/script/generate controller
+Usage<span style="color: #990000">:</span> <span style="color: #990000">.</span>/script/generate controller ControllerName <span style="color: #990000">[</span>options<span style="color: #990000">]</span>
+
+<span style="color: #990000">...</span>
+<span style="color: #990000">...</span>
+
+Example<span style="color: #990000">:</span>
+ `<span style="color: #990000">.</span>/script/generate controller CreditCard open debit credit close`
+
+ Credit card controller with URLs like /credit_card/debit<span style="color: #990000">.</span>
+ Controller<span style="color: #990000">:</span> app/controllers/credit_card_controller<span style="color: #990000">.</span>rb
+ Views<span style="color: #990000">:</span> app/views/credit_card/debit<span style="color: #990000">.</span>html<span style="color: #990000">.</span>erb <span style="color: #990000">[...]</span>
+ Helper<span style="color: #990000">:</span> app/helpers/credit_card_helper<span style="color: #990000">.</span>rb
+ Test<span style="color: #990000">:</span> test/functional/credit_card_controller_test<span style="color: #990000">.</span>rb
+
+Modules Example<span style="color: #990000">:</span>
+ `<span style="color: #990000">.</span>/script/generate controller <span style="color: #FF0000">'admin/credit_card'</span> <span style="font-weight: bold"><span style="color: #0000FF">suspend</span></span> late_fee`
+
+ Credit card admin controller with URLs /admin/credit_card/suspend<span style="color: #990000">.</span>
+ Controller<span style="color: #990000">:</span> app/controllers/admin/credit_card_controller<span style="color: #990000">.</span>rb
+ Views<span style="color: #990000">:</span> app/views/admin/credit_card/debit<span style="color: #990000">.</span>html<span style="color: #990000">.</span>erb <span style="color: #990000">[...]</span>
+ Helper<span style="color: #990000">:</span> app/helpers/admin/credit_card_helper<span style="color: #990000">.</span>rb
+ Test<span style="color: #990000">:</span> test/functional/admin/credit_card_controller_test<span style="color: #990000">.</span>rb
+</tt></pre></div></div>
+<div class="para"><p>Ah, the controller generator is expecting parameters in the form of <tt>generate controller ControllerName action1 action2</tt>. Let's make a <tt>Greetings</tt> controller with an action of <strong>hello</strong>, which will say something nice to us.</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>/script/generate controller Greeting hello
+ exists app/controllers<span style="color: #990000">/</span>
+ exists app/helpers<span style="color: #990000">/</span>
+ create app/views/greeting
+ exists test/functional<span style="color: #990000">/</span>
+ create app/controllers/greetings_controller<span style="color: #990000">.</span>rb
+ create test/functional/greetings_controller_test<span style="color: #990000">.</span>rb
+ create app/helpers/greetings_helper<span style="color: #990000">.</span>rb
+ create app/views/greetings/hello<span style="color: #990000">.</span>html<span style="color: #990000">.</span>erb
+</tt></pre></div></div>
+<div class="para"><p>Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command!</p></div>
+</div>
+ + </div> + </div> +</body> +</html> diff --git a/railties/doc/guides/html/configuring.html b/railties/doc/guides/html/configuring.html new file mode 100644 index 0000000000..4aa3a0f545 --- /dev/null +++ b/railties/doc/guides/html/configuring.html @@ -0,0 +1,438 @@ +<!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>Configuring Rails Applications</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="#_locations_for_initialization_code">Locations for Initialization Code</a> + </li> + <li> + <a href="#_using_a_preinitializer">Using a Preinitializer</a> + </li> + <li> + <a href="#_configuring_rails_components">Configuring Rails Components</a> + <ul> + + <li><a href="#_configuring_active_record">Configuring Active Record</a></li> + + <li><a href="#_configuring_action_controller">Configuring Action Controller</a></li> + + <li><a href="#_configuring_action_view">Configuring Action View</a></li> + + <li><a href="#_configuring_action_mailer">Configuring Action Mailer</a></li> + + <li><a href="#_configuring_active_resource">Configuring Active Resource</a></li> + + <li><a href="#_configuring_active_support">Configuring Active Support</a></li> + + </ul> + </li> + <li> + <a href="#_using_initializers">Using Initializers</a> + </li> + <li> + <a href="#_using_an_after_initializer">Using an After-Initializer</a> + </li> + <li> + <a href="#_changelog">Changelog</a> + </li> + </ol> + </div> + + <div id="content"> + <h1>Configuring Rails Applications</h1> + <div id="preamble">
+<div class="sectionbody">
+<div class="para"><p>This guide covers the configuration and initialization features available to Rails applications. By referring to this guide, you will be able to:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Adjust the behavior of your Rails applications
+</p>
+</li>
+<li>
+<p>
+Add additional code to be run at application start time
+</p>
+</li>
+</ul></div>
+</div>
+</div>
+<h2 id="_locations_for_initialization_code">1. Locations for Initialization Code</h2>
+<div class="sectionbody">
+<div class="para"><p>preinitializers
+environment.rb first
+env-specific files
+initializers (load_application_initializers)
+after-initializer</p></div>
+</div>
+<h2 id="_using_a_preinitializer">2. Using a Preinitializer</h2>
+<div class="sectionbody">
+</div>
+<h2 id="_configuring_rails_components">3. Configuring Rails Components</h2>
+<div class="sectionbody">
+<h3 id="_configuring_active_record">3.1. Configuring Active Record</h3>
+<h3 id="_configuring_action_controller">3.2. Configuring Action Controller</h3>
+<h3 id="_configuring_action_view">3.3. Configuring Action View</h3>
+<h3 id="_configuring_action_mailer">3.4. Configuring Action Mailer</h3>
+<h3 id="_configuring_active_resource">3.5. Configuring Active Resource</h3>
+<h3 id="_configuring_active_support">3.6. Configuring Active Support</h3>
+</div>
+<h2 id="_using_initializers">4. Using Initializers</h2>
+<div class="sectionbody">
+<div class="literalblock">
+<div class="content">
+<pre><tt>organization, controlling load order</tt></pre>
+</div></div>
+</div>
+<h2 id="_using_an_after_initializer">5. Using an After-Initializer</h2>
+<div class="sectionbody">
+</div>
+<h2 id="_changelog">6. Changelog</h2>
+<div class="sectionbody">
+<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28">Lighthouse ticket</a></p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+November 5, 2008: Rough outline by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
+</p>
+</li>
+</ul></div>
+<div class="para"><p>actionmailer/lib/action_mailer/base.rb
+257: cattr_accessor :logger
+267: cattr_accessor :smtp_settings
+273: cattr_accessor :sendmail_settings
+276: cattr_accessor :raise_delivery_errors
+282: cattr_accessor :perform_deliveries
+285: cattr_accessor :deliveries
+288: cattr_accessor :default_charset
+291: cattr_accessor :default_content_type
+294: cattr_accessor :default_mime_version
+297: cattr_accessor :default_implicit_parts_order
+299: cattr_reader :protected_instance_variables</p></div>
+<div class="para"><p>actionmailer/Rakefile
+36: rdoc.options << <em>—line-numbers</em> << <em>—inline-source</em> << <em>-A cattr_accessor=object</em></p></div>
+<div class="para"><p>actionpack/lib/action_controller/base.rb
+263: cattr_reader :protected_instance_variables
+273: cattr_accessor :asset_host
+279: cattr_accessor :consider_all_requests_local
+285: cattr_accessor :allow_concurrency
+317: cattr_accessor :param_parsers
+321: cattr_accessor :default_charset
+325: cattr_accessor :logger
+329: cattr_accessor :resource_action_separator
+333: cattr_accessor :resources_path_names
+337: cattr_accessor :request_forgery_protection_token
+341: cattr_accessor :optimise_named_routes
+351: cattr_accessor :use_accept_header
+361: cattr_accessor :relative_url_root</p></div>
+<div class="para"><p>actionpack/lib/action_controller/caching/pages.rb
+55: cattr_accessor :page_cache_directory
+58: cattr_accessor :page_cache_extension</p></div>
+<div class="para"><p>actionpack/lib/action_controller/caching.rb
+37: cattr_reader :cache_store
+48: cattr_accessor :perform_caching</p></div>
+<div class="para"><p>actionpack/lib/action_controller/dispatcher.rb
+98: cattr_accessor :error_file_path</p></div>
+<div class="para"><p>actionpack/lib/action_controller/mime_type.rb
+24: cattr_reader :html_types, :unverifiable_types</p></div>
+<div class="para"><p>actionpack/lib/action_controller/rescue.rb
+36: base.cattr_accessor :rescue_responses
+40: base.cattr_accessor :rescue_templates</p></div>
+<div class="para"><p>actionpack/lib/action_controller/session/active_record_store.rb
+60: cattr_accessor :data_column_name
+170: cattr_accessor :connection
+173: cattr_accessor :table_name
+177: cattr_accessor :session_id_column
+181: cattr_accessor :data_column
+282: cattr_accessor :session_class</p></div>
+<div class="para"><p>actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+44: cattr_accessor :included_tags, :instance_writer ⇒ false</p></div>
+<div class="para"><p>actionpack/lib/action_view/base.rb
+189: cattr_accessor :debug_rjs
+193: cattr_accessor :warn_cache_misses</p></div>
+<div class="para"><p>actionpack/lib/action_view/helpers/active_record_helper.rb
+7: cattr_accessor :field_error_proc</p></div>
+<div class="para"><p>actionpack/lib/action_view/helpers/form_helper.rb
+805: cattr_accessor :default_form_builder</p></div>
+<div class="para"><p>actionpack/lib/action_view/template_handlers/erb.rb
+47: cattr_accessor :erb_trim_mode</p></div>
+<div class="para"><p>actionpack/test/active_record_unit.rb
+5: cattr_accessor :able_to_connect
+6: cattr_accessor :connected</p></div>
+<div class="para"><p>actionpack/test/controller/filters_test.rb
+286: cattr_accessor :execution_log</p></div>
+<div class="para"><p>actionpack/test/template/form_options_helper_test.rb
+3:TZInfo::Timezone.cattr_reader :loaded_zones</p></div>
+<div class="para"><p>activemodel/lib/active_model/errors.rb
+28: cattr_accessor :default_error_messages</p></div>
+<div class="para"><p>activemodel/Rakefile
+19: rdoc.options << <em>—line-numbers</em> << <em>—inline-source</em> << <em>-A cattr_accessor=object</em></p></div>
+<div class="para"><p>activerecord/lib/active_record/attribute_methods.rb
+9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer ⇒ false
+11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer ⇒ false</p></div>
+<div class="para"><p>activerecord/lib/active_record/base.rb
+394: cattr_accessor :logger, :instance_writer ⇒ false
+443: cattr_accessor :configurations, :instance_writer ⇒ false
+450: cattr_accessor :primary_key_prefix_type, :instance_writer ⇒ false
+456: cattr_accessor :table_name_prefix, :instance_writer ⇒ false
+461: cattr_accessor :table_name_suffix, :instance_writer ⇒ false
+467: cattr_accessor :pluralize_table_names, :instance_writer ⇒ false
+473: cattr_accessor :colorize_logging, :instance_writer ⇒ false
+478: cattr_accessor :default_timezone, :instance_writer ⇒ false
+487: cattr_accessor :schema_format , :instance_writer ⇒ false
+491: cattr_accessor :timestamped_migrations , :instance_writer ⇒ false</p></div>
+<div class="para"><p>activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
+11: cattr_accessor :connection_handler, :instance_writer ⇒ false</p></div>
+<div class="para"><p>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+166: cattr_accessor :emulate_booleans</p></div>
+<div class="para"><p>activerecord/lib/active_record/fixtures.rb
+498: cattr_accessor :all_loaded_fixtures</p></div>
+<div class="para"><p>activerecord/lib/active_record/locking/optimistic.rb
+38: base.cattr_accessor :lock_optimistically, :instance_writer ⇒ false</p></div>
+<div class="para"><p>activerecord/lib/active_record/migration.rb
+259: cattr_accessor :verbose</p></div>
+<div class="para"><p>activerecord/lib/active_record/schema_dumper.rb
+13: cattr_accessor :ignore_tables</p></div>
+<div class="para"><p>activerecord/lib/active_record/serializers/json_serializer.rb
+4: base.cattr_accessor :include_root_in_json, :instance_writer ⇒ false</p></div>
+<div class="para"><p>activerecord/Rakefile
+142: rdoc.options << <em>—line-numbers</em> << <em>—inline-source</em> << <em>-A cattr_accessor=object</em></p></div>
+<div class="para"><p>activerecord/test/cases/lifecycle_test.rb
+61: cattr_reader :last_inherited</p></div>
+<div class="para"><p>activerecord/test/cases/mixin_test.rb
+9: cattr_accessor :forced_now_time</p></div>
+<div class="para"><p>activeresource/lib/active_resource/base.rb
+206: cattr_accessor :logger</p></div>
+<div class="para"><p>activeresource/Rakefile
+43: rdoc.options << <em>—line-numbers</em> << <em>—inline-source</em> << <em>-A cattr_accessor=object</em></p></div>
+<div class="para"><p>activesupport/lib/active_support/buffered_logger.rb
+17: cattr_accessor :silencer</p></div>
+<div class="para"><p>activesupport/lib/active_support/cache.rb
+81: cattr_accessor :logger</p></div>
+<div class="para"><p>activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
+5:# cattr_accessor :hair_colors
+10: def cattr_reader(*syms)
+29: def cattr_writer(*syms)
+50: def cattr_accessor(*syms)
+51: cattr_reader(*syms)
+52: cattr_writer(*syms)</p></div>
+<div class="para"><p>activesupport/lib/active_support/core_ext/logger.rb
+34: cattr_accessor :silencer</p></div>
+<div class="para"><p>activesupport/test/core_ext/class/attribute_accessor_test.rb
+6: cattr_accessor :foo
+7: cattr_accessor :bar, :instance_writer ⇒ false</p></div>
+<div class="para"><p>activesupport/test/core_ext/module/synchronization_test.rb
+6: @target.cattr_accessor :mutex, :instance_writer ⇒ false</p></div>
+<div class="para"><p>railties/doc/guides/html/creating_plugins.html
+786: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field
+860: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field</p></div>
+<div class="para"><p>railties/lib/rails_generator/base.rb
+93: cattr_accessor :logger</p></div>
+<div class="para"><p>railties/Rakefile
+265: rdoc.options << <em>—line-numbers</em> << <em>—inline-source</em> << <em>—accessor</em> << <em>cattr_accessor=object</em></p></div>
+<div class="para"><p>railties/test/rails_info_controller_test.rb
+12: cattr_accessor :local_request</p></div>
+<div class="para"><p>Rakefile
+32: rdoc.options << <em>-A cattr_accessor=object</em></p></div>
+</div>
+ + </div> + </div> +</body> +</html> diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 48d5f03687..375d216b4a 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -204,26 +204,61 @@ ul#navMain { <li><a href="#_create_the_basic_app">Create the basic app</a></li> - <li><a href="#_create_the_plugin">Create the plugin</a></li> + <li><a href="#_generate_the_plugin_skeleton">Generate the plugin skeleton</a></li> <li><a href="#_setup_the_plugin_for_testing">Setup the plugin for testing</a></li> + <li><a href="#_run_the_plugin_tests">Run the plugin tests</a></li> + + </ul> + </li> + <li> + <a href="#_extending_core_classes">Extending core classes</a> + <ul> + + <li><a href="#_creating_the_test">Creating the test</a></li> + + <li><a href="#_organize_your_files">Organize your files</a></li> + + <li><a href="#_working_with_init_rb">Working with init.rb</a></li> + </ul> </li> <li> - <a href="#_add_a_tt_to_squawk_tt_method_to_string">Add a <tt>to_squawk</tt> method to String</a> + <a href="#_add_an_tt_acts_as_yaffle_tt_method_to_active_record">Add an <tt>acts_as_yaffle</tt> method to Active Record</a> + <ul> + + <li><a href="#_add_a_class_method">Add a class method</a></li> + + <li><a href="#_add_an_instance_method">Add an instance method</a></li> + + </ul> + </li> + <li> + <a href="#_create_a_generator">Create a generator</a> + <ul> + + <li><a href="#_testing_generators">Testing generators</a></li> + + <li><a href="#_adding_to_the_manifest">Adding to the manifest</a></li> + + <li><a href="#_manually_test_the_generator">Manually test the generator</a></li> + + <li><a href="#_the_usage_file">The USAGE file</a></li> + + </ul> </li> <li> - <a href="#_add_an_tt_acts_as_yaffle_tt_method_to_activerecord">Add an <tt>acts_as_yaffle</tt> method to ActiveRecord</a> + <a href="#_add_a_custom_generator_command">Add a custom generator command</a> </li> <li> - <a href="#_create_a_tt_squawk_info_for_tt_view_helper">Create a <tt>squawk_info_for</tt> view helper</a> + <a href="#_add_a_model">Add a model</a> </li> <li> - <a href="#_create_a_migration_generator">Create a migration generator</a> + <a href="#_add_a_controller">Add a controller</a> </li> <li> - <a href="#_add_a_custom_generator_command">Add a custom generator command</a> + <a href="#_add_a_helper">Add a helper</a> </li> <li> <a href="#_add_a_custom_route">Add a Custom Route</a> @@ -232,12 +267,8 @@ ul#navMain { <a href="#_odds_and_ends">Odds and ends</a> <ul> - <li><a href="#_work_with_init_rb">Work with init.rb</a></li> - <li><a href="#_generate_rdoc_documentation">Generate RDoc Documentation</a></li> - <li><a href="#_store_models_views_helpers_and_controllers_in_your_plugins">Store models, views, helpers, and controllers in your plugins</a></li> - <li><a href="#_write_custom_rake_tasks_in_your_plugin">Write custom Rake tasks in your plugin</a></li> <li><a href="#_store_plugins_in_alternate_locations">Store plugins in alternate locations</a></li> @@ -265,123 +296,107 @@ ul#navMain { <h1>The Basics of Creating Rails Plugins</h1> <div id="preamble">
<div class="sectionbody">
-<div class="para"><p>Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness.</p></div>
-<div class="para"><p>In this tutorial you will learn how to create a plugin that includes:</p></div>
+<div class="para"><p>A Rails plugin is either an extension or a modification of the core framework. Plugins provide:</p></div>
<div class="ilist"><ul>
<li>
<p>
-Core Extensions - extending String with a <tt>to_squawk</tt> method:
+a way for developers to share bleeding-edge ideas without hurting the stable code base
</p>
-<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"># Anywhere</span></span>
-<span style="color: #FF0000">"hello!"</span><span style="color: #990000">.</span>to_squawk <span style="font-style: italic"><span style="color: #9A1900"># => "squawk! hello!"</span></span>
-</tt></pre></div></div>
</li>
<li>
<p>
-An <tt>acts_as_yaffle</tt> method for ActiveRecord models that adds a <tt>squawk</tt> method:
+a segmented architecture so that units of code can be fixed or updated on their own release schedule
</p>
-<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-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
- acts_as_yaffle <span style="color: #990000">:</span>yaffle_text_field <span style="color: #990000">=></span> <span style="color: #990000">:</span>last_sang_at
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
-Hickwall<span style="color: #990000">.</span>new<span style="color: #990000">.</span>squawk<span style="color: #990000">(</span><span style="color: #FF0000">"Hello World"</span><span style="color: #990000">)</span>
-</tt></pre></div></div>
</li>
<li>
<p>
-A view helper that will print out squawking info:
+an outlet for the core developers so that they don’t have to include every cool new feature under the sun
</p>
-<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>squawk_info_for<span style="color: #990000">(</span><span style="color: #009900">@hickwall</span><span style="color: #990000">)</span>
-</tt></pre></div></div>
</li>
+</ul></div>
+<div class="para"><p>After reading this guide you should be familiar with:</p></div>
+<div class="ilist"><ul>
<li>
<p>
-A generator that creates a migration to add squawk columns to a model:
+Creating a plugin from scratch
</p>
-<div class="listingblock">
-<div class="content">
-<pre><tt>script/generate yaffle hickwall</tt></pre>
-</div></div>
</li>
<li>
<p>
-A custom generator command:
+Writing and running tests for the plugin
</p>
-<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-weight: bold"><span style="color: #0000FF">class</span></span> YaffleGenerator <span style="color: #990000"><</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
- m<span style="color: #990000">.</span>yaffle_definition
- <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>
</li>
<li>
<p>
-A custom route method:
+Storing models, views, controllers, helpers and even other plugins in your plugins
+</p>
+</li>
+<li>
+<p>
+Writing generators
+</p>
+</li>
+<li>
+<p>
+Writing custom Rake tasks in your plugin
+</p>
+</li>
+<li>
+<p>
+Generating RDoc documentation for your plugin
+</p>
+</li>
+<li>
+<p>
+Avoiding common pitfalls with <em>init.rb</em>
</p>
-<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>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
- map<span style="color: #990000">.</span>yaffles
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
</li>
</ul></div>
-<div class="para"><p>In addition you'll learn how to:</p></div>
+<div class="para"><p>This guide describes how to build a test-driven plugin that will:</p></div>
<div class="ilist"><ul>
<li>
<p>
-test your plugins.
+Extend core ruby classes like Hash and String
</p>
</li>
<li>
<p>
-work with <em>init.rb</em>, how to store model, views, controllers, helpers and even other plugins in your plugins.
+Add methods to ActiveRecord::Base in the tradition of the <em>acts_as</em> plugins
</p>
</li>
<li>
<p>
-create documentation for your plugin.
+Add a view helper that can be used in erb templates
</p>
</li>
<li>
<p>
-write custom Rake tasks in your plugin.
+Add a new generator that will generate a migration
+</p>
+</li>
+<li>
+<p>
+Add a custom generator command
+</p>
+</li>
+<li>
+<p>
+A custom route method that can be used in routes.rb
</p>
</li>
</ul></div>
+<div class="para"><p>For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.</p></div>
</div>
</div>
<h2 id="_preparation">1. Preparation</h2>
<div class="sectionbody">
<h3 id="_create_the_basic_app">1.1. Create the basic app</h3>
-<div class="para"><p>In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app:</p></div>
+<div class="para"><p>The examples in this guide require that you have a working rails application. To create a simple rails app execute:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>rails plugin_demo
-cd plugin_demo
+<pre><tt>gem install rails
+rails yaffle_guide
+cd yaffle_guide
script/generate scaffold bird name:string
rake db:migrate
script/server</tt></pre>
@@ -392,22 +407,24 @@ script/server</tt></pre> <td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
-<td class="content">The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.</td>
+<td class="content">
+<div class="title">Editor's note:</div>The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.</td>
</tr></table>
</div>
-<h3 id="_create_the_plugin">1.2. Create the plugin</h3>
-<div class="para"><p>The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either <em>CamelCased</em> or <em>under_scored</em>, as an argument. Pass <tt>--with-generator</tt> to add an example generator also.</p></div>
+<h3 id="_generate_the_plugin_skeleton">1.2. Generate the plugin skeleton</h3>
+<div class="para"><p>Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either <em>CamelCased</em> or <em>under_scored</em>, as an argument. Pass <tt>--with-generator</tt> to add an example generator also.</p></div>
<div class="para"><p>This creates a plugin in <em>vendor/plugins</em> including an <em>init.rb</em> and <em>README</em> as well as standard <em>lib</em>, <em>task</em>, and <em>test</em> directories.</p></div>
<div class="para"><p>Examples:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>./script/generate plugin BrowserFilters
-./script/generate plugin BrowserFilters --with-generator</tt></pre>
+<pre><tt>./script/generate plugin yaffle
+./script/generate plugin yaffle --with-generator</tt></pre>
</div></div>
-<div class="para"><p>Later in the plugin we will create a generator, so go ahead and add the <tt>--with-generator</tt> option now:</p></div>
+<div class="para"><p>To get more detailed help on the plugin generator, type <tt>./script/generate plugin</tt>.</p></div>
+<div class="para"><p>Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the <tt>--with-generator</tt> option now:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>script/generate plugin yaffle --with-generator</tt></pre>
+<pre><tt>./script/generate plugin yaffle --with-generator</tt></pre>
</div></div>
<div class="para"><p>You should see the following output:</p></div>
<div class="listingblock">
@@ -430,51 +447,37 @@ create vendor/plugins/yaffle/generators/yaffle/templates create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE</tt></pre>
</div></div>
-<div class="para"><p>For this plugin you won't need the file <em>vendor/plugins/yaffle/lib/yaffle.rb</em> so you can delete that.</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>rm vendor/plugins/yaffle/lib/yaffle.rb</tt></pre>
-</div></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/note.png" alt="Note" />
-</td>
-<td class="content">
-<div class="title">Editor's note:</div>Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be <tt>require "yaffle"</tt>. If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean</td>
-</tr></table>
-</div>
+<div class="para"><p>To begin just change one thing - move <em>init.rb</em> to <em>rails/init.rb</em>.</p></div>
<h3 id="_setup_the_plugin_for_testing">1.3. Setup the plugin for testing</h3>
-<div class="para"><p>Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests.</p></div>
+<div class="para"><p>If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.</p></div>
<div class="para"><p>To setup your plugin to allow for easy testing you'll need to add 3 files:</p></div>
<div class="ilist"><ul>
<li>
<p>
-A <em>database.yml</em> file with all of your connection strings.
+A <em>database.yml</em> file with all of your connection strings
</p>
</li>
<li>
<p>
-A <em>schema.rb</em> file with your table definitions.
+A <em>schema.rb</em> file with your table definitions
</p>
</li>
<li>
<p>
-A test helper that sets up the database before your tests.
+A test helper method that sets up the database
</p>
</li>
</ul></div>
-<div class="para"><p>For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/test/database.yml:</strong></p></div>
<div class="listingblock">
<div class="content">
<pre><tt>sqlite:
:adapter: sqlite
- :dbfile: yaffle_plugin.sqlite.db
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
sqlite3:
:adapter: sqlite3
- :dbfile: yaffle_plugin.sqlite3.db
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
postgresql:
:adapter: postgresql
@@ -486,11 +489,12 @@ postgresql: mysql:
:adapter: mysql
:host: localhost
- :username: rails
- :password:
+ :username: root
+ :password: password
:database: yaffle_plugin_test</tt></pre>
</div></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/test/test_helper.rb:</strong></p></div>
+<div class="para"><p>For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/schema.rb:</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -507,203 +511,273 @@ http://www.gnu.org/software/src-highlite --> t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>last_tweet
t<span style="color: #990000">.</span>datetime <span style="color: #990000">:</span>last_tweeted_at
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ create_table <span style="color: #990000">:</span>woodpeckers<span style="color: #990000">,</span> <span style="color: #990000">:</span>force <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
+ t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
+ <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-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/test/test_helper.rb</span></span>
-
-ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ENV'</span><span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">'test'</span>
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/test_helper.rb:</strong></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>ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ENV'</span><span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">'test'</span>
ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ROOT'</span><span style="color: #990000">]</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">'/../../../..'</span>
<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test/unit'</span>
<span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>expand_path<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ROOT'</span><span style="color: #990000">],</span> <span style="color: #FF0000">'config/environment.rb'</span><span style="color: #990000">))</span>
-config <span style="color: #990000">=</span> YAML<span style="color: #990000">::</span><span style="font-weight: bold"><span style="color: #0000FF">load</span></span><span style="color: #990000">(</span>IO<span style="color: #990000">.</span>read<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">'/database.yml'</span><span style="color: #990000">))</span>
-ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>logger <span style="color: #990000">=</span> Logger<span style="color: #990000">.</span>new<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">"/debug.log"</span><span style="color: #990000">)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> load_schema
+ config <span style="color: #990000">=</span> YAML<span style="color: #990000">::</span><span style="font-weight: bold"><span style="color: #0000FF">load</span></span><span style="color: #990000">(</span>IO<span style="color: #990000">.</span>read<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">'/database.yml'</span><span style="color: #990000">))</span>
+ ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>logger <span style="color: #990000">=</span> Logger<span style="color: #990000">.</span>new<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">"/debug.log"</span><span style="color: #990000">)</span>
-db_adapter <span style="color: #990000">=</span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">'DB'</span><span style="color: #990000">]</span>
+ db_adapter <span style="color: #990000">=</span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">'DB'</span><span style="color: #990000">]</span>
-<span style="font-style: italic"><span style="color: #9A1900"># no db passed, try one of these fine config-free DBs before bombing.</span></span>
-db_adapter <span style="color: #990000">||=</span>
- <span style="font-weight: bold"><span style="color: #0000FF">begin</span></span>
- <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rubygems'</span>
- <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite'</span>
- <span style="color: #FF0000">'sqlite'</span>
- <span style="font-weight: bold"><span style="color: #0000FF">rescue</span></span> MissingSourceFile
+ <span style="font-style: italic"><span style="color: #9A1900"># no db passed, try one of these fine config-free DBs before bombing.</span></span>
+ db_adapter <span style="color: #990000">||=</span>
<span style="font-weight: bold"><span style="color: #0000FF">begin</span></span>
- <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite3'</span>
- <span style="color: #FF0000">'sqlite3'</span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rubygems'</span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite'</span>
+ <span style="color: #FF0000">'sqlite'</span>
<span style="font-weight: bold"><span style="color: #0000FF">rescue</span></span> MissingSourceFile
+ <span style="font-weight: bold"><span style="color: #0000FF">begin</span></span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite3'</span>
+ <span style="color: #FF0000">'sqlite3'</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">rescue</span></span> MissingSourceFile
+ <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">if</span></span> db_adapter<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">raise</span></span> <span style="color: #FF0000">"No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">if</span></span> db_adapter<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
- <span style="font-weight: bold"><span style="color: #0000FF">raise</span></span> <span style="color: #FF0000">"No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."</span>
+ ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>establish_connection<span style="color: #990000">(</span>config<span style="color: #990000">[</span>db_adapter<span style="color: #990000">])</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">load</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">"/schema.rb"</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></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">'/../rails/init.rb'</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Now whenever you write a test that requires the database, you can call <em>load_schema</em>.</p></div>
+<h3 id="_run_the_plugin_tests">1.4. Run the plugin tests</h3>
+<div class="para"><p>Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in <em>vendor/plugins/yaffle/test/yaffle_test.rb</em> with a sample test. Replace the contents of that file with:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/yaffle_test.rb:</strong></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-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
-ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>establish_connection<span style="color: #990000">(</span>config<span style="color: #990000">[</span>db_adapter<span style="color: #990000">])</span>
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
-<span style="font-weight: bold"><span style="color: #0000FF">load</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">"/schema.rb"</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></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">'/../init.rb'</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Wickwall <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
- acts_as_yaffle
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_schema_has_loaded_correctly
+ assert_equal <span style="color: #990000">[],</span> Hickwall<span style="color: #990000">.</span>all
+ assert_equal <span style="color: #990000">[],</span> Wickwall<span style="color: #990000">.</span>all
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Wickwall <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
- acts_as_yaffle <span style="color: #990000">:</span>yaffle_text_field <span style="color: #990000">=></span> <span style="color: #990000">:</span>last_tweet<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field <span style="color: #990000">=></span> <span style="color: #990000">:</span>last_tweeted_at
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p>To run this, go to the plugin directory and run <tt>rake</tt>:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>cd vendor/plugins/yaffle
+rake</tt></pre>
+</div></div>
+<div class="para"><p>You should see output like:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
+-- create_table(:hickwalls, {:force=>true})
+ -> 0.0220s
+-- create_table(:wickwalls, {:force=>true})
+ -> 0.0077s
+-- initialize_schema_migrations_table()
+ -> 0.0007s
+-- assume_migrated_upto_version(0)
+ -> 0.0007s
+Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
+Started
+.
+Finished in 0.002236 seconds.
+
+1 test, 1 assertion, 0 failures, 0 errors</tt></pre>
+</div></div>
+<div class="para"><p>By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>rake DB=sqlite
+rake DB=sqlite3
+rake DB=mysql
+rake DB=postgresql</tt></pre>
+</div></div>
+<div class="para"><p>Now you are ready to test-drive your plugin!</p></div>
</div>
-<h2 id="_add_a_tt_to_squawk_tt_method_to_string">2. Add a <tt>to_squawk</tt> method to String</h2>
+<h2 id="_extending_core_classes">2. Extending core classes</h2>
<div class="sectionbody">
-<div class="para"><p>To update a core class you will have to:</p></div>
+<div class="para"><p>This section will explain how to add a method to String that will be available anywhere in your rails app by:</p></div>
<div class="ilist"><ul>
<li>
<p>
-Write tests for the desired functionality.
-</p>
-</li>
-<li>
-<p>
-Create a file for the code you wish to use.
+Writing tests for the desired behavior
</p>
</li>
<li>
<p>
-Require that file from your <em>init.rb</em>.
+Creating and requiring the correct files
</p>
</li>
</ul></div>
-<div class="para"><p>Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from <em>init.rb</em>. The file you are going to add for this tutorial is <em>lib/core_ext.rb</em>.</p></div>
-<div class="para"><p>First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:</p></div>
+<h3 id="_creating_the_test">2.1. Creating the test</h3>
+<div class="para"><p>In this example you will add a method to String named <tt>to_squawk</tt>. To begin, create a new test file with a few assertions:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/core_ext_test.rb</strong></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"># File: vendor/plugins/yaffle/test/core_ext_test.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test/unit'</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CoreExtTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
- <span style="font-style: italic"><span style="color: #9A1900"># Replace this with your real tests.</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_this_plugin
- flunk
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_to_squawk_prepends_the_word_squawk
+ assert_equal <span style="color: #FF0000">"squawk! Hello World"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"Hello World"</span><span style="color: #990000">.</span>to_squawk
<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="para"><p>Start off by removing the default test, and adding a require statement for your test helper.</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"># File: vendor/plugins/yaffle/test/core_ext_test.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test/unit'</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CoreExtTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
<div class="para"><p>Navigate to your plugin directory and run <tt>rake test</tt>:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>cd vendor/plugins/yaffle
rake test</tt></pre>
</div></div>
-<div class="para"><p>Your test should fail with <tt>no such file to load — ./test/../lib/core_ext.rb (LoadError)</tt> because we haven't created any file yet. Create the file <em>lib/core_ext.rb</em> and re-run the tests. You should see a different error message:</p></div>
+<div class="para"><p>The test above should fail with the message:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt> 1) Error:
+test_to_squawk_prepends_the_word_squawk(CoreExtTest):
+NoMethodError: undefined method `to_squawk' for "Hello World":String
+ ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'</tt></pre>
+</div></div>
+<div class="para"><p>Great - now you are ready to start development.</p></div>
+<h3 id="_organize_your_files">2.2. Organize your files</h3>
+<div class="para"><p>A common pattern in rails plugins is to set up the file structure like this:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>1.) Failure ...
-No tests were specified</tt></pre>
+<pre><tt>|-- lib
+| |-- yaffle
+| | `-- core_ext.rb
+| `-- yaffle.rb</tt></pre>
</div></div>
-<div class="para"><p>Great - now you are ready to start development. The first thing we'll do is to add a method to String called <tt>to_squawk</tt> which will prefix the string with the word “squawk!”. The test will look something like this:</p></div>
+<div class="para"><p>The first thing we need to to is to require our <em>lib/yaffle.rb</em> file from <em>rails/init.rb</em>:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/rails/init.rb</strong></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"># File: vendor/plugins/yaffle/init.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CoreExtTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_string_should_respond_to_squawk
- assert_equal <span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">,</span> <span style="color: #FF0000">""</span><span style="color: #990000">.</span>respond_to?<span style="color: #990000">(:</span>to_squawk<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">def</span></span> test_string_prepend_empty_strings_with_the_word_squawk
- assert_equal <span style="color: #FF0000">"squawk!"</span><span style="color: #990000">,</span> <span style="color: #FF0000">""</span><span style="color: #990000">.</span>to_squawk
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_string_prepend_non_empty_strings_with_the_word_squawk
- assert_equal <span style="color: #FF0000">"squawk! Hello World"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"Hello World"</span><span style="color: #990000">.</span>to_squawk
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'yaffle'</span>
</tt></pre></div></div>
+<div class="para"><p>Then in <em>lib/yaffle.rb</em> require <em>lib/core_ext.rb</em>:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></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"># File: vendor/plugins/yaffle/init.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"core_ext"</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"yaffle/core_ext"</span>
</tt></pre></div></div>
+<div class="para"><p>Finally, create the <em>core_ext.rb</em> file and add the <em>to_squawk</em> method:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/core_ext.rb</strong></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"># File: vendor/plugins/yaffle/lib/core_ext.rb</span></span>
-
-String<span style="color: #990000">.</span>class_eval <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+<pre><tt>String<span style="color: #990000">.</span>class_eval <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> to_squawk
<span style="color: #FF0000">"squawk! #{self}"</span><span style="color: #990000">.</span>strip
<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="para"><p>When monkey-patching existing classes it's often better to use <tt>class_eval</tt> instead of opening the class directly.</p></div>
-<div class="para"><p>To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking:</p></div>
+<div class="para"><p>To test that your method does what it says it does, run the unit tests with <tt>rake</tt> from your plugin directory. To see this in action, fire up a console and start squawking:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>$ ./script/console
>> "Hello World".to_squawk
=> "squawk! Hello World"</tt></pre>
</div></div>
-<div class="para"><p>If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.</p></div>
+<h3 id="_working_with_init_rb">2.3. Working with init.rb</h3>
+<div class="para"><p>When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, <em>init.rb</em> is invoked via <tt>eval</tt> (not <tt>require</tt>) so it has slightly different behavior.</p></div>
+<div class="para"><p>Under certain circumstances if you reopen classes or modules in <em>init.rb</em> you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from <tt>init.rb</tt>, as shown above.</p></div>
+<div class="para"><p>If you must reopen a class in <tt>init.rb</tt> you can use <tt>module_eval</tt> or <tt>class_eval</tt> to avoid any issues:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/init.rb</strong></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>Hash<span style="color: #990000">.</span>class_eval <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> is_a_special_hash?
+ <span style="font-weight: bold"><span style="color: #0000FF">true</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="para"><p>Another way is to explicitly define the top-level module space for all modules and classes, like <tt>::Hash</tt>:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/init.rb</strong></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-weight: bold"><span style="color: #0000FF">class</span></span> <span style="color: #990000">::</span>Hash
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> is_a_special_hash?
+ <span style="font-weight: bold"><span style="color: #0000FF">true</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>
-<h2 id="_add_an_tt_acts_as_yaffle_tt_method_to_activerecord">3. Add an <tt>acts_as_yaffle</tt> method to ActiveRecord</h2>
+<h2 id="_add_an_tt_acts_as_yaffle_tt_method_to_active_record">3. Add an <tt>acts_as_yaffle</tt> method to Active Record</h2>
<div class="sectionbody">
-<div class="para"><p>A common pattern in plugins is to add a method called <tt>acts_as_something</tt> to models. In this case, you want to write a method called <tt>acts_as_yaffle</tt> that adds a <tt>squawk</tt> method to your models.</p></div>
-<div class="para"><p>To keep things clean, create a new test file called <em>acts_as_yaffle_test.rb</em> in your plugin's test directory and require your test helper.</p></div>
+<div class="para"><p>A common pattern in plugins is to add a method called <em>acts_as_something</em> to models. In this case, you want to write a method called <em>acts_as_yaffle</em> that adds a <em>squawk</em> method to your models.</p></div>
+<div class="para"><p>To begin, set up your files so that you have:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></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"># File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
- acts_as_yaffle
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ActsAsYaffleTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></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"># File: vendor/plugins/lib/acts_as_yaffle.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'yaffle/acts_as_yaffle'</span>
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></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-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
+ <span style="font-style: italic"><span style="color: #9A1900"># your code will go here</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>One of the most common plugin patterns for <tt>acts_as_yaffle</tt> plugins is to structure your file like so:</p></div>
+<div class="para"><p>Note that after requiring <em>acts_as_yaffle</em> you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.</p></div>
+<div class="para"><p>One of the most common plugin patterns for <em>acts_as_yaffle</em> plugins is to structure your file like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -727,139 +801,118 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>With structure you can easily separate the methods that will be used for the class (like <tt>Hickwall.some_method</tt>) and the instance (like <tt>@hickwell.some_method</tt>).</p></div>
-<div class="para"><p>Let's add class method named <tt>acts_as_yaffle</tt> - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail.</p></div>
-<div class="para"><p>Back in your <tt>acts_as_yaffle</tt> file, update ClassMethods like so:</p></div>
+<h3 id="_add_a_class_method">3.1. Add a class method</h3>
+<div class="para"><p>This plugin will expect that you've added a method to your model named <em>last_squawk</em>. However, the plugin users might have already defined a method on their model named <em>last_squawk</em> that they use for something else. This plugin will allow the name to be changed by adding a class method called <em>yaffle_text_field</em>.</p></div>
+<div class="para"><p>To start out, write a failing test that shows the behavior you'd like:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></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-weight: bold"><span style="color: #0000FF">module</span></span> ClassMethods
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> acts_as_yaffle<span style="color: #990000">(</span>options <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span>
- send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> InstanceMethods
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ acts_as_yaffle
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:</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"># File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</span></span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Wickwall <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ acts_as_yaffle <span style="color: #990000">:</span>yaffle_text_field <span style="color: #990000">=></span> <span style="color: #990000">:</span>last_tweet
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ActsAsYaffleTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
+
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal <span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> Hickwall<span style="color: #990000">.</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal <span style="color: #FF0000">"last_squawked_at"</span><span style="color: #990000">,</span> Hickwall<span style="color: #990000">.</span>yaffle_date_field
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal <span style="color: #FF0000">"last_tweet"</span><span style="color: #990000">,</span> Wickwall<span style="color: #990000">.</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
- assert_equal <span style="color: #FF0000">"last_tweeted_at"</span><span style="color: #990000">,</span> Wickwall<span style="color: #990000">.</span>yaffle_date_field
- <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="para"><p>To make these tests pass, you could modify your <tt>acts_as_yaffle</tt> file like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></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"># File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
<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>included<span style="color: #990000">(</span>base<span style="color: #990000">)</span>
base<span style="color: #990000">.</span>send <span style="color: #990000">:</span>extend<span style="color: #990000">,</span> ClassMethods
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> ClassMethods
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> acts_as_yaffle<span style="color: #990000">(</span>options <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span>
- cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field
+ cattr_accessor <span style="color: #990000">:</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>yaffle_text_field <span style="color: #990000">=</span> <span style="color: #990000">(</span>options<span style="color: #990000">[:</span>yaffle_text_field<span style="color: #990000">]</span> <span style="color: #990000">||</span> <span style="color: #990000">:</span>last_squawk<span style="color: #990000">).</span>to_s
- <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>yaffle_date_field <span style="color: #990000">=</span> <span style="color: #990000">(</span>options<span style="color: #990000">[:</span>yaffle_date_field<span style="color: #990000">]</span> <span style="color: #990000">||</span> <span style="color: #990000">:</span>last_squawked_at<span style="color: #990000">).</span>to_s
- send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> InstanceMethods
<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">module</span></span> InstanceMethods
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle
</tt></pre></div></div>
-<div class="para"><p>Now you can add tests for the instance methods, and the instance method itself:</p></div>
+<h3 id="_add_an_instance_method">3.2. Add an instance method</h3>
+<div class="para"><p>This plugin will add a method named <em>squawk</em> to any Active Record objects that call <em>acts_as_yaffle</em>. The <em>squawk</em> method will simply set the value of one of the fields in the database.</p></div>
+<div class="para"><p>To start out, write a failing test that shows the behavior you'd like:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></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"># File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ acts_as_yaffle
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Wickwall <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ acts_as_yaffle <span style="color: #990000">:</span>yaffle_text_field <span style="color: #990000">=></span> <span style="color: #990000">:</span>last_tweet
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ActsAsYaffleTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal <span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> Hickwall<span style="color: #990000">.</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal <span style="color: #FF0000">"last_squawked_at"</span><span style="color: #990000">,</span> Hickwall<span style="color: #990000">.</span>yaffle_date_field
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_wickwalls_yaffle_text_field_should_be_last_squawk
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal <span style="color: #FF0000">"last_tweet"</span><span style="color: #990000">,</span> Wickwall<span style="color: #990000">.</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal <span style="color: #FF0000">"last_tweeted_at"</span><span style="color: #990000">,</span> Wickwall<span style="color: #990000">.</span>yaffle_date_field
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_hickwalls_squawk_should_populate_last_squawk
hickwall <span style="color: #990000">=</span> Hickwall<span style="color: #990000">.</span>new
hickwall<span style="color: #990000">.</span>squawk<span style="color: #990000">(</span><span style="color: #FF0000">"Hello World"</span><span style="color: #990000">)</span>
assert_equal <span style="color: #FF0000">"squawk! Hello World"</span><span style="color: #990000">,</span> hickwall<span style="color: #990000">.</span>last_squawk
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_hickwalls_squawk_should_populate_last_squawked_at
- hickwall <span style="color: #990000">=</span> Hickwall<span style="color: #990000">.</span>new
- hickwall<span style="color: #990000">.</span>squawk<span style="color: #990000">(</span><span style="color: #FF0000">"Hello World"</span><span style="color: #990000">)</span>
- assert_equal Date<span style="color: #990000">.</span>today<span style="color: #990000">,</span> hickwall<span style="color: #990000">.</span>last_squawked_at
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_wickwalls_squawk_should_populate_last_tweet
- wickwall <span style="color: #990000">=</span> Wickwall<span style="color: #990000">.</span>new
- wickwall<span style="color: #990000">.</span>squawk<span style="color: #990000">(</span><span style="color: #FF0000">"Hello World"</span><span style="color: #990000">)</span>
- assert_equal <span style="color: #FF0000">"squawk! Hello World"</span><span style="color: #990000">,</span> wickwall<span style="color: #990000">.</span>last_tweet
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_wickwalls_squawk_should_populate_last_tweeted_at
wickwall <span style="color: #990000">=</span> Wickwall<span style="color: #990000">.</span>new
wickwall<span style="color: #990000">.</span>squawk<span style="color: #990000">(</span><span style="color: #FF0000">"Hello World"</span><span style="color: #990000">)</span>
- assert_equal Date<span style="color: #990000">.</span>today<span style="color: #990000">,</span> wickwall<span style="color: #990000">.</span>last_tweeted_at
+ assert_equal <span style="color: #FF0000">"squawk! Hello World"</span><span style="color: #990000">,</span> wickwall<span style="color: #990000">.</span>last_tweet
<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="para"><p>Run this test to make sure the last two tests fail, then update <em>acts_as_yaffle.rb</em> to look like this:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></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"># File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
<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>included<span style="color: #990000">(</span>base<span style="color: #990000">)</span>
base<span style="color: #990000">.</span>send <span style="color: #990000">:</span>extend<span style="color: #990000">,</span> ClassMethods
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> ClassMethods
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> acts_as_yaffle<span style="color: #990000">(</span>options <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span>
- cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field
+ cattr_accessor <span style="color: #990000">:</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>yaffle_text_field <span style="color: #990000">=</span> <span style="color: #990000">(</span>options<span style="color: #990000">[:</span>yaffle_text_field<span style="color: #990000">]</span> <span style="color: #990000">||</span> <span style="color: #990000">:</span>last_squawk<span style="color: #990000">).</span>to_s
- <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>yaffle_date_field <span style="color: #990000">=</span> <span style="color: #990000">(</span>options<span style="color: #990000">[:</span>yaffle_date_field<span style="color: #990000">]</span> <span style="color: #990000">||</span> <span style="color: #990000">:</span>last_squawked_at<span style="color: #990000">).</span>to_s
send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> InstanceMethods
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -867,130 +920,122 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> InstanceMethods
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> squawk<span style="color: #990000">(</span>string<span style="color: #990000">)</span>
write_attribute<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">class</span></span><span style="color: #990000">.</span>yaffle_text_field<span style="color: #990000">,</span> string<span style="color: #990000">.</span>to_squawk<span style="color: #990000">)</span>
- write_attribute<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">class</span></span><span style="color: #990000">.</span>yaffle_date_field<span style="color: #990000">,</span> Date<span style="color: #990000">.</span>today<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>
+
+ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle
</tt></pre></div></div>
-<div class="para"><p>Note the use of <tt>write_attribute</tt> to write to the field in model.</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">Editor's note:</div>The use of <tt>write_attribute</tt> to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use <tt>send("#{self.class.yaffle_text_field}=", string.to_squawk)</tt>.</td>
+</tr></table>
</div>
-<h2 id="_create_a_tt_squawk_info_for_tt_view_helper">4. Create a <tt>squawk_info_for</tt> view helper</h2>
+</div>
+<h2 id="_create_a_generator">4. Create a generator</h2>
<div class="sectionbody">
-<div class="para"><p>Creating a view helper is a 3-step process:</p></div>
+<div class="para"><p>Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in <em>vendor/plugins/yaffle/generators/yaffle</em>.</p></div>
+<div class="para"><p>Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.</p></div>
+<div class="para"><p>To create a generator you must:</p></div>
<div class="ilist"><ul>
<li>
<p>
-Add an appropriately named file to the <em>lib</em> directory.
+Add your instructions to the <em>manifest</em> method of the generator
+</p>
+</li>
+<li>
+<p>
+Add any necessary template files to the templates directory
</p>
</li>
<li>
<p>
-Require the file and hooks in <em>init.rb</em>.
+Test the generator manually by running various combinations of <tt>script/generate</tt> and <tt>script/destroy</tt>
</p>
</li>
<li>
<p>
-Write the tests.
+Update the USAGE file to add helpful documentation for your generator
</p>
</li>
</ul></div>
-<div class="para"><p>First, create the test to define the functionality you want:</p></div>
+<h3 id="_testing_generators">4.1. Testing generators</h3>
+<div class="para"><p>Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Creates a new fake rails root directory that will serve as destination
+</p>
+</li>
+<li>
+<p>
+Runs the generator forward and backward, making whatever assertions are necessary
+</p>
+</li>
+<li>
+<p>
+Removes the fake rails root
+</p>
+</li>
+</ul></div>
+<div class="para"><p>For the generator in this section, the test could look something like this:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/yaffle_generator_test.rb</strong></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"># File: vendor/plugins/yaffle/test/view_helpers_test.rb</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/generate'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/destroy'</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
-<span style="font-weight: bold"><span style="color: #0000FF">include</span></span> YaffleViewHelper
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> GeneratorTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ViewHelpersTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_squawk_info_for_should_return_the_text_and_date
- time <span style="color: #990000">=</span> Time<span style="color: #990000">.</span>now
- hickwall <span style="color: #990000">=</span> Hickwall<span style="color: #990000">.</span>new
- hickwall<span style="color: #990000">.</span>last_squawk <span style="color: #990000">=</span> <span style="color: #FF0000">"Hello World"</span>
- hickwall<span style="color: #990000">.</span>last_squawked_at <span style="color: #990000">=</span> time
- assert_equal <span style="color: #FF0000">"Hello World, #{time.to_s}"</span><span style="color: #990000">,</span> squawk_info_for<span style="color: #990000">(</span>hickwall<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> fake_rails_root
+ File<span style="color: #990000">.</span>join<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: #FF0000">'rails_root'</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>
-</tt></pre></div></div>
-<div class="para"><p>Then add the following statements to init.rb:</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"># File: vendor/plugins/yaffle/init.rb</span></span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"view_helpers"</span>
-ActionView<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> YaffleViewHelper
-</tt></pre></div></div>
-<div class="para"><p>Then add the view helpers file and</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"># File: vendor/plugins/yaffle/lib/view_helpers.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> YaffleViewHelper
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> squawk_info_for<span style="color: #990000">(</span>yaffle<span style="color: #990000">)</span>
- returning <span style="color: #FF0000">""</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>result<span style="color: #990000">|</span>
- result <span style="color: #990000"><<</span> yaffle<span style="color: #990000">.</span>read_attribute<span style="color: #990000">(</span>yaffle<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">class</span></span><span style="color: #990000">.</span>yaffle_text_field<span style="color: #990000">)</span>
- result <span style="color: #990000"><<</span> <span style="color: #FF0000">", "</span>
- result <span style="color: #990000"><<</span> yaffle<span style="color: #990000">.</span>read_attribute<span style="color: #990000">(</span>yaffle<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">class</span></span><span style="color: #990000">.</span>yaffle_date_field<span style="color: #990000">).</span>to_s
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> file_list
+ Dir<span style="color: #990000">.</span>glob<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"db"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"*"</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>
-</tt></pre></div></div>
-<div class="para"><p>You can also test this in script/console by using the <tt>helper</tt> method:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>$ ./script/console
->> helper.squawk_info_for(@some_yaffle_instance)</tt></pre>
-</div></div>
-</div>
-<h2 id="_create_a_migration_generator">5. Create a migration generator</h2>
-<div class="sectionbody">
-<div class="para"><p>When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in your plugin.</p></div>
-<div class="para"><p>We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial.</p></div>
-<div class="para"><p>Type:</p></div>
-<div class="literalblock">
-<div class="content">
-<pre><tt>script/generate</tt></pre>
-</div></div>
-<div class="para"><p>You should see the line:</p></div>
-<div class="literalblock">
-<div class="content">
-<pre><tt>Plugins (vendor/plugins): yaffle</tt></pre>
-</div></div>
-<div class="para"><p>When you run <tt>script/generate yaffle</tt> you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>Description:
- Creates a migration that adds yaffle squawk fields to the given model
-Example:
- ./script/generate yaffle hickwall
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
+ FileUtils<span style="color: #990000">.</span>mkdir_p<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
+ <span style="color: #009900">@original_files</span> <span style="color: #990000">=</span> file_list
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- This will create:
- db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall</tt></pre>
-</div></div>
-<div class="para"><p>Now you can add code to your generator:</p></div>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
+ FileUtils<span style="color: #990000">.</span>rm_r<span style="color: #990000">(</span>fake_rails_root<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">def</span></span> test_generates_correct_file_name
+ Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"bird"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=></span> fake_rails_root<span style="color: #990000">)</span>
+ new_file <span style="color: #990000">=</span> <span style="color: #990000">(</span>file_list <span style="color: #990000">-</span> <span style="color: #009900">@original_files</span><span style="color: #990000">).</span>first
+ assert_match <span style="color: #FF6600">/add_yaffle_fields_to_bird/</span><span style="color: #990000">,</span> new_file
+ <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="para"><p>You can run <em>rake</em> from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.</p></div>
+<h3 id="_adding_to_the_manifest">4.2. Adding to the manifest</h3>
+<div class="para"><p>This example will demonstrate how to use one of the built-in generator methods named <em>migration_template</em> to create a migration file. To start, update your generator file to look like this:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</strong></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"># File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleGenerator <span style="color: #990000"><</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleGenerator <span style="color: #990000"><</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
record <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>migration_template <span style="color: #FF0000">'migration:migration.rb'</span><span style="color: #990000">,</span> <span style="color: #FF0000">"db/migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>assigns <span style="color: #990000">=></span> yaffle_local_assigns<span style="color: #990000">,</span>
<span style="color: #990000">:</span>migration_file_name <span style="color: #990000">=></span> <span style="color: #FF0000">"add_yaffle_fields_to_#{custom_file_name}"</span>
- <span style="color: #FF0000">}</span>
+ <span style="color: #FF0000">}</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>
@@ -1006,91 +1051,100 @@ http://www.gnu.org/software/src-highlite --> assigns<span style="color: #990000">[:</span>class_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"add_yaffle_fields_to_#{custom_file_name}"</span>
assigns<span style="color: #990000">[:</span>table_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> custom_file_name
assigns<span style="color: #990000">[:</span>attributes<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #990000">[</span>Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>GeneratedAttribute<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"string"</span><span style="color: #990000">)]</span>
- assigns<span style="color: #990000">[:</span>attributes<span style="color: #990000">]</span> <span style="color: #990000"><<</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>GeneratedAttribute<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"last_squawked_at"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"datetime"</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="para"><p>Note that you need to be aware of whether or not table names are pluralized.</p></div>
-<div class="para"><p>This does a few things:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-Reuses the built in rails <tt>migration_template</tt> method.
-</p>
-</li>
-<li>
-<p>
-Reuses the built-in rails migration template.
-</p>
-</li>
-</ul></div>
-<div class="para"><p>When you run the generator like</p></div>
-<div class="literalblock">
+<div class="para"><p>The generator creates a new file in <em>db/migrate</em> with a timestamp and an <em>add_column</em> statement. It reuses the built in rails <tt>migration_template</tt> method, and reuses the built-in rails migration template.</p></div>
+<div class="para"><p>It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.</p></div>
+<h3 id="_manually_test_the_generator">4.3. Manually test the generator</h3>
+<div class="para"><p>To run the generator, type the following at the command line:</p></div>
+<div class="listingblock">
<div class="content">
-<pre><tt>script/generate yaffle bird</tt></pre>
+<pre><tt>./script/generate yaffle bird</tt></pre>
</div></div>
-<div class="para"><p>You will see a new file:</p></div>
+<div class="para"><p>and you will see a new file:</p></div>
+<div class="para"><p><strong>db/migrate/20080529225649_add_yaffle_fields_to_birds.rb</strong></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"># File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddYaffleFieldsToBirds <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Migration
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddYaffleFieldsToBirds <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Migration
<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>up
add_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawk<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
- add_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawked_at<span style="color: #990000">,</span> <span style="color: #990000">:</span>datetime
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<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>down
- remove_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawked_at
remove_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawk
<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>
+<h3 id="_the_usage_file">4.4. The USAGE file</h3>
+<div class="para"><p>Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>script/generate</tt></pre>
+</div></div>
+<div class="para"><p>You should see something like this:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>Installed Generators
+ Plugins (vendor/plugins): yaffle
+ Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration</tt></pre>
+</div></div>
+<div class="para"><p>When you run <tt>script/generate yaffle</tt> you should see the contents of your <em>vendor/plugins/yaffle/generators/yaffle/USAGE</em> file.</p></div>
+<div class="para"><p>For this plugin, update the USAGE file looks like this:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>Description:
+ Creates a migration that adds yaffle squawk fields to the given model
+
+Example:
+ ./script/generate yaffle hickwall
+
+ This will create:
+ db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall</tt></pre>
+</div></div>
</div>
-<h2 id="_add_a_custom_generator_command">6. Add a custom generator command</h2>
+<h2 id="_add_a_custom_generator_command">5. Add a custom generator command</h2>
<div class="sectionbody">
-<div class="para"><p>You may have noticed above that you can used one of the built-in rails migration commands <tt>m.migration_template</tt>. You can create your own commands for these, using the following steps:</p></div>
-<div class="olist"><ol>
-<li>
-<p>
-Add the require and hook statements to init.rb.
-</p>
-</li>
-<li>
-<p>
-Create the commands - creating 3 sets, Create, Destroy, List.
-</p>
-</li>
-<li>
-<p>
-Add the method to your generator.
-</p>
-</li>
-</ol></div>
-<div class="para"><p>Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:</p></div>
+<div class="para"><p>You may have noticed above that you can used one of the built-in rails migration commands <tt>migration_template</tt>. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.</p></div>
+<div class="para"><p>This section describes how you you can create your own commands to add and remove a line of text from <em>routes.rb</em>. This example creates a very simple method that adds or removes a text file.</p></div>
+<div class="para"><p>To start, add the following test method:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/generator_test.rb</strong></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"># File: vendor/plugins/yaffle/init.rb</span></span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"commands"</span>
-Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create
-Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy
-Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_generates_definition
+ Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"bird"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=></span> fake_rails_root<span style="color: #990000">)</span>
+ definition <span style="color: #990000">=</span> File<span style="color: #990000">.</span>read<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">))</span>
+ assert_match <span style="color: #FF6600">/Yaffle\:/</span><span style="color: #990000">,</span> definition
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p>Run <tt>rake</tt> to watch the test fail, then make the test pass add the following:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/templates/definition.txt</strong></p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>Yaffle: A bird</tt></pre>
+</div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></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"># File: vendor/plugins/yaffle/lib/commands.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"yaffle/commands"</span>
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/commands.rb</strong></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-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/commands'</span>
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
@@ -1113,42 +1167,230 @@ http://www.gnu.org/software/src-highlite --> file<span style="color: #990000">(</span><span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</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">module</span></span> Update
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_definition
+ file<span style="color: #990000">(</span><span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</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>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Update<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Update
+</tt></pre></div></div>
+<div class="para"><p>Finally, call your new method in the manifest:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</strong></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-weight: bold"><span style="color: #0000FF">class</span></span> YaffleGenerator <span style="color: #990000"><</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
+ m<span style="color: #990000">.</span>yaffle_definition
+ <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>
+<h2 id="_add_a_model">6. Add a model</h2>
+<div class="sectionbody">
+<div class="para"><p>This section describes how to add a model named <em>Woodpecker</em> to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt># File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
-
-Yaffle is a bird</tt></pre>
+<pre><tt>vendor/plugins/yaffle/
+|-- lib
+| |-- app
+| | |-- controllers
+| | |-- helpers
+| | |-- models
+| | | `-- woodpecker.rb
+| | `-- views
+| |-- yaffle
+| | |-- acts_as_yaffle.rb
+| | |-- commands.rb
+| | `-- core_ext.rb
+| `-- yaffle.rb</tt></pre>
</div></div>
+<div class="para"><p>As always, start with a test:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/yaffle/woodpecker_test.rb:</strong></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"># File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleGenerator <span style="color: #990000"><</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
- m<span style="color: #990000">.</span>yaffle_definition
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> WoodpeckerTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_woodpecker
+ assert_kind_of Woodpecker<span style="color: #990000">,</span> Woodpecker<span style="color: #990000">.</span>new
<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="para"><p>This example just uses the built-in "file" method, but you could do anything that Ruby allows.</p></div>
+<div class="para"><p>This is just a simple test to make sure the class is being loaded correctly. After watching it fail with <tt>rake</tt>, you can make it pass like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></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>w<span style="color: #FF0000">{</span> models <span style="color: #FF0000">}</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>dir<span style="color: #990000">|</span>
+ path <span style="color: #990000">=</span> File<span style="color: #990000">.</span>join<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: #FF0000">'app'</span><span style="color: #990000">,</span> dir<span style="color: #990000">)</span>
+ <span style="color: #009900">$LOAD_PATH</span> <span style="color: #990000"><<</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_paths <span style="color: #990000"><<</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_once_paths<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>path<span style="color: #990000">)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the <em>load_once_paths</em> allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/app/models/woodpecker.rb:</strong></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-weight: bold"><span style="color: #0000FF">class</span></span> Woodpecker <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Finally, add the following to your plugin's <em>schema.rb</em>:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/schema.rb:</strong></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>ActiveRecord<span style="color: #990000">::</span>Schema<span style="color: #990000">.</span>define<span style="color: #990000">(:</span>version <span style="color: #990000">=></span> <span style="color: #993399">0</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ create_table <span style="color: #990000">:</span>woodpeckers<span style="color: #990000">,</span> <span style="color: #990000">:</span>force <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
+ t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
+ <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="para"><p>Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.</p></div>
</div>
-<h2 id="_add_a_custom_route">7. Add a Custom Route</h2>
+<h2 id="_add_a_controller">7. Add a controller</h2>
<div class="sectionbody">
-<div class="para"><p>Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in <a href="http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2">http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2</a>.</p></div>
+<div class="para"><p>This section describes how to add a controller named <em>woodpeckers</em> to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.</p></div>
+<div class="para"><p>You can test your plugin's controller as you would test any other controller:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:</strong></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"># File: vendor/plugins/yaffle/test/routing_test.rb</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'woodpeckers_controller'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'action_controller/test_process'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> WoodpeckersController<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> rescue_action<span style="color: #990000">(</span>e<span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">raise</span></span> e <span style="font-weight: bold"><span style="color: #0000FF">end</span></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: #000080">require</span></span> <span style="color: #FF0000">"#{File.dirname(__FILE__)}/test_helper"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> WoodpeckersControllerTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
+ <span style="color: #009900">@controller</span> <span style="color: #990000">=</span> WoodpeckersController<span style="color: #990000">.</span>new
+ <span style="color: #009900">@request</span> <span style="color: #990000">=</span> ActionController<span style="color: #990000">::</span>TestRequest<span style="color: #990000">.</span>new
+ <span style="color: #009900">@response</span> <span style="color: #990000">=</span> ActionController<span style="color: #990000">::</span>TestResponse<span style="color: #990000">.</span>new
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_index
+ get <span style="color: #990000">:</span>index
+ assert_response <span style="color: #990000">:</span>success
+ <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="para"><p>This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with <tt>rake</tt>, you can make it pass like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></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>w<span style="color: #FF0000">{</span> models controllers <span style="color: #FF0000">}</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>dir<span style="color: #990000">|</span>
+ path <span style="color: #990000">=</span> File<span style="color: #990000">.</span>join<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: #FF0000">'app'</span><span style="color: #990000">,</span> dir<span style="color: #990000">)</span>
+ <span style="color: #009900">$LOAD_PATH</span> <span style="color: #990000"><<</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_paths <span style="color: #990000"><<</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_once_paths<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>path<span style="color: #990000">)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:</strong></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-weight: bold"><span style="color: #0000FF">class</span></span> WoodpeckersController <span style="color: #990000"><</span> ActionController<span style="color: #990000">::</span>Base
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> index
+ render <span style="color: #990000">:</span>text <span style="color: #990000">=></span> <span style="color: #FF0000">"Squawk!"</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="para"><p>Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to <a href="http://localhost:3000/woodpeckers">http://localhost:3000/woodpeckers</a> to see your controller in action.</p></div>
+</div>
+<h2 id="_add_a_helper">8. Add a helper</h2>
+<div class="sectionbody">
+<div class="para"><p>This section describes how to add a helper named <em>WoodpeckersHelper</em> to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.</p></div>
+<div class="para"><p>You can test your plugin's helper as you would test any other helper:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/woodpeckers_helper_test.rb</strong></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-weight: bold"><span style="color: #000080">require</span></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">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #0000FF">include</span></span> WoodpeckersHelper
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> WoodpeckersHelperTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_tweet
+ assert_equal <span style="color: #FF0000">"Tweet! Hello"</span><span style="color: #990000">,</span> tweet<span style="color: #990000">(</span><span style="color: #FF0000">"Hello"</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>
+</tt></pre></div></div>
+<div class="para"><p>This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with <tt>rake</tt>, you can make it pass like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></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>w<span style="color: #FF0000">{</span> models controllers helpers <span style="color: #FF0000">}</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>dir<span style="color: #990000">|</span>
+ path <span style="color: #990000">=</span> File<span style="color: #990000">.</span>join<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: #FF0000">'app'</span><span style="color: #990000">,</span> dir<span style="color: #990000">)</span>
+ <span style="color: #009900">$LOAD_PATH</span> <span style="color: #990000"><<</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_paths <span style="color: #990000"><<</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_once_paths<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>path<span style="color: #990000">)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ActionView<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> WoodpeckersHelper
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:</strong></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-weight: bold"><span style="color: #0000FF">module</span></span> WoodpeckersHelper
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> tweet<span style="color: #990000">(</span>text<span style="color: #990000">)</span>
+ <span style="color: #FF0000">"Tweet! #{text}"</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="para"><p>Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.</p></div>
+</div>
+<h2 id="_add_a_custom_route">9. Add a Custom Route</h2>
+<div class="sectionbody">
+<div class="para"><p>Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in <a href="http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2">http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2</a>.</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/routing_test.rb</strong></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-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"#{File.dirname(__FILE__)}/test_helper"</span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> RoutingTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
@@ -1174,24 +1416,22 @@ http://www.gnu.org/software/src-highlite --> <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="para"><p><strong>vendor/plugins/yaffle/init.rb</strong></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"># File: vendor/plugins/yaffle/init.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"routing"</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"routing"</span>
ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>RouteSet<span style="color: #990000">::</span>Mapper<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>MapperExtensions
</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/routing.rb</strong></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"># File: vendor/plugins/yaffle/lib/routing.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Routing <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> MapperExtensions
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffles
@@ -1201,51 +1441,22 @@ http://www.gnu.org/software/src-highlite --> <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="para"><p><strong>config/routes.rb</strong></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"># File: config/routes.rb</span></span>
-
-ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
+<pre><tt>ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
<span style="color: #990000">...</span>
map<span style="color: #990000">.</span>yaffles
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>You can also see if your routes work by running <tt>rake routes</tt> from your app directory.</p></div>
</div>
-<h2 id="_odds_and_ends">8. Odds and ends</h2>
+<h2 id="_odds_and_ends">10. Odds and ends</h2>
<div class="sectionbody">
-<h3 id="_work_with_init_rb">8.1. Work with init.rb</h3>
-<div class="para"><p>The plugin initializer script <em>init.rb</em> is invoked via <tt>eval</tt> (not <tt>require</tt>) so it has slightly different behavior.</p></div>
-<div class="para"><p>If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this:</p></div>
-<div class="para"><p>The first way is to explicitly define the top-level module space for all modules and classes, like <tt>::Hash</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"># File: vendor/plugins/yaffle/init.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> <span style="color: #990000">::</span>Hash
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> is_a_special_hash?
- <span style="font-weight: bold"><span style="color: #0000FF">true</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="para"><p>OR you can use <tt>module_eval</tt> or <tt>class_eval</tt>:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt># File: vendor/plugins/yaffle/init.rb
-
-Hash.class_eval do
- def is_a_special_hash?
- true
- end
-end</tt></pre>
-</div></div>
-<h3 id="_generate_rdoc_documentation">8.2. Generate RDoc Documentation</h3>
+<h3 id="_generate_rdoc_documentation">10.1. Generate RDoc Documentation</h3>
<div class="para"><p>Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.</p></div>
<div class="para"><p>The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:</p></div>
<div class="ilist"><ul>
@@ -1277,35 +1488,16 @@ Warning, gotchas or tips that might help save users time. <div class="content">
<pre><tt>rake rdoc</tt></pre>
</div></div>
-<h3 id="_store_models_views_helpers_and_controllers_in_your_plugins">8.3. Store models, views, helpers, and controllers in your plugins</h3>
-<div class="para"><p>You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:</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"># File: vendor/plugins/yaffle/init.rb</span></span>
-
-<span style="color: #990000">%</span>w<span style="color: #FF0000">{</span> models controllers helpers <span style="color: #FF0000">}</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>dir<span style="color: #990000">|</span>
- path <span style="color: #990000">=</span> File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>directory<span style="color: #990000">,</span> <span style="color: #FF0000">'lib'</span><span style="color: #990000">,</span> dir<span style="color: #990000">)</span>
- <span style="color: #009900">$LOAD_PATH</span> <span style="color: #990000"><<</span> path
- Dependencies<span style="color: #990000">.</span>load_paths <span style="color: #990000"><<</span> path
- Dependencies<span style="color: #990000">.</span>load_once_paths<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>path<span style="color: #990000">)</span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser.</p></div>
-<div class="para"><p>Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.</p></div>
-<h3 id="_write_custom_rake_tasks_in_your_plugin">8.4. Write custom Rake tasks in your plugin</h3>
+<h3 id="_write_custom_rake_tasks_in_your_plugin">10.2. Write custom Rake tasks in your plugin</h3>
<div class="para"><p>When you created the plugin with the built-in rails generator, it generated a rake file for you in <em>vendor/plugins/yaffle/tasks/yaffle.rake</em>. Any rake task you add here will be available to the app.</p></div>
<div class="para"><p>Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/tasks/yaffle.rake</strong></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"># File: vendor/plugins/yaffle/tasks/yaffle.rake</span></span>
-
-namespace <span style="color: #990000">:</span>yaffle <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+<pre><tt>namespace <span style="color: #990000">:</span>yaffle <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
desc <span style="color: #FF0000">"Prints out the word 'Yaffle'"</span>
task <span style="color: #990000">:</span>squawk <span style="color: #990000">=></span> <span style="color: #990000">:</span>environment <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
puts <span style="color: #FF0000">"squawk!"</span>
@@ -1318,7 +1510,7 @@ namespace <span style="color: #990000">:</span>yaffle <span style="font-weight: <pre><tt>yaffle:squawk # Prints out the word 'Yaffle'</tt></pre>
</div></div>
<div class="para"><p>You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.</p></div>
-<h3 id="_store_plugins_in_alternate_locations">8.5. Store plugins in alternate locations</h3>
+<h3 id="_store_plugins_in_alternate_locations">10.3. Store plugins in alternate locations</h3>
<div class="para"><p>You can store plugins wherever you want - you just have to add those plugins to the plugins path in <em>environment.rb</em>.</p></div>
<div class="para"><p>Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.</p></div>
<div class="para"><p>You can even store plugins inside of other plugins for complete plugin madness!</p></div>
@@ -1329,14 +1521,14 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt>config<span style="color: #990000">.</span>plugin_paths <span style="color: #990000"><<</span> File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>RAILS_ROOT<span style="color: #990000">,</span><span style="color: #FF0000">"vendor"</span><span style="color: #990000">,</span><span style="color: #FF0000">"plugins"</span><span style="color: #990000">,</span><span style="color: #FF0000">"yaffle"</span><span style="color: #990000">,</span><span style="color: #FF0000">"lib"</span><span style="color: #990000">,</span><span style="color: #FF0000">"plugins"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
-<h3 id="_create_your_own_plugin_loaders_and_plugin_locators">8.6. Create your own Plugin Loaders and Plugin Locators</h3>
+<h3 id="_create_your_own_plugin_loaders_and_plugin_locators">10.4. Create your own Plugin Loaders and Plugin Locators</h3>
<div class="para"><p>If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.</p></div>
-<h3 id="_use_custom_plugin_generators">8.7. Use Custom Plugin Generators</h3>
+<h3 id="_use_custom_plugin_generators">10.5. Use Custom Plugin Generators</h3>
<div class="para"><p>If you are an RSpec fan, you can install the <tt>rspec_plugin_generator</tt> gem, which will generate the spec folder and database for you. See <a href="http://github.com/pat-maddox/rspec-plugin-generator/tree/master">http://github.com/pat-maddox/rspec-plugin-generator/tree/master</a>.</p></div>
</div>
-<h2 id="_appendix">9. Appendix</h2>
+<h2 id="_appendix">11. Appendix</h2>
<div class="sectionbody">
-<h3 id="_references">9.1. References</h3>
+<h3 id="_references">11.1. References</h3>
<div class="ilist"><ul>
<li>
<p>
@@ -1359,7 +1551,7 @@ http://www.gnu.org/software/src-highlite --> </p>
</li>
</ul></div>
-<h3 id="_final_plugin_directory_structure">9.2. Final plugin directory structure</h3>
+<h3 id="_final_plugin_directory_structure">11.2. Final plugin directory structure</h3>
<div class="para"><p>The final plugin should have a directory structure that looks something like this:</p></div>
<div class="listingblock">
<div class="content">
diff --git a/railties/doc/guides/html/debugging_rails_applications.html b/railties/doc/guides/html/debugging_rails_applications.html index bf1e442d59..0653caaf7a 100644 --- a/railties/doc/guides/html/debugging_rails_applications.html +++ b/railties/doc/guides/html/debugging_rails_applications.html @@ -208,6 +208,8 @@ ul#navMain { <li><a href="#_inspect">inspect</a></li> + <li><a href="#_debugging_javascript">Debugging Javascript</a></li> + </ul> </li> <li> @@ -253,6 +255,19 @@ ul#navMain { </ul> </li> <li> + <a href="#_debugging_memory_leaks">Debugging Memory Leaks</a> + <ul> + + <li><a href="#_bleakhouse">BleakHouse</a></li> + + <li><a href="#_valgrind">Valgrind</a></li> + + </ul> + </li> + <li> + <a href="#_plugins_for_debugging">Plugins for Debugging</a> + </li> + <li> <a href="#_references">References</a> </li> <li> @@ -325,10 +340,7 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>You'll see something like this:</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 -->
+<div class="content">
<pre><tt>--- !ruby/object:Post
attributes:
updated_at: 2008-09-05 22:55:47
@@ -340,8 +352,8 @@ attributes: attributes_cache: {}
-Title: Rails debugging guide
-</tt></pre></div></div>
+Title: Rails debugging guide</tt></pre>
+</div></div>
<h3 id="_to_yaml">1.2. to_yaml</h3>
<div class="para"><p>Displaying an instance variable, or any other object or method, in yaml format can be achieved this way:</p></div>
<div class="listingblock">
@@ -358,10 +370,7 @@ http://www.gnu.org/software/src-highlite --> <div class="para"><p>The <tt>to_yaml</tt> method converts the method to YAML format leaving it more readable, and then the <tt>simple_format</tt> helper is used to render each line as in the console. This is how <tt>debug</tt> method does its magic.</p></div>
<div class="para"><p>As a result of this, you will have something like this in your view:</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 -->
+<div class="content">
<pre><tt>--- !ruby/object:Post
attributes:
updated_at: 2008-09-05 22:55:47
@@ -372,8 +381,8 @@ id: "1" created_at: 2008-09-05 22:55:47
attributes_cache: {}
-Title: Rails debugging guide
-</tt></pre></div></div>
+Title: Rails debugging guide</tt></pre>
+</div></div>
<h3 id="_inspect">1.3. inspect</h3>
<div class="para"><p>Another useful method for displaying object values is <tt>inspect</tt>, especially when working with arrays or hashes. This will print the object value as a string. For example:</p></div>
<div class="listingblock">
@@ -389,14 +398,37 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>Will be rendered as follows:</p></div>
<div class="listingblock">
+<div class="content">
+<pre><tt>[1, 2, 3, 4, 5]
+
+Title: Rails debugging guide</tt></pre>
+</div></div>
+<h3 id="_debugging_javascript">1.4. Debugging Javascript</h3>
+<div class="para"><p>Rails has built-in support to debug RJS, to active it, set <tt>ActionView::Base.debug_rjs</tt> to <em>true</em>, this will specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it).</p></div>
+<div class="para"><p>To enable it, add the following in the <tt>Rails::Initializer do |config|</tt> block inside <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>[1, 2, 3, 4, 5]
-
-Title: Rails debugging guide
+<pre><tt>config<span style="color: #990000">.</span>action_view<span style="color: #990000">[:</span>debug_rjs<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Or, at any time, setting <tt>ActionView::Base.debug_rjs</tt> to <em>true</em>:</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>ActionView<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>debug_rjs <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">For more information on debugging javascript refer to <a href="http://getfirebug.com/">Firebug</a>, the popular debugger for Firefox.</td>
+</tr></table>
+</div>
</div>
<h2 id="_the_logger">2. The Logger</h2>
<div class="sectionbody">
@@ -488,11 +520,8 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>Here's an example of the log generated by this method:</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>Processing PostsController#create (for <span style="color: #009900">127.0.0.1</span> at 2008-09-08 11:52:54) [POST]
+<div class="content">
+<pre><tt>Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
@@ -506,8 +535,8 @@ Post should be valid: true 'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
The post was saved and now is the user is going to be redirected...
Redirected to #<Post:0x20af760>
-Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
-</tt></pre></div></div>
+Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]</tt></pre>
+</div></div>
<div class="para"><p>Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia.</p></div>
</div>
<h2 id="_debugging_with_ruby_debug">3. Debugging with ruby-debug</h2>
@@ -540,12 +569,9 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>If you see the message in the console or logs:</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>***** Debugger requested, but was not available: Start server with --debugger to enable *****
-</tt></pre></div></div>
+<div class="content">
+<pre><tt>***** Debugger requested, but was not available: Start server with --debugger to enable *****</tt></pre>
+</div></div>
<div class="para"><p>Make sure you have started your web server with the option <tt>—debugger</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -576,7 +602,7 @@ http://www.gnu.org/software/src-highlite --> <pre><tt>@posts = Post.find(:all)
(rdb:7)</tt></pre>
</div></div>
-<div class="para"><p>Now it's time to play and dig into your application. A good place to start is by asking the debugger for help… so type: <tt>help</tt> (You didn't see that coming, right?)</p></div>
+<div class="para"><p>Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help… so type: <tt>help</tt> (You didn't see that coming, right?)</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:7) help
@@ -913,7 +939,7 @@ No breakpoints.</tt></pre> </li>
<li>
<p>
-<tt>finish</tt> [frame-number] (or <tt>fin</tt>): execute until the selected stack frame returns. If no frame number is given, the application run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns.
+<tt>finish</tt> [frame-number] (or <tt>fin</tt>): execute until the selected stack frame returns. If no frame number is given, the application will run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns.
</p>
</li>
</ul></div>
@@ -969,16 +995,104 @@ No breakpoints.</tt></pre> </div>
<div class="para"><p>Here's a good start for an <tt>.rdebugrc</tt>:</p></div>
<div class="listingblock">
+<div class="content">
+<pre><tt>set autolist
+set forcestep
+set listsize 25</tt></pre>
+</div></div>
+</div>
+<h2 id="_debugging_memory_leaks">4. Debugging Memory Leaks</h2>
+<div class="sectionbody">
+<div class="para"><p>A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level.</p></div>
+<div class="para"><p>In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools.</p></div>
+<h3 id="_bleakhouse">4.1. BleakHouse</h3>
+<div class="para"><p><a href="http://github.com/fauna/bleak_house/tree/master">BleakHouse</a> is a library for finding memory leaks.</p></div>
+<div class="para"><p>If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap.</p></div>
+<div class="para"><p>To install it run:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>sudo gem install bleak_house</tt></pre>
+</div></div>
+<div class="para"><p>Then setup you application for profiling. Then add the following at the bottom of config/environment.rb:</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>set autolist
-set forcestep
-set listsize 25
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'bleak_house'</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">'BLEAK_HOUSE'</span><span style="color: #990000">]</span>
</tt></pre></div></div>
+<div class="para"><p>Start a server instance with BleakHouse integration:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house ./script/server</tt></pre>
+</div></div>
+<div class="para"><p>Make sure to run a couple hundred requests to get better data samples, then press <tt>CTRL-C</tt>. The server will stop and Bleak House will produce a dumpfile in <tt>/tmp</tt>:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>** BleakHouse: working...
+** BleakHouse: complete
+** Bleakhouse: run 'bleak /tmp/bleak.5979.0.dump' to analyze.</tt></pre>
+</div></div>
+<div class="para"><p>To analyze it, just run the listed command. The top 20 leakiest lines will be listed:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt> 191691 total objects
+ Final heap size 191691 filled, 220961 free
+ Displaying top 20 most common line/class pairs
+ 89513 __null__:__null__:__node__
+ 41438 __null__:__null__:String
+ 2348 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:Array
+ 1508 /opt/local//lib/ruby/gems/1.8/specifications/gettext-1.90.0.gemspec:14:String
+ 1021 /opt/local//lib/ruby/gems/1.8/specifications/heel-0.2.0.gemspec:14:String
+ 951 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:111:String
+ 935 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:String
+ 834 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:146:Array
+ ...</tt></pre>
+</div></div>
+<div class="para"><p>This way you can find where your application is leaking memory and fix it.</p></div>
+<div class="para"><p>If <a href="http://github.com/fauna/bleak_house/tree/master">BleakHouse</a> doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.</p></div>
+<h3 id="_valgrind">4.2. Valgrind</h3>
+<div class="para"><p><a href="http://valgrind.org/">Valgrind</a> is a Linux-only application for detecting C-based memory leaks and race conditions.</p></div>
+<div class="para"><p>There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls <tt>malloc()</tt> but is doesn't properly call <tt>free()</tt>, this memory won't be available until the app terminates.</p></div>
+<div class="para"><p>For further information on how to install Valgrind and use with Ruby, refer to <a href="http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/">Valgrind and Ruby</a> by Evan Weaver.</p></div>
</div>
-<h2 id="_references">4. References</h2>
+<h2 id="_plugins_for_debugging">5. Plugins for Debugging</h2>
+<div class="sectionbody">
+<div class="para"><p>There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<a href="http://github.com/drnic/rails-footnotes/tree/master">Footnotes</a>: Every Rails page has footnotes that give request information and link back to your source via TextMate.
+</p>
+</li>
+<li>
+<p>
+<a href="http://github.com/ntalbott/query_trace/tree/master">Query Trace</a>: Adds query origin tracing to your logs.
+</p>
+</li>
+<li>
+<p>
+<a href="http://github.com/dan-manges/query_stats/tree/master">Query Stats</a>: A Rails plugin to track database queries.
+</p>
+</li>
+<li>
+<p>
+<a href="http://code.google.com/p/query-reviewer/">Query Reviewer</a>: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
+</p>
+</li>
+<li>
+<p>
+<a href="http://github.com/rails/exception_notification/tree/master">Exception Notifier</a>: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
+</p>
+</li>
+<li>
+<p>
+<a href="http://github.com/defunkt/exception_logger/tree/master">Exception Logger</a>: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
+</p>
+</li>
+</ul></div>
+</div>
+<h2 id="_references">6. References</h2>
<div class="sectionbody">
<div class="ilist"><ul>
<li>
@@ -1026,14 +1140,24 @@ set listsize 25 <a href="http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging">Ruby on Rails Wiki: How to Configure Logging</a>
</p>
</li>
+<li>
+<p>
+<a href="http://blog.evanweaver.com/files/doc/fauna/bleak_house/files/README.html">Bleak House Documentation</a>
+</p>
+</li>
</ul></div>
</div>
-<h2 id="_changelog">5. Changelog</h2>
+<h2 id="_changelog">7. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/5">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
<li>
<p>
+November 3, 2008: Accepted for publication. Added RJS, memory leaks and plugins chapters by <a href="../authors.html#miloops">Emilio Tagua</a>
+</p>
+</li>
+<li>
+<p>
October 19, 2008: Copy editing pass by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
</p>
</li>
diff --git a/railties/doc/guides/html/finders.html b/railties/doc/guides/html/finders.html index f8396bb517..02c1654aa5 100644 --- a/railties/doc/guides/html/finders.html +++ b/railties/doc/guides/html/finders.html @@ -199,9 +199,6 @@ ul#navMain { <h2>Chapters</h2> <ol> <li> - <a href="#_in_the_beginning_8230">In the beginning…</a> - </li> - <li> <a href="#_the_sample_models">The Sample Models</a> </li> <li> @@ -260,6 +257,21 @@ ul#navMain { </li> <li> <a href="#_named_scopes">Named Scopes</a> + <ul> + + <li><a href="#_simple_named_scopes">Simple Named Scopes</a></li> + + <li><a href="#_combining_named_scopes">Combining Named Scopes</a></li> + + <li><a href="#_runtime_evaluation_of_named_scope_conditions">Runtime Evaluation of Named Scope Conditions</a></li> + + <li><a href="#_named_scopes_with_multiple_models">Named Scopes with Multiple Models</a></li> + + <li><a href="#_arguments_to_named_scopes">Arguments to Named Scopes</a></li> + + <li><a href="#_anonymous_scopes">Anonymous Scopes</a></li> + + </ul> </li> <li> <a href="#_existence_of_objects">Existence of Objects</a> @@ -293,25 +305,48 @@ ul#navMain { <h1>Rails Finders</h1> <div id="preamble">
<div class="sectionbody">
-<div class="para"><p>This guide is all about the <tt>find</tt> method defined in <tt>ActiveRecord::Base</tt>, finding on associations, and associated goodness such as named scopes. You will learn how to be a find master.</p></div>
-</div>
+<div class="para"><p>This guide covers the <tt>find</tt> method defined in <tt>ActiveRecord::Base</tt>, as well as other ways of finding particular instances of your models. By using this guide, you will be able to:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Find records using a variety of methods and conditions
+</p>
+</li>
+<li>
+<p>
+Specify the order, retrieved attributes, grouping, and other properties of the found records
+</p>
+</li>
+<li>
+<p>
+Use eager loading to cut down on the number of database queries in your application
+</p>
+</li>
+<li>
+<p>
+Use dynamic finders
+</p>
+</li>
+<li>
+<p>
+Create named scopes to add custom finding behavior to your models
+</p>
+</li>
+<li>
+<p>
+Check for the existence of particular records
+</p>
+</li>
+<li>
+<p>
+Perform aggregate calculations on Active Record models
+</p>
+</li>
+</ul></div>
+<div class="para"><p>If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.</p></div>
</div>
-<h2 id="_in_the_beginning_8230">1. In the beginning…</h2>
-<div class="sectionbody">
-<div class="para"><p>In the beginning there was SQL. SQL looked like this:</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-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients
-<span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> id <span style="color: #990000">=</span> <span style="color: #FF0000">'1'</span>
-<span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">0</span><span style="color: #990000">,</span><span style="color: #993399">1</span>
-<span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">ORDER</span></span> <span style="font-weight: bold"><span style="color: #0000FF">BY</span></span> id <span style="font-weight: bold"><span style="color: #0000FF">DESC</span></span> <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">0</span><span style="color: #990000">,</span><span style="color: #993399">1</span>
-</tt></pre></div></div>
-<div class="para"><p>In Rails (unlike some other frameworks) you don't usually have to type SQL because Active Record is there to help you find your records.</p></div>
</div>
-<h2 id="_the_sample_models">2. The Sample Models</h2>
+<h2 id="_the_sample_models">1. The Sample Models</h2>
<div class="sectionbody">
<div class="para"><p>This guide demonstrates finding using the following models:</p></div>
<div class="listingblock">
@@ -342,11 +377,11 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_database_agnostic">3. Database Agnostic</h2>
+<h2 id="_database_agnostic">2. Database Agnostic</h2>
<div class="sectionbody">
<div class="para"><p>Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.</p></div>
</div>
-<h2 id="_ids_first_last_and_all">4. IDs, First, Last and All</h2>
+<h2 id="_ids_first_last_and_all">3. IDs, First, Last and All</h2>
<div class="sectionbody">
<div class="para"><p><tt>ActiveRecord::Base</tt> has methods defined on it to make interacting with your database and the tables within it much, much easier. For finding records, the key method is <tt>find</tt>. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type <tt>Client.find(1)</tt> which would execute this query on your database:</p></div>
<div class="listingblock">
@@ -373,27 +408,29 @@ http://www.gnu.org/software/src-highlite --> <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>clients<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(+</span>clients<span style="color: #990000">+.+</span>id<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">IN</span></span> <span style="color: #990000">(</span><span style="color: #993399">1</span><span style="color: #990000">,</span><span style="color: #993399">2</span><span style="color: #990000">))</span>
</tt></pre></div></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 -->
+<div class="content">
<pre><tt>>> Client.find(1,2)
=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
#<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
-</tt></pre></div></div>
+ created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]</tt></pre>
+</div></div>
<div class="para"><p>Note that if you pass in a list of numbers that the result will be returned as an array, not as a single <tt>Client</tt> object.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">If <tt>find(id)</tt> or <tt>find([id1, id2])</tt> fails to find any records, it will raise a <tt>RecordNotFound</tt> exception.</td>
+</tr></table>
+</div>
<div class="para"><p>If you wanted to find the first client you would simply type <tt>Client.first</tt> and that would find the first client created in your clients table:</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 -->
+<div class="content">
<pre><tt>>> Client.first
=> #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
- created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">
-</tt></pre></div></div>
+ created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50"></tt></pre>
+</div></div>
<div class="para"><p>If you were running script/server you might see the following output:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -405,14 +442,11 @@ http://www.gnu.org/software/src-highlite --> <div class="para"><p>Indicating the query that Rails has performed on your database.</p></div>
<div class="para"><p>To find the last client you would simply type <tt>Client.find(:last)</tt> and that would find the last client created in your clients table:</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 -->
+<div class="content">
<pre><tt>>> Client.find(:last)
=> #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
-</tt></pre></div></div>
+ created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"></tt></pre>
+</div></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -422,28 +456,31 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>To find all the clients you would simply type <tt>Client.all</tt> and that would find all the clients in your clients table:</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 -->
+<div class="content">
<pre><tt>>> Client.all
=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
#<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
-</tt></pre></div></div>
+ created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]</tt></pre>
+</div></div>
<div class="para"><p>As alternatives to calling <tt>Client.first</tt>, <tt>Client.last</tt>, and <tt>Client.all</tt>, you can use the class methods <tt>Client.first</tt>, <tt>Client.last</tt>, and <tt>Client.all</tt> instead. <tt>Client.first</tt>, <tt>Client.last</tt> and <tt>Client.all</tt> just call their longer counterparts: <tt>Client.find(:first)</tt>, <tt>Client.find(:last)</tt> and <tt>Client.find(:all)</tt> respectively.</p></div>
<div class="para"><p>Be aware that <tt>Client.first</tt>/<tt>Client.find(:first)</tt> and <tt>Client.last</tt>/<tt>Client.find(:last)</tt> will both return a single object, where as <tt>Client.all</tt>/<tt>Client.find(:all)</tt> will return an array of Client objects, just as passing in an array of ids to find will do also.</p></div>
</div>
-<h2 id="_conditions">5. Conditions</h2>
+<h2 id="_conditions">4. Conditions</h2>
<div class="sectionbody">
-<h3 id="_pure_string_conditions">5.1. Pure String Conditions</h3>
+<div class="para"><p>The <tt>find</tt> method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.</p></div>
+<h3 id="_pure_string_conditions">4.1. Pure String Conditions</h3>
<div class="para"><p>If you'd like to add conditions to your find, you could just specify them in there, just like <tt>Client.first(:conditions ⇒ "orders_count = <em>2</em>")</tt>. This will find all clients where the <tt>orders_count</tt> field's value is 2.</p></div>
-<h3 id="_array_conditions">5.2. Array Conditions</h3>
-<div class="literalblock">
-<div class="content">
-<pre><tt>Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.</tt></pre>
-</div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/warning.png" alt="Warning" />
+</td>
+<td class="content">Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, <tt>Client.first(:conditions ⇒ "name LIKE <em>%#{params[:name]}%</em>")</tt> is not safe. See the next section for the preferred way to handle conditions using an array.</td>
+</tr></table>
+</div>
+<h3 id="_array_conditions">4.2. Array Conditions</h3>
+<div class="para"><p>Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like <tt>Client.first(:conditions ⇒ ["orders_count = ?", params[:orders]])</tt>. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like <tt>Client.first(:conditions ⇒ ["orders_count = ? AND locked = ?", params[:orders], false])</tt>. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has <em>2</em> as its value for the orders_count field and <em>false</em> for its locked field.</p></div>
<div class="para"><p>The reason for doing code like:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -510,12 +547,9 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:</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>Got a packet bigger than 'max_allowed_packet' bytes: _query_
-</tt></pre></div></div>
+<div class="content">
+<pre><tt>Got a packet bigger than 'max_allowed_packet' bytes: _query_</tt></pre>
+</div></div>
<div class="para"><p>Where <em>query</em> is the actual query used to get that error.</p></div>
<div class="para"><p>In this example it would be better to use greater-than and less-than operators in SQL, like so:</p></div>
<div class="listingblock">
@@ -536,7 +570,7 @@ http://www.gnu.org/software/src-highlite --> <span style="color: #990000">[</span><span style="color: #FF0000">"created_at >= ? AND created_at <= ?"</span><span style="color: #990000">,</span> params<span style="color: #990000">[:</span>start_date<span style="color: #990000">],</span> params<span style="color: #990000">[:</span>end_date<span style="color: #990000">]])</span>
</tt></pre></div></div>
<div class="para"><p>Just like in Ruby.</p></div>
-<h3 id="_hash_conditions">5.3. Hash Conditions</h3>
+<h3 id="_hash_conditions">4.3. Hash Conditions</h3>
<div class="para"><p>Similar to the array style of params you can also specify keys in your conditions:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -548,17 +582,17 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>This makes for clearer readability if you have a large number of variable conditions.</p></div>
</div>
-<h2 id="_ordering">6. Ordering</h2>
+<h2 id="_ordering">5. Ordering</h2>
<div class="sectionbody">
<div class="para"><p>If you're getting a set of records and want to force an order, you can use <tt>Client.all(:order ⇒ "created_at")</tt> which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using <tt>Client.all(:order ⇒ "created_at desc")</tt></p></div>
</div>
-<h2 id="_selecting_certain_fields">7. Selecting Certain Fields</h2>
+<h2 id="_selecting_certain_fields">6. Selecting Certain Fields</h2>
<div class="sectionbody">
<div class="para"><p>To select certain fields, you can use the select option like this: <tt>Client.first(:select ⇒ "viewable_by, locked")</tt>. This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute <tt>SELECT viewable_by, locked FROM clients LIMIT 0,1</tt> on your database.</p></div>
</div>
-<h2 id="_limit_amp_offset">8. Limit & Offset</h2>
+<h2 id="_limit_amp_offset">7. Limit & Offset</h2>
<div class="sectionbody">
-<div class="para"><p>If you want to limit the amount of records to a certain subset of all the records retreived you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retreived from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:</p></div>
+<div class="para"><p>If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -590,7 +624,7 @@ http://www.gnu.org/software/src-highlite --> <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">5</span><span style="color: #990000">,</span> <span style="color: #993399">5</span>
</tt></pre></div></div>
</div>
-<h2 id="_group">9. Group</h2>
+<h2 id="_group">8. Group</h2>
<div class="sectionbody">
<div class="para"><p>The group option for find is useful, for example, if you want to find a collection of the dates orders were created on. You could use the option in this context:</p></div>
<div class="listingblock">
@@ -610,9 +644,9 @@ http://www.gnu.org/software/src-highlite --> <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>orders<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">GROUP</span></span> <span style="font-weight: bold"><span style="color: #0000FF">BY</span></span> <span style="color: #009900">date</span><span style="color: #990000">(</span>created_at<span style="color: #990000">)</span>
</tt></pre></div></div>
</div>
-<h2 id="_read_only">10. Read Only</h2>
+<h2 id="_read_only">9. Read Only</h2>
<div class="sectionbody">
-<div class="para"><p>Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an <tt>Active Record::ReadOnlyRecord</tt> error. To set this option, specify it like this:</p></div>
+<div class="para"><p>Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an <tt>Active Record::ReadOnlyRecord</tt> exception. To set this option, specify it like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -620,7 +654,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>first<span style="color: #990000">(:</span>readonly <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">)</span>
</tt></pre></div></div>
-<div class="para"><p>If you assign this record to a variable <tt>client</tt>, calling the following code will raise an ActiveRecord::ReadOnlyRecord:</p></div>
+<div class="para"><p>If you assign this record to a variable <tt>client</tt>, calling the following code will raise an <tt>ActiveRecord::ReadOnlyRecord</tt> exception:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -631,7 +665,7 @@ client<span style="color: #990000">.</span>locked <span style="color: #990000">= client<span style="color: #990000">.</span>save
</tt></pre></div></div>
</div>
-<h2 id="_lock">11. Lock</h2>
+<h2 id="_lock">10. Lock</h2>
<div class="sectionbody">
<div class="para"><p>If you're wanting to stop race conditions for a specific record (for example, you're incrementing a single field for a record, potentially from multiple simultaneous connections) you can use the lock option to ensure that the record is updated correctly. For safety, you should use this inside a transaction.</p></div>
<div class="listingblock">
@@ -645,13 +679,13 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_making_it_all_work_together">12. Making It All Work Together</h2>
+<h2 id="_making_it_all_work_together">11. Making It All Work Together</h2>
<div class="sectionbody">
-<div class="para"><p>You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter.</p></div>
+<div class="para"><p>You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement Active Record will use the latter.</p></div>
</div>
-<h2 id="_eager_loading">13. Eager Loading</h2>
+<h2 id="_eager_loading">12. Eager Loading</h2>
<div class="sectionbody">
-<div class="para"><p>Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use <tt>Client.all(:include ⇒ :address)</tt>. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all), :include ⇒ [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:</p></div>
+<div class="para"><p>Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use <tt>Client.all(:include ⇒ :address)</tt>. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include ⇒ [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -694,7 +728,7 @@ http://www.gnu.org/software/src-highlite --> <span style="color: #990000">[</span><span style="color: #FF0000">"orders.created_at >= ? AND orders.created_at <= ?"</span><span style="color: #990000">,</span> Time<span style="color: #990000">.</span>now <span style="color: #990000">-</span> <span style="color: #993399">2</span><span style="color: #990000">.</span>weeks<span style="color: #990000">,</span> Time<span style="color: #990000">.</span>now<span style="color: #990000">])</span>
</tt></pre></div></div>
</div>
-<h2 id="_dynamic_finders">14. Dynamic finders</h2>
+<h2 id="_dynamic_finders">13. Dynamic finders</h2>
<div class="sectionbody">
<div class="para"><p>For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called <tt>name</tt> on your Client model for example, you get <tt>find_by_name</tt> and <tt>find_all_by_name</tt> for free from Active Record. If you have also have a <tt>locked</tt> field on the client model, you also get <tt>find_by_locked</tt> and <tt>find_all_by_locked</tt>. If you want to find both by name and locked, you can chain these finders together by simply typing <tt>and</tt> between the fields for example <tt>Client.find_by_name_and_locked(<em>Ryan</em>, true)</tt>. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type <tt>find_by_name(params[:name])</tt> than it is to type <tt>first(:conditions ⇒ ["name = ?", params[:name]])</tt>.</p></div>
<div class="para"><p>There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like <tt>find_or_create_by_name(params[:name])</tt>. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for <tt>Client.find_or_create_by_name(<em>Ryan</em>)</tt>:</p></div>
@@ -719,7 +753,7 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>will either assign an existing client object with the name <em>Ryan</em> to the client local variable, or initialize new object similar to calling <tt>Client.new(:name ⇒ <em>Ryan</em>)</tt>. From here, you can modify other fields in client by calling the attribute setters on it: <tt>client.locked = true</tt> and when you want to write it to the database just call <tt>save</tt> on it.</p></div>
</div>
-<h2 id="_finding_by_sql">15. Finding By SQL</h2>
+<h2 id="_finding_by_sql">14. Finding By SQL</h2>
<div class="sectionbody">
<div class="para"><p>If you'd like to use your own SQL to find records a table you can use <tt>find_by_sql</tt>. The <tt>find_by_sql</tt> method will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:</p></div>
<div class="listingblock">
@@ -729,11 +763,11 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>find_by_sql<span style="color: #990000">(</span><span style="color: #FF0000">"SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
-<div class="para"><p><tt>find_by_sql</tt> provides you with a simple way of making custom calls to the database and retreiving instantiated objects.</p></div>
+<div class="para"><p><tt>find_by_sql</tt> provides you with a simple way of making custom calls to the database and retrieving instantiated objects.</p></div>
</div>
-<h2 id="_tt_select_all_tt">16. <tt>select_all</tt></h2>
+<h2 id="_tt_select_all_tt">15. <tt>select_all</tt></h2>
<div class="sectionbody">
-<div class="para"><p><tt>find_by_sql</tt> has a close relative called <tt>select_all</tt>. <tt>select_all</tt> will retreive objects from the database using custom SQL just like <tt>find_by_sql</tt> but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.</p></div>
+<div class="para"><p><tt>find_by_sql</tt> has a close relative called <tt>connection#select_all</tt>. <tt>select_all</tt> will retrieve objects from the database using custom SQL just like <tt>find_by_sql</tt> but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -742,13 +776,15 @@ http://www.gnu.org/software/src-highlite --> <pre><tt>Client<span style="color: #990000">.</span>connection<span style="color: #990000">.</span>select_all<span style="color: #990000">(</span><span style="color: #FF0000">"SELECT * FROM `clients` WHERE `id` = '1'"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
</div>
-<h2 id="_working_with_associations">17. Working with Associations</h2>
+<h2 id="_working_with_associations">16. Working with Associations</h2>
<div class="sectionbody">
-<div class="para"><p>When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an exisiting record, for example finding all the orders for a client that have been sent and not received by doing something like <tt>Client.find(params[:id]).orders.find_by_sent_and_received(true, false)</tt>. Having this find method available on associations is extremely helpful when using nested controllers.</p></div>
+<div class="para"><p>When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an existing record, for example finding all the orders for a client that have been sent and not received by doing something like <tt>Client.find(params[:id]).orders.find_by_sent_and_received(true, false)</tt>. Having this find method available on associations is extremely helpful when using nested controllers.</p></div>
</div>
-<h2 id="_named_scopes">18. Named Scopes</h2>
+<h2 id="_named_scopes">17. Named Scopes</h2>
<div class="sectionbody">
-<div class="para"><p>Named scopes are another way to add custom finding behavior to the models in the application. Suppose want to find all clients who are male. Yould use this code:</p></div>
+<div class="para"><p>Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query.</p></div>
+<h3 id="_simple_named_scopes">17.1. Simple Named Scopes</h3>
+<div class="para"><p>Suppose want to find all clients who are male. You could use this code:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -758,7 +794,7 @@ http://www.gnu.org/software/src-highlite --> named_scope <span style="color: #990000">:</span>males<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=></span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>gender <span style="color: #990000">=></span> <span style="color: #FF0000">"male"</span> <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>And you could call it like <tt>Client.males.all</tt> to get all the clients who are male. Please note that if you do not specify the <tt>all</tt> on the end you will get a <tt>Scope</tt> object back, not a set of records which you do get back if you put the <tt>all</tt> on the end.</p></div>
+<div class="para"><p>Then you could call <tt>Client.males.all</tt> to get all the clients who are male. Please note that if you do not specify the <tt>all</tt> on the end you will get a <tt>Scope</tt> object back, not a set of records which you do get back if you put the <tt>all</tt> on the end.</p></div>
<div class="para"><p>If you wanted to find all the clients who are active, you could use this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -769,7 +805,8 @@ http://www.gnu.org/software/src-highlite --> named_scope <span style="color: #990000">:</span>active<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=></span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>active <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>You can call this new named_scope by doing <tt>Client.active.all</tt> and this will do the same query as if we just used <tt>Client.all(:conditions ⇒ ["active = ?", true])</tt>. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do <tt>Client.active.first</tt>.</p></div>
+<div class="para"><p>You can call this new named_scope with <tt>Client.active.all</tt> and this will do the same query as if we just used <tt>Client.all(:conditions ⇒ ["active = ?", true])</tt>. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do <tt>Client.active.first</tt>.</p></div>
+<h3 id="_combining_named_scopes">17.2. Combining Named Scopes</h3>
<div class="para"><p>If you wanted to find all the clients who are active and male you can stack the named scopes like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -786,6 +823,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>males<span style="color: #990000">.</span>active<span style="color: #990000">.</span>all<span style="color: #990000">(:</span>conditions <span style="color: #990000">=></span> <span style="color: #990000">[</span><span style="color: #FF0000">"age > ?"</span><span style="color: #990000">,</span> params<span style="color: #990000">[:</span>age<span style="color: #990000">]])</span>
</tt></pre></div></div>
+<h3 id="_runtime_evaluation_of_named_scope_conditions">17.3. Runtime Evaluation of Named Scope Conditions</h3>
<div class="para"><p>Consider the following code:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -807,6 +845,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.</p></div>
+<h3 id="_named_scopes_with_multiple_models">17.4. Named Scopes with Multiple Models</h3>
<div class="para"><p>In a named scope you can use <tt>:include</tt> and <tt>:joins</tt> options just like in find.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -819,6 +858,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>This method, called as <tt>Client.active_within_2_weeks.all</tt>, will return all clients who have placed orders in the past 2 weeks.</p></div>
+<h3 id="_arguments_to_named_scopes">17.5. Arguments to Named Scopes</h3>
<div class="para"><p>If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -841,7 +881,8 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>This will work with <tt>Client.recent(2.weeks.ago).all</tt> and <tt>Client.recent.all</tt>, with the latter always returning records with a created_at date between right now and 2 weeks ago.</p></div>
<div class="para"><p>Remember that named scopes are stackable, so you will be able to do <tt>Client.recent(2.weeks.ago).unlocked.all</tt> to find all clients created between right now and 2 weeks ago and have their locked field set to false.</p></div>
-<div class="para"><p>Finally, if you wish to define named scopes on the fly you can use the scoped method:</p></div>
+<h3 id="_anonymous_scopes">17.6. Anonymous Scopes</h3>
+<div class="para"><p>All Active Record models come with a named scope named <tt>scoped</tt>, which allows you to create anonymous scopes. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -853,8 +894,17 @@ http://www.gnu.org/software/src-highlite --> <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="para"><p>Anonymous scopes are most useful to create scopes "on the fly":</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>Client<span style="color: #990000">.</span>scoped<span style="color: #990000">(:</span>conditions <span style="color: #990000">=></span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>gender <span style="color: #990000">=></span> <span style="color: #FF0000">"male"</span> <span style="color: #FF0000">}</span><span style="color: #990000">)</span>
+</tt></pre></div></div>
+<div class="para"><p>Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.</p></div>
</div>
-<h2 id="_existence_of_objects">19. Existence of Objects</h2>
+<h2 id="_existence_of_objects">18. Existence of Objects</h2>
<div class="sectionbody">
<div class="para"><p>If you simply want to check for the existence of the object there's a method called <tt>exists?</tt>. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.</p></div>
<div class="listingblock">
@@ -864,7 +914,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>exists?<span style="color: #990000">(</span><span style="color: #993399">1</span><span style="color: #990000">)</span>
</tt></pre></div></div>
-<div class="para"><p>The above code will check for the existance of a clients table record with the id of 1 and return true if it exists.</p></div>
+<div class="para"><p>The above code will check for the existence of a clients table record with the id of 1 and return true if it exists.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -884,7 +934,7 @@ http://www.gnu.org/software/src-highlite --> <pre><tt>Client<span style="color: #990000">.</span>exists?<span style="color: #990000">(:</span>conditions <span style="color: #990000">=></span> <span style="color: #FF0000">"first_name = 'Ryan'"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
</div>
-<h2 id="_calculations">20. Calculations</h2>
+<h2 id="_calculations">19. Calculations</h2>
<div class="sectionbody">
<div class="para"><p>This section uses count as an example method in this preamble, but the options described apply to all sub-sections.</p></div>
<div class="para"><p><tt>count</tt> takes conditions much in the same way <tt>exists?</tt> does:</p></div>
@@ -922,10 +972,10 @@ http://www.gnu.org/software/src-highlite --> <span style="color: #990000">(</span>clients<span style="color: #990000">.</span>first_name <span style="color: #990000">=</span> <span style="color: #FF0000">'name'</span> <span style="font-weight: bold"><span style="color: #0000FF">AND</span></span> orders<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">status</span></span> <span style="color: #990000">=</span> <span style="color: #FF0000">'received'</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>This code specifies <tt>clients.first_name</tt> just in case one of the join tables has a field also called <tt>first_name</tt> and it uses <tt>orders.status</tt> because that's the name of our join table.</p></div>
-<h3 id="_count">20.1. Count</h3>
+<h3 id="_count">19.1. Count</h3>
<div class="para"><p>If you want to see how many records are in your model's table you could call <tt>Client.count</tt> and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use <tt>Client.count(:age)</tt>.</p></div>
<div class="para"><p>For options, please see the parent section, Calculations.</p></div>
-<h3 id="_average">20.2. Average</h3>
+<h3 id="_average">19.2. Average</h3>
<div class="para"><p>If you want to see the average of a certain number in one of your tables you can call the <tt>average</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -936,7 +986,7 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.</p></div>
<div class="para"><p>For options, please see the parent section, <a href="#_calculations">Calculations</a></p></div>
-<h3 id="_minimum">20.3. Minimum</h3>
+<h3 id="_minimum">19.3. Minimum</h3>
<div class="para"><p>If you want to find the minimum value of a field in your table you can call the <tt>minimum</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -946,7 +996,7 @@ http://www.gnu.org/software/src-highlite --> <pre><tt>Client<span style="color: #990000">.</span>minimum<span style="color: #990000">(</span><span style="color: #FF0000">"age"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>For options, please see the parent section, <a href="#_calculations">Calculations</a></p></div>
-<h3 id="_maximum">20.4. Maximum</h3>
+<h3 id="_maximum">19.4. Maximum</h3>
<div class="para"><p>If you want to find the maximum value of a field in your table you can call the <tt>maximum</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -956,7 +1006,7 @@ http://www.gnu.org/software/src-highlite --> <pre><tt>Client<span style="color: #990000">.</span>maximum<span style="color: #990000">(</span><span style="color: #FF0000">"age"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>For options, please see the parent section, <a href="#_calculations">Calculations</a></p></div>
-<h3 id="_sum">20.5. Sum</h3>
+<h3 id="_sum">19.5. Sum</h3>
<div class="para"><p>If you want to find the sum of a field for all records in your table you can call the <tt>sum</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -967,23 +1017,28 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>For options, please see the parent section, <a href="#_calculations">Calculations</a></p></div>
</div>
-<h2 id="_credits">21. Credits</h2>
+<h2 id="_credits">20. Credits</h2>
<div class="sectionbody">
<div class="para"><p>Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.</p></div>
<div class="para"><p>Thanks to Mike Gunderloy for his tips on creating this guide.</p></div>
</div>
-<h2 id="_changelog">22. Changelog</h2>
+<h2 id="_changelog">21. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
<li>
<p>
-October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section.
+November 8, 2008: Editing pass by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> . First release version.
+</p>
+</li>
+<li>
+<p>
+October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg
</p>
</li>
<li>
<p>
-October 27, 2008: Fixed up all points specified in <a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6">this comment</a> with an exception of the final point.
+October 27, 2008: Fixed up all points specified in <a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6">this comment</a> with an exception of the final point by Ryan Bigg
</p>
</li>
<li>
diff --git a/railties/doc/guides/html/form_helpers.html b/railties/doc/guides/html/form_helpers.html index 28c317411b..7ff4a13a6a 100644 --- a/railties/doc/guides/html/form_helpers.html +++ b/railties/doc/guides/html/form_helpers.html @@ -220,6 +220,16 @@ ul#navMain { </ul> </li> + <li> + <a href="#_making_select_boxes_with_ease">Making select boxes with ease</a> + <ul> + + <li><a href="#_the_select_tag_and_options">The select tag and options</a></li> + + <li><a href="#_select_boxes_for_dealing_with_models">Select boxes for dealing with models</a></li> + + </ul> + </li> </ol> </div> @@ -227,7 +237,7 @@ ul#navMain { <h1>Rails form helpers</h1> <div id="preamble">
<div class="sectionbody">
-<div class="para"><p>Forms in web applications are an essential interface for user input. They are also often considered the most complex elements of HTML. Rails deals away with these complexities by providing numerous view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.</p></div>
+<div class="para"><p>Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.</p></div>
<div class="para"><p>In this guide we will:</p></div>
<div class="ilist"><ul>
<li>
@@ -392,7 +402,7 @@ a submit element. <td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
-<td class="content">Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an ugly <tt>expecting tASSOC</tt> syntax error.</td>
+<td class="content">Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an <tt>expecting tASSOC</tt> syntax error.</td>
</tr></table>
</div>
<h3 id="_checkboxes_radio_buttons_and_other_controls">1.3. Checkboxes, radio buttons and other controls</h3>
@@ -431,7 +441,7 @@ output: <td class="icon">
<img src="./images/icons/important.png" alt="Important" />
</td>
-<td class="content">Always use labels for each checkbox and radio button. They associate text with a specific option, while also providing a larger clickable region.</td>
+<td class="content">Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.</td>
</tr></table>
</div>
<div class="para"><p>Other form controls we might mention are the text area, password input and hidden input:</p></div>
@@ -458,7 +468,7 @@ output: </div>
<h3 id="_how_do_forms_with_put_or_delete_methods_work">1.4. How do forms with PUT or DELETE methods work?</h3>
<div class="para"><p>Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PUT" and "DELETE" requests (besides "GET" and "POST"). Still, most browsers <em>don't support</em> methods other than "GET" and "POST" when it comes to submitting forms. How does this work, then?</p></div>
-<div class="para"><p>Rails works around this issue by emulating other methods over POST with a hidden input named <tt>"<em>method"</tt> that is set to reflect the _real</em> method:</p></div>
+<div class="para"><p>Rails works around this issue by emulating other methods over POST with a hidden input named <tt>"_method"</tt> that is set to reflect the wanted method:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>form_tag(search_path, :method => "put")
@@ -563,6 +573,64 @@ form_for(@article)</tt></pre> </tr></table>
</div>
</div>
+<h2 id="_making_select_boxes_with_ease">3. Making select boxes with ease</h2>
+<div class="sectionbody">
+<div class="para"><p>Select boxes in HTML require a significant amount of markup (one <tt>OPTION</tt> element for each option to choose from), therefore it makes the most sense for them to be dynamically generated from data stored in arrays or hashes.</p></div>
+<div class="para"><p>Here is what our wanted markup might look like:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt><select name="city_id" id="city_id">
+ <option value="1">Lisabon</option>
+ <option value="2">Madrid</option>
+ ...
+ <option value="12">Berlin</option>
+</select></tt></pre>
+</div></div>
+<div class="para"><p>Here we have a list of cities where their names are presented to the user, but internally we want to handle just their IDs so we keep them in value attributes. Let's see how Rails can help out here.</p></div>
+<h3 id="_the_select_tag_and_options">3.1. The select tag and options</h3>
+<div class="para"><p>The most generic helper is <tt>select_tag</tt>, which — as the name implies — simply generates the <tt>SELECT</tt> tag that encapsulates the options:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt><%= select_tag(:city_id, '<option value="1">Lisabon</option>...') %></tt></pre>
+</div></div>
+<div class="para"><p>This is a start, but it doesn't dynamically create our option tags. We had to pass them in as a string.</p></div>
+<div class="para"><p>We can generate option tags with the <tt>options_for_select</tt> helper:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt><%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
+
+output:
+
+<option value="1">Lisabon</option>
+<option value="2">Madrid</option>
+...</tt></pre>
+</div></div>
+<div class="para"><p>For input data we used a nested array where each element has two elements: visible value (name) and internal value (ID).</p></div>
+<div class="para"><p>Now you can combine <tt>select_tag</tt> and <tt>options_for_select</tt> to achieve the desired, complete markup:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt><%= select_tag(:city_id, options_for_select(...)) %></tt></pre>
+</div></div>
+<div class="para"><p>Sometimes, depending on our application's needs, we also wish a specific option to be pre-selected. The <tt>options_for_select</tt> helper supports this with an optional second argument:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt><%= options_for_select(cities_array, 2) %>
+
+output:
+
+<option value="1">Lisabon</option>
+<option value="2" selected="selected">Madrid</option>
+...</tt></pre>
+</div></div>
+<div class="para"><p>So whenever Rails sees that the internal value of an option being generated matches this value, it will add the <tt>selected</tt> attribute to that option.</p></div>
+<h3 id="_select_boxes_for_dealing_with_models">3.2. Select boxes for dealing with models</h3>
+<div class="para"><p>Until now we've covered how to make generic select boxes, but in most cases our form controls will be tied to a specific database model. So, to continue from our previous examples, let's assume that we have a "Person" model with a <tt>city_id</tt> attribute.</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>...</tt></pre>
+</div></div>
+<div class="para"><p>…</p></div>
+</div>
</div> </div> diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html index 797ae2fb3a..5111d0c645 100644 --- a/railties/doc/guides/html/getting_started_with_rails.html +++ b/railties/doc/guides/html/getting_started_with_rails.html @@ -712,7 +712,7 @@ The <tt>production</tt> environment is used when you deploy your application for </li>
</ul></div>
<h4 id="_configuring_a_sqlite_database">3.3.1. Configuring a SQLite Database</h4>
-<div class="para"><p>Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.</p></div>
+<div class="para"><p>Rails comes with built-in support for <a href="http://www.sqlite.org/">SQLite</a>, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.</p></div>
<div class="para"><p>Here's the section of the default configuration file with connection information for the development environment:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1159,7 +1159,7 @@ http://www.gnu.org/software/src-highlite --> <td class="content">For more information on finding records with Active Record, see <a href="../finders.html">Active Record Finders</a>.</td>
</tr></table>
</div>
-<div class="para"><p>The <tt>respond_to</tt> block handles both HTML and XML calls to this action. If you borwse to <tt>http://localhost:3000/posts.xml</tt>, you'll see all of the posts in XML format. The HTML format looks for a view in <tt>app/views/posts/</tt> with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's <tt>app/view/posts/index.html.erb</tt>:</p></div>
+<div class="para"><p>The <tt>respond_to</tt> block handles both HTML and XML calls to this action. If you browse to <tt>http://localhost:3000/posts.xml</tt>, you'll see all of the posts in XML format. The HTML format looks for a view in <tt>app/views/posts/</tt> with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's <tt>app/view/posts/index.html.erb</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1457,51 +1457,57 @@ http://www.gnu.org/software/src-highlite --> <div class="para"><p>At this point, it’s worth looking at some of the tools that Rails provides to eliminate duplication in your code. In particular, you can use <em>partials</em> to clean up duplication in views and <em>filters</em> to help with duplication in controllers.</p></div>
<h3 id="_using_partials_to_eliminate_view_duplication">7.1. Using Partials to Eliminate View Duplication</h3>
<div class="para"><p>As you saw earlier, the scaffold-generated views for the <tt>new</tt> and <tt>edit</tt> actions are largely identical. You can pull the shared code out into a <tt>partial</tt> template. This requires editing the new and edit views, and adding a new template:</p></div>
-<div class="para"><p><tt>new.html.erb</tt>:
-[source, ruby]</p></div>
+<div class="para"><p><tt>new.html.erb</tt>:</p></div>
<div class="listingblock">
-<div class="content">
-<pre><tt><h1>New post</h1>
+<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: #FF0000"><h1></span>New post<span style="color: #FF0000"></h1></span>
-<%= render :partial => "form" %>
+<span style="color: #FF0000"><%= render :partial =></span> <span style="color: #FF0000">"form"</span> <span style="color: #990000">%></span>
-<%= link_to 'Back', posts_path %></tt></pre>
-</div></div>
-<div class="para"><p><tt>edit.html.erb</tt>:
-[source, ruby]</p></div>
+<span style="color: #FF0000"><%= link_to 'Back', posts_path %></span>
+</tt></pre></div></div>
+<div class="para"><p><tt>edit.html.erb</tt>:</p></div>
<div class="listingblock">
-<div class="content">
-<pre><tt><h1>Editing post</h1>
+<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: #FF0000"><h1></span>Editing post<span style="color: #FF0000"></h1></span>
-<%= render :partial => "form" %>
+<span style="color: #FF0000"><%= render :partial =></span> <span style="color: #FF0000">"form"</span> <span style="color: #990000">%></span>
-<%= link_to 'Show', @post %> |
-<%= link_to 'Back', posts_path %></tt></pre>
-</div></div>
-<div class="para"><p><tt>_form.html.erb</tt>:
-[source, ruby]</p></div>
+<span style="color: #FF0000"><%= link_to 'Show', @post %></span> <span style="color: #990000">|</span>
+<span style="color: #FF0000"><%= link_to 'Back', posts_path %></span>
+</tt></pre></div></div>
+<div class="para"><p><tt>_form.html.erb</tt>:</p></div>
<div class="listingblock">
-<div class="content">
-<pre><tt><% form_for(@post) do |f| %>
- <%= f.error_messages %>
-
- <p>
- <%= f.label :name %><br />
- <%= f.text_field :name %>
- </p>
- <p>
- <%= f.label :title, "title" %><br />
- <%= f.text_field :title %>
- </p>
- <p>
- <%= f.label :content %><br />
- <%= f.text_area :content %>
- </p>
- <p>
- <%= f.submit "Save" %>
- </p>
-<% end %></tt></pre>
-</div></div>
+<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: #FF0000"><% form_for(@post) do |f| %></span>
+ <span style="color: #FF0000"><%= f.error_messages %></span>
+
+ <span style="color: #FF0000"><p></span>
+ <span style="color: #FF0000"><%= f.label :name %><br /></span>
+ <span style="color: #FF0000"><%= f.text_field :name %></span>
+ <span style="color: #FF0000"></p></span>
+ <span style="color: #FF0000"><p></span>
+ <span style="color: #FF0000"><%= f.label :title, "title" %><br /></span>
+ <span style="color: #FF0000"><%= f.text_field :title %></span>
+ <span style="color: #FF0000"></p></span>
+ <span style="color: #FF0000"><p></span>
+ <span style="color: #FF0000"><%= f.label :content %><br /></span>
+ <span style="color: #FF0000"><%= f.text_area :content %></span>
+ <span style="color: #FF0000"></p></span>
+ <span style="color: #FF0000"><p></span>
+ <span style="color: #FF0000"><%= f.submit "Save" %></span>
+ <span style="color: #FF0000"></p></span>
+<span style="color: #FF0000"><% end %></span>
+</tt></pre></div></div>
<div class="para"><p>Now, when Rails renders the <tt>new</tt> or <tt>edit</tt> view, it will insert the <tt>_form</tt> partial at the indicated point. Note the naming convention for partials: if you refer to a partial named <tt>form</tt> inside of a view, the corresponding file is <tt>_form.html.erb</tt>, with a leading underscore.</p></div>
<div class="para"><p>For more information on partials, refer to the <a href="../layouts_and_rendering.html">Layouts and Rending in Rails</a> guide.</p></div>
<h3 id="_using_filters_to_eliminate_controller_duplication">7.2. Using Filters to Eliminate Controller Duplication</h3>
@@ -1721,32 +1727,32 @@ http://www.gnu.org/software/src-highlite --> </li>
<li>
<p>
-+app/helpers/comments_helper.rb - A view helper file
+<tt>app/helpers/comments_helper.rb</tt> - A view helper file
</p>
</li>
<li>
<p>
-+app/views/comments/index.html.erb - The view for the index action
+<tt>app/views/comments/index.html.erb</tt> - The view for the index action
</p>
</li>
<li>
<p>
-+app/views/comments/show.html.erb - The view for the show action
+<tt>app/views/comments/show.html.erb</tt> - The view for the show action
</p>
</li>
<li>
<p>
-+app/views/comments/new.html.erb - The view for the new action
+<tt>app/views/comments/new.html.erb</tt> - The view for the new action
</p>
</li>
<li>
<p>
-+app/views/comments/edit.html.erb - The view for the edit action
+<tt>app/views/comments/edit.html.erb</tt> - The view for the edit action
</p>
</li>
<li>
<p>
-+test/functional/comments_controller_test.rb - The functional tests for the controller
+<tt>test/functional/comments_controller_test.rb</tt> - The functional tests for the controller
</p>
</li>
</ul></div>
@@ -1984,7 +1990,7 @@ http://www.gnu.org/software/src-highlite --> <div class="ilist"><ul>
<li>
<p>
-The [http://manuals.rubyonrails.org/]Ruby On Rails guides
+The <a href="http://manuals.rubyonrails.org/">Ruby On Rails guides</a>
</p>
</li>
<li>
@@ -2003,6 +2009,19 @@ The <a href="http://wiki.rubyonrails.org/rails">Rails wiki</a> </p>
</li>
</ul></div>
+<div class="para"><p>Rails also comes with built-in help that you can generate using the rake command-line utility:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Running <tt>rake doc:guides</tt> will put a full copy of the Rails Guides in the <tt>/doc/guides</tt> folder of your application. Open <tt>/doc/guides/index.html</tt> in your web browser to explore the Guides.
+</p>
+</li>
+<li>
+<p>
+Running <tt>rake doc:rails</tt> will put a full copy of the API documentation for Rails in the <tt>/doc/api</tt> folder of your application. Open <tt>/doc/api/index.html</tt> in your web browser to explore the API documentation.
+</p>
+</li>
+</ul></div>
</div>
<h2 id="_changelog">10. Changelog</h2>
<div class="sectionbody">
@@ -2010,6 +2029,11 @@ The <a href="http://wiki.rubyonrails.org/rails">Rails wiki</a> <div class="ilist"><ul>
<li>
<p>
+November 3, 2008: Formatting patch from Dave Rothlisberger
+</p>
+</li>
+<li>
+<p>
November 1, 2008: First approved version by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
</p>
</li>
diff --git a/railties/doc/guides/html/index.html b/railties/doc/guides/html/index.html index 306257678b..991b10c7e8 100644 --- a/railties/doc/guides/html/index.html +++ b/railties/doc/guides/html/index.html @@ -250,7 +250,7 @@ ul#navMain { <div class="sidebar-content">
<div class="sidebar-title"><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></div>
<div class="para"><p>This guide covers the basic layout features of Action Controller and Action View,
-including rendering and redirecting, using +content_for_ blocks, and working
+including rendering and redirecting, using <tt>content_for</tt> blocks, and working
with partials.</p></div>
</div></div>
<div class="sidebarblock">
@@ -276,14 +276,6 @@ understand how to use routing in your own Rails applications, start here.</p></d <div class="sidebarblock">
<div class="sidebar-content">
<div class="sidebar-title"><a href="actioncontroller_basics.html">Basics of Action Controller</a></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/caution.png" alt="Caution" />
-</td>
-<td class="content"><a href="http://rails.lighthouseapp.com/projects/16213/tickets/17">Lighthouse Ticket</a></td>
-</tr></table>
-</div>
<div class="para"><p>This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics.</p></div>
</div></div>
<div class="sidebarblock">
@@ -318,20 +310,12 @@ Enjoy.</p></div> <div class="sidebarblock">
<div class="sidebar-content">
<div class="sidebar-title"><a href="security.html">Securing Rails Applications</a></div>
-<div class="para"><p>This manual describes common security problems in web applications and how to
+<div class="para"><p>This guide describes common security problems in web applications and how to
avoid them with Rails.</p></div>
</div></div>
<div class="sidebarblock">
<div class="sidebar-content">
<div class="sidebar-title"><a href="debugging_rails_applications.html">Debugging Rails Applications</a></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/caution.png" alt="Caution" />
-</td>
-<td class="content"><a href="http://rails.lighthouseapp.com/projects/16213/tickets/5">Lighthouse Ticket</a></td>
-</tr></table>
-</div>
<div class="para"><p>This guide describes how to debug Rails applications. It covers the different
ways of achieving this and how to understand what is happening "behind the scenes"
of your code.</p></div>
diff --git a/railties/doc/guides/html/layouts_and_rendering.html b/railties/doc/guides/html/layouts_and_rendering.html index 1c9ef8ce24..7138c45853 100644 --- a/railties/doc/guides/html/layouts_and_rendering.html +++ b/railties/doc/guides/html/layouts_and_rendering.html @@ -1305,6 +1305,14 @@ http://www.gnu.org/software/src-highlite --> <pre><tt><%= render :partial => "product", :collection => @products, :as => :item %>
</tt></pre></div></div>
<div class="para"><p>With this change, you can access an instance of the <tt>@products</tt> collection as the <tt>item</tt> local variable within the partial.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by <tt>_counter</tt>. For example, if you're rendering <tt>@products</tt>, within the partial you can refer to <tt>product_counter</tt> to tell you how many times the partial has been rendered.</td>
+</tr></table>
+</div>
<div class="para"><p>You can also specify a second partial to be rendered between instances of the main partial by using the <tt>:spacer_template</tt> option:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1366,6 +1374,11 @@ http://www.gnu.org/software/src-highlite --> <div class="ilist"><ul>
<li>
<p>
+November 9, 2008: Added partial collection counter by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
+</p>
+</li>
+<li>
+<p>
November 1, 2008: Added <tt>:js</tt> option for <tt>render</tt> by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
</p>
</li>
diff --git a/railties/doc/guides/html/migrations.html b/railties/doc/guides/html/migrations.html index fd466d3a02..8b580d8086 100644 --- a/railties/doc/guides/html/migrations.html +++ b/railties/doc/guides/html/migrations.html @@ -717,7 +717,7 @@ version is the numerical prefix on the migration's filename. For example to migr <div class="content">
<pre><tt>rake db:rollback STEP=3</tt></pre>
</div></div>
-<div class="para"><p>will run the <tt>down</tt> method fron the last 3 migrations.</p></div>
+<div class="para"><p>will run the <tt>down</tt> method from the last 3 migrations.</p></div>
<div class="para"><p>The <tt>db:migrate:redo</tt> task is a shortcut for doing a rollback and then migrating back up again. As with the <tt>db:rollback</tt> task you can use the <tt>STEP</tt> parameter if you need to go more than one version back, for example</p></div>
<div class="listingblock">
<div class="content">
@@ -865,7 +865,7 @@ http://www.gnu.org/software/src-highlite --> <div class="para"><p>Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either <tt>schema.rb</tt> or an SQL file which Active Record generates by examining the database. They are not designed to be edited, they just represent the current state of the database.</p></div>
<div class="para"><p>There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema.</p></div>
<div class="para"><p>For example, this is how the test database is created: the current development database is dumped (either to <tt>schema.rb</tt> or <tt>development.sql</tt>) and then loaded into the test database.</p></div>
-<div class="para"><p>Schema files are also useful if want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The <a href="http://agilewebdevelopment.com/plugins/annotate_models">annotate_models</a> plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.</p></div>
+<div class="para"><p>Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The <a href="http://agilewebdevelopment.com/plugins/annotate_models">annotate_models</a> plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.</p></div>
<h3 id="_types_of_schema_dumps">6.2. Types of schema dumps</h3>
<div class="para"><p>There are two ways to dump the schema. This is set in <tt>config/environment.rb</tt> by the <tt>config.active_record.schema_format</tt> setting, which may be either <tt>:sql</tt> or <tt>:ruby</tt>.</p></div>
<div class="para"><p>If <tt>:ruby</tt> is selected then the schema is stored in <tt>db/schema.rb</tt>. If you look at this file you'll find that it looks an awful lot like one very big migration:</p></div>
@@ -899,7 +899,7 @@ http://www.gnu.org/software/src-highlite --> </div>
<h2 id="foreign_key">7. Active Record and Referential Integrity</h2>
<div class="sectionbody">
-<div class="para"><p>The Active Record way is that intelligence belongs in your models, not in the database. As such features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used.</p></div>
+<div class="para"><p>The Active Record way is that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used.</p></div>
<div class="para"><p>Validations such as <tt>validates_uniqueness_of</tt> are one way in which models can enforce data integrity. The <tt>:dependent</tt> option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints.</p></div>
<div class="para"><p>Although Active Record does not provide any tools for working directly with such features, the <tt>execute</tt> method can be used to execute arbitrary SQL. There are also a number of plugins such as <a href="http://agilewebdevelopment.com/plugins/search?search=redhillonrails">redhillonrails</a> which add foreign key support to Active Record (including support for dumping foreign keys in <tt>schema.rb</tt>).</p></div>
</div>
diff --git a/railties/doc/guides/html/routing_outside_in.html b/railties/doc/guides/html/routing_outside_in.html index a1f1f98cfb..947d0836ce 100644 --- a/railties/doc/guides/html/routing_outside_in.html +++ b/railties/doc/guides/html/routing_outside_in.html @@ -925,6 +925,16 @@ cellspacing="0" cellpadding="4"> <tt>:name_prefix</tt>
</p>
</li>
+<li>
+<p>
+<tt>:only</tt>
+</p>
+</li>
+<li>
+<p>
+<tt>:except</tt>
+</p>
+</li>
</ul></div>
<div class="para"><p>You can also add additional routes via the <tt>:member</tt> and <tt>:collection</tt> options, which are discussed later in this guide.</p></div>
<h4 id="_using_controller">3.6.1. Using :controller</h4>
@@ -1419,6 +1429,34 @@ map<span style="color: #990000">.</span>resources <span style="color: #990000">: <td class="content">You can also use <tt>:name_prefix</tt> with non-RESTful routes.</td>
</tr></table>
</div>
+<h4 id="_using_only_and_except">3.7.8. Using :only and :except</h4>
+<div class="para"><p>By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the <tt>:only</tt> and <tt>:except</tt> options to fine-tune this behavior. The <tt>:only</tt> option specifies that only certain routes should be generated:</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>map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>photos<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=></span> <span style="color: #990000">[:</span>index<span style="color: #990000">,</span> <span style="color: #990000">:</span>show<span style="color: #990000">]</span>
+</tt></pre></div></div>
+<div class="para"><p>With this declaration, a <tt>GET</tt> request to <tt>/photos</tt> would succeed, but a <tt>POST</tt> request to <tt>/photos</tt> (which would ordinarily be routed to the create action) will fail.</p></div>
+<div class="para"><p>The <tt>:except</tt> option specifies a route or list of routes that should <em>not</em> be generated:</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>map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>photos<span style="color: #990000">,</span> <span style="color: #990000">:</span>except <span style="color: #990000">=></span> <span style="color: #990000">:</span>destroy
+</tt></pre></div></div>
+<div class="para"><p>In this case, all of the normal routes except the route for <tt>destroy</tt> (a <tt>DELETE</tt> request to <tt>/photos/<em>id</em></tt>) will be generated.</p></div>
+<div class="para"><p>In addition to an action or a list of actions, you can also supply the special symbols <tt>:all</tt> or <tt>:none</tt> to the <tt>:only</tt> and <tt>:except</tt> options.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">If your application has many RESTful routes, using <tt>:only</tt> and <tt>:accept</tt> to generate only the routes that you actually need can cut down on memory use and speed up the routing process.</td>
+</tr></table>
+</div>
<h3 id="_nested_resources">3.8. Nested Resources</h3>
<div class="para"><p>It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:</p></div>
<div class="listingblock">
@@ -1690,15 +1728,7 @@ http://www.gnu.org/software/src-highlite --> /magazines/2/photos ==> magazines_photos_path(2)
/photos/3 ==> photo_path(3)</tt></pre>
</div></div>
-<div class="para"><p>With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you <em>can</em> supply more information. All of the nested routes continue to work, just as they would without shallow nesting, but less-deeply nested routes (even direct routes) work as well. So, with the declaration above, all of these routes refer to the same resource:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>/publishers/1/magazines/2/photos/3 ==> publisher_magazine_photo_path(1,2,3)
-/magazines/2/photos/3 ==> magazine_photo_path(2,3)
-/photos/3 ==> photo_path(3)</tt></pre>
-</div></div>
-<div class="para"><p>Shallow nesting gives you the flexibility to use the shorter direct routes when you like, while still preserving the longer nested routes for times when they add code clarity.</p></div>
-<div class="para"><p>If you like, you can combine shallow nesting with the <tt>:has_one</tt> and <tt>:has_many</tt> options:</p></div>
+<div class="para"><p>With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. If you like, you can combine shallow nesting with the <tt>:has_one</tt> and <tt>:has_many</tt> options:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
diff --git a/railties/doc/guides/html/testing_rails_applications.html b/railties/doc/guides/html/testing_rails_applications.html index 73634ef328..b8a99767ee 100644 --- a/railties/doc/guides/html/testing_rails_applications.html +++ b/railties/doc/guides/html/testing_rails_applications.html @@ -202,7 +202,7 @@ ul#navMain { <a href="#_why_write_tests_for_your_rails_applications">Why Write Tests for your Rails Applications?</a> </li> <li> - <a href="#_before_you_start_writing_tests">Before you Start Writing Tests</a> + <a href="#_introduction_to_testing">Introduction to Testing</a> <ul> <li><a href="#_the_3_environments">The 3 Environments</a></li> @@ -214,9 +214,11 @@ ul#navMain { </ul> </li> <li> - <a href="#_unit_testing_your_models">Unit Testing Your Models</a> + <a href="#_unit_testing_your_models">Unit Testing your Models</a> <ul> + <li><a href="#_preparing_you_application_for_testing">Preparing you Application for Testing</a></li> + <li><a href="#_running_tests">Running Tests</a></li> <li><a href="#_what_to_include_in_your_unit_tests">What to Include in Your Unit Tests</a></li> @@ -233,7 +235,7 @@ ul#navMain { <li><a href="#_what_to_include_in_your_functional_tests">What to include in your Functional Tests</a></li> - <li><a href="#_available_request_types_for_functional_tests">Available Request Types for Functional Tests===</a></li> + <li><a href="#_available_request_types_for_functional_tests">Available Request Types for Functional Tests</a></li> <li><a href="#_the_4_hashes_of_the_apocalypse">The 4 Hashes of the Apocalypse</a></li> @@ -256,6 +258,18 @@ ul#navMain { </ul> </li> <li> + <a href="#_rake_tasks_for_running_your_tests">Rake Tasks for Running your Tests</a> + </li> + <li> + <a href="#_brief_note_about_test_unit">Brief Note About Test::Unit</a> + </li> + <li> + <a href="#_setup_and_teardown">Setup and Teardown</a> + </li> + <li> + <a href="#_testing_routes">Testing Routes</a> + </li> + <li> <a href="#_testing_your_mailers">Testing Your Mailers</a> <ul> @@ -268,9 +282,6 @@ ul#navMain { </ul> </li> <li> - <a href="#_rake_tasks_for_testing">Rake Tasks for Testing</a> - </li> - <li> <a href="#_other_testing_approaches">Other Testing Approaches</a> </li> <li> @@ -309,12 +320,7 @@ Identify other popular testing approaches and plugins <div class="ilist"><ul>
<li>
<p>
-Because Ruby code that you write in your Rails application is interpreted, you may only find that it's broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code in advance and catching syntactical and logic errors.
-</p>
-</li>
-<li>
-<p>
-Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
+Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
</p>
</li>
<li>
@@ -324,16 +330,16 @@ By simply running your Rails tests you can ensure your code adheres to the desir </li>
<li>
<p>
-Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
+Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
</p>
</li>
</ul></div>
</div>
-<h2 id="_before_you_start_writing_tests">2. Before you Start Writing Tests</h2>
+<h2 id="_introduction_to_testing">2. Introduction to Testing</h2>
<div class="sectionbody">
-<div class="para"><p>Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.</p></div>
+<div class="para"><p>Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.</p></div>
<h3 id="_the_3_environments">2.1. The 3 Environments</h3>
-<div class="para"><p>Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.</p></div>
+<div class="para"><p>Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.</p></div>
<div class="para"><p>One place you'll find this distinction is in the <tt>config/database.yml</tt> file. This YAML configuration file has 3 different sections defining 3 unique database setups:</p></div>
<div class="ilist"><ul>
<li>
@@ -370,9 +376,9 @@ fixtures<span style="color: #990000">/</span> functional<span style="color <h3 id="_the_low_down_on_fixtures">2.3. The Low-Down on Fixtures</h3>
<div class="para"><p>For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.</p></div>
<h4 id="_what_are_fixtures">2.3.1. What Are Fixtures?</h4>
-<div class="para"><p><em>Fixtures</em> is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: <strong>YAML</strong> or <strong>CSV</strong>.</p></div>
+<div class="para"><p><em>Fixtures</em> is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: <strong>YAML</strong> or <strong>CSV</strong>. In this guide we will use <strong>YAML</strong> which is the preferred format.</p></div>
<div class="para"><p>You'll find fixtures under your <tt>test/fixtures</tt> directory. When you run <tt>script/generate model</tt> to create a new model, fixture stubs will be automatically created and placed in this directory.</p></div>
-<h4 id="_yaml_the_camel_is_a_mammal_with_enamel">2.3.2. YAML the Camel is a Mammal with Enamel</h4>
+<h4 id="_yaml">2.3.2. YAML</h4>
<div class="para"><p>YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the <strong>.yml</strong> file extension (as in <tt>users.yml</tt>).</p></div>
<div class="para"><p>Here's a sample YAML fixture file:</p></div>
<div class="listingblock">
@@ -382,81 +388,18 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># low & behold! I am a YAML comment!</span></span>
david<span style="color: #990000">:</span>
- id<span style="color: #990000">:</span> <span style="color: #993399">1</span>
name<span style="color: #990000">:</span> David Heinemeier Hansson
birthday<span style="color: #990000">:</span> <span style="color: #993399">1979</span><span style="color: #990000">-</span><span style="color: #993399">10</span><span style="color: #990000">-</span><span style="color: #993399">15</span>
profession<span style="color: #990000">:</span> Systems development
steve<span style="color: #990000">:</span>
- id<span style="color: #990000">:</span> <span style="color: #993399">2</span>
name<span style="color: #990000">:</span> Steve Ross Kellock
birthday<span style="color: #990000">:</span> <span style="color: #993399">1974</span><span style="color: #990000">-</span><span style="color: #993399">09</span><span style="color: #990000">-</span><span style="color: #993399">27</span>
profession<span style="color: #990000">:</span> guy with keyboard
</tt></pre></div></div>
<div class="para"><p>Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.</p></div>
-<h4 id="_comma_seperated">2.3.3. Comma Seperated</h4>
-<div class="para"><p>Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the <em>test/fixtures</em> directory, but these end with the <tt>.csv</tt> file extension (as in <tt>celebrity_holiday_figures.csv</tt>).</p></div>
-<div class="para"><p>A CSV fixture looks like this:</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>id, username, password, stretchable, comments
-1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
-2, ebunny, ihateeggs, true, Hoppity hop y'all
-3, tfairy, ilovecavities, true, "Pull your teeth, I will"
-</tt></pre></div></div>
-<div class="para"><p>The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-Leading and trailing spaces are trimmed from each value when it is imported
-</p>
-</li>
-<li>
-<p>
-If you use a comma as data, the cell must be encased in quotes
-</p>
-</li>
-<li>
-<p>
-If you use a quote as data, you must escape it with a 2nd quote
-</p>
-</li>
-<li>
-<p>
-Don't use blank lines
-</p>
-</li>
-<li>
-<p>
-Nulls can be defined by including no data between a pair of commas
-</p>
-</li>
-</ul></div>
-<div class="para"><p>Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-<tt>celebrity-holiday-figures-1</tt>
-</p>
-</li>
-<li>
-<p>
-<tt>celebrity-holiday-figures-2</tt>
-</p>
-</li>
-<li>
-<p>
-<tt>celebrity-holiday-figures-3</tt>
-</p>
-</li>
-</ul></div>
-<div class="para"><p>The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.</p></div>
-<h4 id="_erb_in_it_up">2.3.4. ERb'in It Up</h4>
+<h4 id="_erb_in_it_up">2.3.3. ERb'in It Up</h4>
<div class="para"><p>ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.</p></div>
-<div class="para"><p>I'll demonstrate with a YAML file:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -464,16 +407,16 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #FF0000"><% earth_size = 20 -%></span>
mercury<span style="color: #990000">:</span>
- id<span style="color: #990000">:</span> <span style="color: #993399">1</span>
size<span style="color: #990000">:</span> <span style="color: #FF0000"><%= earth_size / 50 %></span>
+ brightest_on<span style="color: #990000">:</span> <span style="color: #FF0000"><%= 113.days.ago.to_s(:db) %></span>
venus<span style="color: #990000">:</span>
- id<span style="color: #990000">:</span> <span style="color: #993399">2</span>
size<span style="color: #990000">:</span> <span style="color: #FF0000"><%= earth_size / 2 %></span>
+ brightest_on<span style="color: #990000">:</span> <span style="color: #FF0000"><%= 67.days.ago.to_s(:db) %></span>
mars<span style="color: #990000">:</span>
- id<span style="color: #990000">:</span> <span style="color: #993399">3</span>
size<span style="color: #990000">:</span> <span style="color: #FF0000"><%= earth_size - 69 %></span>
+ brightest_on<span style="color: #990000">:</span> <span style="color: #FF0000"><%= 13.days.from_now.to_s(:db) %></span>
</tt></pre></div></div>
<div class="para"><p>Anything encased within the</p></div>
<div class="listingblock">
@@ -483,8 +426,8 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #FF0000"><% %></span>
</tt></pre></div></div>
-<div class="para"><p>tag is considered Ruby code. When this fixture is loaded, the <tt>size</tt> attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively.</p></div>
-<h4 id="_fixtures_in_action">2.3.5. Fixtures in Action</h4>
+<div class="para"><p>tag is considered Ruby code. When this fixture is loaded, the <tt>size</tt> attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The <tt>brightest_on</tt> attribute will also be evaluated and formatted by Rails to be compatible with the database.</p></div>
+<h4 id="_fixtures_in_action">2.3.4. Fixtures in Action</h4>
<div class="para"><p>Rails by default automatically loads all fixtures from the <em>test/fixtures</em> folder for your unit and functional test. Loading involves three steps:</p></div>
<div class="ilist"><ul>
<li>
@@ -503,7 +446,7 @@ Dump the fixture data into a variable in case you want to access it directly </p>
</li>
</ul></div>
-<h4 id="_hashes_with_special_powers">2.3.6. Hashes with Special Powers</h4>
+<h4 id="_hashes_with_special_powers">2.3.5. Hashes with Special Powers</h4>
<div class="para"><p>Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -516,8 +459,7 @@ users<span style="color: #990000">(:</span>david<span style="color: #990000">)</ <span style="font-style: italic"><span style="color: #9A1900"># this will return the property for david called id</span></span>
users<span style="color: #990000">(:</span>david<span style="color: #990000">).</span>id
</tt></pre></div></div>
-<div class="para"><p>But, by there's another side to fixtures… at night, if the moon is full and the wind completely still, fixtures can also transform themselves into the form of the original class!</p></div>
-<div class="para"><p>Now you can get at the methods only available to that class.</p></div>
+<div class="para"><p>Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -530,22 +472,28 @@ david <span style="color: #990000">=</span> users<span style="color: #990000">(: email<span style="color: #990000">(</span>david<span style="color: #990000">.</span>girlfriend<span style="color: #990000">.</span>email<span style="color: #990000">,</span> david<span style="color: #990000">.</span>location_tonight<span style="color: #990000">)</span>
</tt></pre></div></div>
</div>
-<h2 id="_unit_testing_your_models">3. Unit Testing Your Models</h2>
+<h2 id="_unit_testing_your_models">3. Unit Testing your Models</h2>
<div class="sectionbody">
<div class="para"><p>In Rails, unit tests are what you write to test your models.</p></div>
-<div class="para"><p>When you create a model using <tt>script/generate</tt>, among other things it creates a test stub in the <tt>test/unit</tt> folder, as well as a fixture for the model:</p></div>
+<div class="para"><p>For this guide we will be using Rails <em>scaffolding</em>. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practises. I will be using examples from this generated code and would be supplementing it with additional examples where necessary.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">For more information on Rails <em>scaffolding</em>, refer to <a href="../getting_started_with_rails.html">Getting Started with Rails</a></td>
+</tr></table>
+</div>
+<div class="para"><p>When you use <tt>script/generate scaffold</tt>, for a resource among other things it creates a test stub in the <tt>test/unit</tt> folder:</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 model Post
+<div class="content">
+<pre><tt>$ script/generate scaffold post title:string body:text
...
create app/models/post.rb
create test/unit/post_test.rb
create test/fixtures/posts.yml
-...
-</tt></pre></div></div>
+...</tt></pre>
+</div></div>
<div class="para"><p>The default test stub in <tt>test/unit/post_test.rb</tt> looks like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -617,7 +565,46 @@ is the user's password greater than 5 characters? </li>
</ul></div>
<div class="para"><p>Every test contains one or more assertions. Only when all the assertions are successful the test passes.</p></div>
-<h3 id="_running_tests">3.1. Running Tests</h3>
+<h3 id="_preparing_you_application_for_testing">3.1. Preparing you Application for Testing</h3>
+<div class="para"><p>Before you can run your tests you need to ensure that the test database structure is current. For this you can use the following rake commands:</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>$ rake db<span style="color: #990000">:</span>migrate
+<span style="color: #990000">...</span>
+$ rake db<span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">test</span></span><span style="color: #990000">:</span>load
+</tt></pre></div></div>
+<div class="para"><p>Above <tt>rake db:migrate</tt> runs any pending migrations on the <em>developemnt</em> environment and updates <tt>db/schema.rb</tt>. <tt>rake db:test:load</tt> recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run <tt>db:test:prepare</tt> as it first checks for pending migrations and warns you appropriately.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content"><tt>db:test:prepare</tt> will fail with an error if db/schema.rb doesn't exists.</td>
+</tr></table>
+</div>
+<h4 id="_rake_tasks_for_preparing_you_application_for_testing">3.1.1. Rake Tasks for Preparing you Application for Testing ==</h4>
+<div class="para"><p>--------------------------------`----------------------------------------------------
+Tasks Description</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>+rake db:test:clone+ Recreate the test database from the current environment's database schema
++rake db:test:clone_structure+ Recreate the test databases from the development structure
++rake db:test:load+ Recreate the test database from the current +schema.rb+
++rake db:test:prepare+ Check for pending migrations and load the test schema
++rake db:test:purge+ Empty the test database.</tt></pre>
+</div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">You can see all these rake tasks and their descriptions by running <tt>rake —tasks —describe</tt></td>
+</tr></table>
+</div>
+<h3 id="_running_tests">3.2. Running Tests</h3>
<div class="para"><p>Running a test is as simple as invoking the file containing the test cases through Ruby:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -637,10 +624,7 @@ Finished <span style="font-weight: bold"><span style="color: #0000FF">in</span>< <div class="para"><p>This will run all the test methods from the test case.</p></div>
<div class="para"><p>You can also run a particular test method from the test case by using the <tt>-n</tt> switch with the <tt>test method name</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 -->
+<div class="content">
<pre><tt>$ ruby unit/post_test.rb -n test_truth
Loaded suite unit/post_test
@@ -648,74 +632,98 @@ Started .
Finished in 0.023513 seconds.
-1 tests, 1 assertions, 0 failures, 0 errors
-</tt></pre></div></div>
+1 tests, 1 assertions, 0 failures, 0 errors</tt></pre>
+</div></div>
<div class="para"><p>The <tt>.</tt> (dot) above indicates a passing test. When a test fails you see an <tt>F</tt>; when a test throws an error you see an <tt>E</tt> in its place. The last line of the output is the summary.</p></div>
-<div class="para"><p>To see how a test failure is reported, you can add a failing test to the <tt>post_test.rb</tt> test case:</p></div>
+<div class="para"><p>To see how a test failure is reported, you can add a failing test to the <tt>post_test.rb</tt> test case.</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-weight: bold"><span style="color: #0000FF">def</span></span> test_should_have_atleast_one_post
- post <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>find<span style="color: #990000">(:</span>first<span style="color: #990000">)</span>
- assert_not_nil post
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_not_save_post_without_title
+ post <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>new
+ assert <span style="color: #990000">!</span>post<span style="color: #990000">.</span>save
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:</p></div>
+<div class="para"><p>Let us run this newly added test.</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>$ ruby unit/post_test.rb
+<div class="content">
+<pre><tt>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.027274 seconds.
+F
+Finished in 0.197094 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:12:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-<nil> expected to not be nil.
+<false> is not true.
-2 tests, 2 assertions, 1 failures, 0 errors
-</tt></pre></div></div>
+1 tests, 1 assertions, 1 failures, 0 errors</tt></pre>
+</div></div>
<div class="para"><p>In the output, <tt>F</tt> denotes a failure. You can see the corresponding trace shown under <tt>1)</tt> along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:</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-weight: bold"><span style="color: #0000FF">def</span></span> test_should_have_atleast_one_post
- post <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>find<span style="color: #990000">(:</span>first<span style="color: #990000">)</span>
- assert_not_nil post<span style="color: #990000">,</span> <span style="color: #FF0000">"Should not be nil as Posts table should have atleast one post"</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_not_save_post_without_title
+ post <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>new
+ assert <span style="color: #990000">!</span>post<span style="color: #990000">.</span>save<span style="color: #990000">,</span> <span style="color: #FF0000">"Saved the post without a title"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Running this test shows the friendlier assertion message:</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>$ ruby unit/post_test.rb
+<div class="content">
+<pre><tt>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.024727 seconds.
+F
+Finished in 0.198093 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
-<nil> expected to not be nil.
+Saved the post without a title.
+<false> is not true.
-2 tests, 2 assertions, 1 failures, 0 errors
+1 tests, 1 assertions, 1 failures, 0 errors</tt></pre>
+</div></div>
+<div class="para"><p>Now to get this test to pass we can add a model level validation for the <em>title</em> field.</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-weight: bold"><span style="color: #0000FF">class</span></span> Post <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>title
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p>Now the test should pass. Let us verify by running the test again:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
+Loaded suite unit/post_test
+Started
+.
+Finished in 0.193608 seconds.
+
+1 tests, 1 assertions, 0 failures, 0 errors</tt></pre>
+</div></div>
+<div class="para"><p>Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as <em>Test-Driven Development</em> (TDD).</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">Many Rails developers practice <em>Test-Driven Development</em> (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with <a href="http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html">15 TDD steps to create a Rails application</a>.</td>
+</tr></table>
+</div>
<div class="para"><p>To see how an error gets reported, here's a test containing an error:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -730,34 +738,23 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>Now you can see even more output in the console from running the 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>$ ruby unit/post_test.rb
+<div class="content">
+<pre><tt>$ ruby unit/post_test.rb -n test_should_report_error
Loaded suite unit/post_test
Started
-FE.
-Finished in 0.108389 seconds.
-
- 1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
-<nil> expected to not be nil.
+E
+Finished in 0.195757 seconds.
- 2) Error:
+ 1) Error:
test_should_report_error(PostTest):
-NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x304a7b0>
+NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x2cc9de8>
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
- unit/post_test.rb:15:in `test_should_report_error'
+ unit/post_test.rb:16:in `test_should_report_error'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
-3 tests, 2 assertions, 1 failures, 1 errors
-</tt></pre></div></div>
+1 tests, 0 assertions, 0 failures, 1 errors</tt></pre>
+</div></div>
<div class="para"><p>Notice the <em>E</em> in the output. It denotes a test with error.</p></div>
<div class="admonitionblock">
<table><tr>
@@ -767,17 +764,9 @@ NameError: undefined local variable or method `some_undefined_variable' for #< <td class="content">The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.</td>
</tr></table>
</div>
-<h3 id="_what_to_include_in_your_unit_tests">3.2. What to Include in Your Unit Tests</h3>
+<h3 id="_what_to_include_in_your_unit_tests">3.3. What to Include in Your Unit Tests</h3>
<div class="para"><p>Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.</p></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/tip.png" alt="Tip" />
-</td>
-<td class="content">Many Rails developers practice <em>test-driven development</em> (TDD), in which the tests are written <em>before</em> the code that they are testing. This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with <a href="http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html">15 TDD steps to create a Rails application</a>.</td>
-</tr></table>
-</div>
-<h3 id="_assertions_available">3.3. Assertions Available</h3>
+<h3 id="_assertions_available">3.4. Assertions Available</h3>
<div class="para"><p>By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.</p></div>
<div class="para"><p>There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with <tt>test/unit</tt>, the testing library used by Rails. The <tt>[msg]</tt> parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.</p></div>
<div class="tableblock">
@@ -961,7 +950,7 @@ cellspacing="0" cellpadding="4"> <td class="content">Creating your own assertions is an advanced topic that we won't cover in this tutorial.</td>
</tr></table>
</div>
-<h3 id="_rails_specific_assertions">3.4. Rails Specific Assertions</h3>
+<h3 id="_rails_specific_assertions">3.5. Rails Specific Assertions</h3>
<div class="para"><p>Rails adds some custom assertions of its own to the <tt>test/unit</tt> framework:</p></div>
<div class="tableblock">
<table rules="all"
@@ -1081,34 +1070,8 @@ was the appropriate message displayed to the user in the view </p>
</li>
</ul></div>
-<div class="para"><p>When you use <tt>script/generate</tt> to create a controller, it automatically creates a functional test for that controller in <tt>test/functional</tt>. For example, if you create a post controller:</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 controller post
-<span style="color: #990000">...</span>
- create app/controllers/post_controller<span style="color: #990000">.</span>rb
- create test/functional/post_controller_test<span style="color: #990000">.</span>rb
-<span style="color: #990000">...</span>
-</tt></pre></div></div>
-<div class="para"><p>Now if you take a look at the file <tt>posts_controller_test.rb</tt> in the <tt>test/functional</tt> directory, you should see:</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-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test_helper'</span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PostsControllerTest <span style="color: #990000"><</span> ActionController<span style="color: #990000">::</span>TestCase
- <span style="font-style: italic"><span style="color: #9A1900"># Replace this with your real tests.</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_truth
- assert <span style="font-weight: bold"><span style="color: #0000FF">true</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="para"><p>Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:</p></div>
+<div class="para"><p>Now that we have used Rails scaffold generator for our <tt>Post</tt> resource, it has already created the controller code and functional tests. You can take look at the file <tt>posts_controller_test.rb</tt> in the <tt>test/functional</tt> directory.</p></div>
+<div class="para"><p>Let me take you through one such test, <tt>test_should_get_index</tt> from the file <tt>posts_controller_test.rb</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1160,7 +1123,30 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt>get<span style="color: #990000">(:</span>view<span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #FF0000">'id'</span> <span style="color: #990000">=></span> <span style="color: #FF0000">'12'</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #FF0000">'message'</span> <span style="color: #990000">=></span> <span style="color: #FF0000">'booya!'</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
-<h3 id="_available_request_types_for_functional_tests">4.2. Available Request Types for Functional Tests===</h3>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">If you try running <tt>test_should_create_post</tt> test from <tt>posts_controller_test.rb</tt> it will fail on account of the newly added model level validation and rightly so.</td>
+</tr></table>
+</div>
+<div class="para"><p>Let us modify <tt>test_should_create_post</tt> test in <tt>posts_controller_test.rb</tt> so that all our test pass:</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-weight: bold"><span style="color: #0000FF">def</span></span> test_should_create_post
+ assert_difference<span style="color: #990000">(</span><span style="color: #FF0000">'Post.count'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ post <span style="color: #990000">:</span>create<span style="color: #990000">,</span> <span style="color: #990000">:</span>post <span style="color: #990000">=></span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>title <span style="color: #990000">=></span> <span style="color: #FF0000">'Some title'</span><span style="color: #FF0000">}</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ assert_redirected_to post_path<span style="color: #990000">(</span>assigns<span style="color: #990000">(:</span>post<span style="color: #990000">))</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Now you can try running all the tests and they should pass.</p></div>
+<h3 id="_available_request_types_for_functional_tests">4.2. Available Request Types for Functional Tests</h3>
<div class="para"><p>If you're familiar with the HTTP protocol, you'll know that <tt>get</tt> is a type of request. There are 5 request types supported in Rails functional tests:</p></div>
<div class="ilist"><ul>
<li>
@@ -1582,10 +1568,159 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_testing_your_mailers">6. Testing Your Mailers</h2>
+<h2 id="_rake_tasks_for_running_your_tests">6. Rake Tasks for Running your Tests</h2>
+<div class="sectionbody">
+<div class="para"><p>You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.</p></div>
+<div class="para"><p>--------------------------------`----------------------------------------------------
+Tasks Description</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
++rake test:units+ Runs all the unit tests from +test/unit+
++rake test:functionals+ Runs all the functional tests from +test/functional+
++rake test:integration+ Runs all the integration tests from +test/integration+
++rake test:recent+ Tests recent changes
++rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
++rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)</tt></pre>
+</div></div>
+</div>
+<h2 id="_brief_note_about_test_unit">7. Brief Note About Test::Unit</h2>
+<div class="sectionbody">
+<div class="para"><p>Ruby ships with a boat load of libraries. One little gem of a library is <tt>Test::Unit</tt>, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in <tt>Test::Unit::Assertions</tt>. The class <tt>ActiveSupport::TestCase</tt> which we have been using in our unit and functional tests extends <tt>Test::Unit::TestCase</tt> that it is how we can use all the basic assertions in our tests.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">For more information on <tt>Test::Unit</tt>, refer to <a href="http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/">test/unit Documentation</a></td>
+</tr></table>
+</div>
+</div>
+<h2 id="_setup_and_teardown">8. Setup and Teardown</h2>
+<div class="sectionbody">
+<div class="para"><p>If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in <tt>Posts</tt> controller:</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-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test_helper'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PostsControllerTest <span style="color: #990000"><</span> ActionController<span style="color: #990000">::</span>TestCase
+
+ <span style="font-style: italic"><span style="color: #9A1900"># called before every single test</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
+ <span style="color: #009900">@post</span> <span style="color: #990000">=</span> posts<span style="color: #990000">(:</span>one<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-style: italic"><span style="color: #9A1900"># called after every single test</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
+ <span style="font-style: italic"><span style="color: #9A1900"># as we are re-initializing @post before every test</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># setting it to nil here is not essential but I hope</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># you understand how you can use the teardown method</span></span>
+ <span style="color: #009900">@post</span> <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_show_post
+ get <span style="color: #990000">:</span>show<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=></span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>id
+ assert_response <span style="color: #990000">:</span>success
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_destroy_post
+ assert_difference<span style="color: #990000">(</span><span style="color: #FF0000">'Post.count'</span><span style="color: #990000">,</span> <span style="color: #990000">-</span><span style="color: #993399">1</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ delete <span style="color: #990000">:</span>destroy<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=></span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>id
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ assert_redirected_to posts_path
+ <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="para"><p>Above, the <tt>setup</tt> method is called before each test and so <tt>@post</tt> is available for each of the tests. Rails implements <tt>setup</tt> and <tt>teardown</tt> as ActiveSupport::Callbacks. Which essentially means you need not only use <tt>setup</tt> and <tt>teardown</tt> as methods in your tests. You could specify them by using:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+a block
+</p>
+</li>
+<li>
+<p>
+a method (like in the earlier example)
+</p>
+</li>
+<li>
+<p>
+a method name as a symbol
+</p>
+</li>
+<li>
+<p>
+a lambda
+</p>
+</li>
+</ul></div>
+<div class="para"><p>Let's see the earlier example by specifying <tt>setup</tt> callback by specifying a method name as a symbol:</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-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'../test_helper'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PostsControllerTest <span style="color: #990000"><</span> ActionController<span style="color: #990000">::</span>TestCase
+
+ <span style="font-style: italic"><span style="color: #9A1900"># called before every single test</span></span>
+ setup <span style="color: #990000">:</span>initialize_post
+
+ <span style="font-style: italic"><span style="color: #9A1900"># called after every single test</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
+ <span style="color: #009900">@post</span> <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_show_post
+ get <span style="color: #990000">:</span>show<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=></span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>id
+ assert_response <span style="color: #990000">:</span>success
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_update_post
+ put <span style="color: #990000">:</span>update<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=></span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>id<span style="color: #990000">,</span> <span style="color: #990000">:</span>post <span style="color: #990000">=></span> <span style="color: #FF0000">{</span> <span style="color: #FF0000">}</span>
+ assert_redirected_to post_path<span style="color: #990000">(</span>assigns<span style="color: #990000">(:</span>post<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">def</span></span> test_should_destroy_post
+ assert_difference<span style="color: #990000">(</span><span style="color: #FF0000">'Post.count'</span><span style="color: #990000">,</span> <span style="color: #990000">-</span><span style="color: #993399">1</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ delete <span style="color: #990000">:</span>destroy<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=></span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>id
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ assert_redirected_to posts_path
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ private
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> initialize_post
+ <span style="color: #009900">@post</span> <span style="color: #990000">=</span> posts<span style="color: #990000">(:</span>one<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>
+</tt></pre></div></div>
+</div>
+<h2 id="_testing_routes">9. Testing Routes</h2>
+<div class="sectionbody">
+<div class="para"><p>Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default <tt>show</tt> action of <tt>Posts</tt> controller above should look like:</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-weight: bold"><span style="color: #0000FF">def</span></span> test_should_route_to_post
+ assert_routing <span style="color: #FF0000">'/posts/1'</span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">"posts"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">"show"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=></span> <span style="color: #FF0000">"1"</span> <span style="color: #FF0000">}</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_testing_your_mailers">10. Testing Your Mailers</h2>
<div class="sectionbody">
<div class="para"><p>Testing mailer classes requires some specific tools to do a thorough job.</p></div>
-<h3 id="_keeping_the_postman_in_check">6.1. Keeping the Postman in Check</h3>
+<h3 id="_keeping_the_postman_in_check">10.1. Keeping the Postman in Check</h3>
<div class="para"><p>Your <tt>ActionMailer</tt> classes — like every other part of your Rails application — should be tested to ensure that it is working as expected.</p></div>
<div class="para"><p>The goals of testing your <tt>ActionMailer</tt> classes are to ensure that:</p></div>
<div class="ilist"><ul>
@@ -1605,14 +1740,14 @@ the right emails are being sent at the right times </p>
</li>
</ul></div>
-<h4 id="_from_all_sides">6.1.1. From All Sides</h4>
+<h4 id="_from_all_sides">10.1.1. From All Sides</h4>
<div class="para"><p>There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture — yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.</p></div>
-<h3 id="_unit_testing">6.2. Unit Testing</h3>
+<h3 id="_unit_testing">10.2. Unit Testing</h3>
<div class="para"><p>In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.</p></div>
-<h4 id="_revenge_of_the_fixtures">6.2.1. Revenge of the Fixtures</h4>
+<h4 id="_revenge_of_the_fixtures">10.2.1. Revenge of the Fixtures</h4>
<div class="para"><p>For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output <em>should</em> look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within <tt>test/fixtures</tt> directly corresponds to the name of the mailer. So, for a mailer named <tt>UserMailer</tt>, the fixtures should reside in <tt>test/fixtures/user_mailer</tt> directory.</p></div>
<div class="para"><p>When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.</p></div>
-<h4 id="_the_basic_test_case">6.2.2. The Basic Test case</h4>
+<h4 id="_the_basic_test_case">10.2.2. The Basic Test case</h4>
<div class="para"><p>Here's a unit test to test a mailer named <tt>UserMailer</tt> whose action <tt>invite</tt> is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an <tt>invite</tt> action.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1638,19 +1773,16 @@ http://www.gnu.org/software/src-highlite --> <div class="para"><p>In this test, <tt>@expected</tt> is an instance of <tt>TMail::Mail</tt> that you can use in your tests. It is defined in <tt>ActionMailer::TestCase</tt>. The test above uses <tt>@expected</tt> to construct an email, which it then asserts with email created by the custom mailer. The <tt>invite</tt> fixture is the body of the email and is used as the sample content to assert against. The helper <tt>read_fixture</tt> is used to read in the content from this file.</p></div>
<div class="para"><p>Here's the content of the <tt>invite</tt> fixture:</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 -->
+<div class="content">
<pre><tt>Hi friend@example.com,
You have been invited.
-Cheers!
-</tt></pre></div></div>
+Cheers!</tt></pre>
+</div></div>
<div class="para"><p>This is the right time to understand a little more about writing tests for your mailers. The line <tt>ActionMailer::Base.delivery_method = :test</tt> in <tt>config/environments/test.rb</tt> sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (<tt>ActionMailer::Base.deliveries</tt>).</p></div>
<div class="para"><p>However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be.</p></div>
-<h3 id="_functional_testing">6.3. Functional Testing</h3>
+<h3 id="_functional_testing">10.3. Functional Testing</h3>
<div class="para"><p>Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job You are probably more interested in is whether your own business logic is sending emails when you expect them to got out. For example, you can check that the invite friend operation is sending an email appropriately:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1673,36 +1805,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_rake_tasks_for_testing">7. Rake Tasks for Testing</h2>
-<div class="sectionbody">
-<div class="para"><p>You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.</p></div>
-<div class="para"><p>--------------------------------`----------------------------------------------------
-Tasks Description</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
-+rake test:units+ Runs all the unit tests from +test/unit+
-+rake test:functionals+ Runs all the functional tests from +test/functional+
-+rake test:integration+ Runs all the integration tests from +test/integration+
-+rake test:recent+ Tests recent changes
-+rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
-+rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
-+rake db:test:clone+ Recreate the test database from the current environment's database schema
-+rake db:test:clone_structure+ Recreate the test databases from the development structure
-+rake db:test:load+ Recreate the test database from the current +schema.rb+
-+rake db:test:prepare+ Check for pending migrations and load the test schema
-+rake db:test:purge+ Empty the test database.</tt></pre>
-</div></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/tip.png" alt="Tip" />
-</td>
-<td class="content">You can see all these rake task and their descriptions by running <tt>rake —tasks —describe</tt></td>
-</tr></table>
-</div>
-</div>
-<h2 id="_other_testing_approaches">8. Other Testing Approaches</h2>
+<h2 id="_other_testing_approaches">11. Other Testing Approaches</h2>
<div class="sectionbody">
<div class="para"><p>The built-in <tt>test/unit</tt> based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:</p></div>
<div class="ilist"><ul>
@@ -1728,18 +1831,23 @@ link: <a href="http://rspec.info/">RSpec</a>, a behavior-driven development fram </li>
</ul></div>
</div>
-<h2 id="_changelog">9. Changelog</h2>
+<h2 id="_changelog">12. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
<li>
<p>
+November 13, 2008: Revised based on feedback from Pratik Naik by <a href="../authors.html#asurve">Akshay Surve</a> (not yet approved for publication)
+</p>
+</li>
+<li>
+<p>
October 14, 2008: Edit and formatting pass by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> (not yet approved for publication)
</p>
</li>
<li>
<p>
-October 12, 2008: First draft by <a href="../authors.html#asurve">Akashay Surve</a> (not yet approved for publication)
+October 12, 2008: First draft by <a href="../authors.html#asurve">Akshay Surve</a> (not yet approved for publication)
</p>
</li>
</ul></div>
|