Merge docrails.

This commit is contained in:
Pratik Naik
2008-11-14 17:47:21 +05:30
parent 549b18c928
commit c70b993a9e
50 changed files with 4430 additions and 2555 deletions

View File

@@ -1029,10 +1029,10 @@ module ActionController #:nodoc:
#
# * <tt>Hash</tt> - The URL will be generated by calling url_for with the +options+.
# * <tt>Record</tt> - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record.
# * <tt>String starting with protocol:// (like http://)</tt> - Is passed straight through as the target for redirection.
# * <tt>String not containing a protocol</tt> - The current protocol and host is prepended to the string.
# * <tt>String</tt> starting with <tt>protocol://</tt> (like <tt>http://</tt>) - Is passed straight through as the target for redirection.
# * <tt>String</tt> not containing a protocol - The current protocol and host is prepended to the string.
# * <tt>:back</tt> - Back to the page that issued the request. Useful for forms that are triggered from multiple places.
# Short-hand for redirect_to(request.env["HTTP_REFERER"])
# Short-hand for <tt>redirect_to(request.env["HTTP_REFERER"])</tt>
#
# Examples:
# redirect_to :action => "show", :id => 5

View File

@@ -1,2 +1,5 @@
Use this README file to introduce your application and point to useful places in the API for learning more.
Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
To build the guides:
* Install source-highlighter (http://www.gnu.org/software/src-highlite/source-highlight.html)
* Install the mizuho gem (http://github.com/FooBarWidget/mizuho/tree/master)
* Run `rake guides` from the railties directory

View File

@@ -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>
@@ -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 &#8658;
</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">=&gt;</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">=&gt;</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>

View File

@@ -349,7 +349,7 @@ Deal with exceptions that may be raised during request processing
</div>
<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 ApplicationController 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 Rails creates an instance of that controller and runs the method corresponding to the action (the method with the same name as the action).</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
@@ -361,7 +361,7 @@ http://www.gnu.org/software/src-highlite -->
<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>
@@ -373,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, Rails will create a ClientsController instance will be created 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="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
@@ -431,6 +431,14 @@ http://www.gnu.org/software/src-highlite -->
<div class="content">
<pre><tt>GET /clients?ids[]=1&amp;ids[]=2&amp;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&amp;ids%5b%5d=2&amp;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">
@@ -442,7 +450,8 @@ http://www.gnu.org/software/src-highlite -->
&lt;input type="text" name="client[address][city]" value="Carrot City" /&gt;
&lt;/form&gt;</tt></pre>
</div></div>
<div class="para"><p>The value of <tt>params[:client]</tt> when this form is submitted will be <tt>{:name &#8658; "Acme", :phone &#8658; "12345", :address &#8658; {:postcode &#8658; "12345", :city &#8658; "Carrot City"}}</tt>. Note the nested hash in <tt>params[:client][:address]</tt>.</p></div>
<div class="para"><p>The value of <tt>params[:client]</tt> when this form is submitted will be <tt>{"name" &#8658; "Acme", "phone" &#8658; "12345", "address" &#8658; {"postcode" &#8658; "12345", "city" &#8658; "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">
@@ -461,18 +470,18 @@ map<span style="color: #990000">.</span>connect <span style="color: #FF0000">"/c
<div class="content">
<pre><tt>class ApplicationController &lt; ActionController::Base
#The options parameter is the hash passed in to url_for
#The options parameter is the hash passed in to +url_for+
def default_url_options(options)
{:locale =&gt; 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 url_for. 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 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>
@@ -481,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>
@@ -495,8 +504,8 @@ ActiveRecordStore - Stores the data in a database using Active Record.
</p>
</li>
</ul></div>
<div class="para"><p>All session stores store either the session ID or the entire session in a cookie - Rails does not allow the session ID to be passed in any other way. 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 but not edit it. 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 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">
@@ -547,7 +556,7 @@ http://www.gnu.org/software/src-highlite -->
<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>
@@ -623,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>&lt;html&gt;
@@ -916,7 +925,7 @@ http://www.gnu.org/software/src-highlite -->
<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 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:</p></div>
<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>
@@ -1030,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">&lt;</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
@@ -1038,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">&amp;&amp;</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">&amp;&amp;</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>
@@ -1095,7 +1104,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 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">

View File

@@ -199,10 +199,72 @@ ul#navMain {
<h2>Chapters</h2>
<ol>
<li>
<a href="#_active_record_validations">Active Record Validations</a>
<a href="#_motivations_to_validate_your_active_record_objects">Motivations to validate your Active Record objects</a>
</li>
<li>
<a href="#_credits">Credits</a>
<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>
@@ -250,13 +312,433 @@ Create Observers - classes with callback methods specific for each of your model
</ul></div>
</div>
</div>
<h2 id="_active_record_validations">1. Active Record Validations</h2>
<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="_credits">2. Credits</h2>
<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">&lt;</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>&gt;&gt; p = Person.new(:name =&gt; "John Doe", :birthdate =&gt; Date.parse("09/03/1979"))
=&gt; #&lt;Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil&gt;
&gt;&gt; p.new_record?
=&gt; true
&gt;&gt; p.save
=&gt; true
&gt;&gt; p.new_record?
=&gt; 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="_changelog">3. Changelog</h2>
<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">&lt;</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">&lt;</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">=&gt;</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">&lt;</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">&lt;</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>&lt;%= text_field :person, :email %&gt;
&lt;%= text_field :person, :email_confirmation %&gt;</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">&lt;</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">&lt;</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">&lt;</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">=&gt;</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">=&gt;</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">&lt;</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">=&gt;</span> <span style="color: #FF6600">/^[a-zA-Z]+$/</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</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">&lt;</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">=&gt;</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">=&gt;</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">&lt;</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">=&gt;</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">=&gt;</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">=&gt;</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">=&gt;</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">&lt;</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">=&gt;</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">&lt;</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">=&gt;</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">&lt;</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">&lt;</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 &#8658; [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # &#8658; 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">&lt;</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">&lt;</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">=&gt;</span> <span style="color: #990000">:</span>year<span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</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">&lt;</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">=&gt;</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">&lt;</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">=&gt;</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">=&gt;</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">=&gt;</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>&gt;</span> :create</tt> to run the validation only when a new record is created or <tt>:on =<span>&gt;</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">&lt;</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">=&gt;</span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900"># =&gt; 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">=&gt;</span> <span style="color: #990000">:</span>update <span style="font-style: italic"><span style="color: #9A1900"># =&gt; 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">=&gt;</span> <span style="color: #990000">:</span>save <span style="font-style: italic"><span style="color: #9A1900"># =&gt; 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">&lt;</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">=&gt;</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">&lt;</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">=&gt;</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">&lt;</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">=&gt;</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">&lt;</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">&lt;</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">&lt;</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">&lt;</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">&lt;=</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>

View File

@@ -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">&lt;</span> ActionController
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</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">&lt;</span> ActionController
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</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">&lt;</span> ActionController
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</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">=&gt;</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 &#8658; 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">&lt;</span> ActionController
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</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">=&gt;</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">=&gt;</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">&lt;</span> ActionController
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</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">=&gt;</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">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>

View File

@@ -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>&#8230; 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">=&gt;</span> Booting WEBrick<span style="color: #990000">...</span>
<span style="color: #990000">=&gt;</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">=&gt;</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 &#8212; 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>&#8212;help</tt> or <tt>-h</tt> to the end, as in <tt>./script/server &#8212;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>

View File

@@ -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 &lt;&lt; <em>&#8212;line-numbers</em> &lt;&lt; <em>&#8212;inline-source</em> &lt;&lt; <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 &#8658; 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 &lt;&lt; <em>&#8212;line-numbers</em> &lt;&lt; <em>&#8212;inline-source</em> &lt;&lt; <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 &#8658; false
11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer &#8658; false</p></div>
<div class="para"><p>activerecord/lib/active_record/base.rb
394: cattr_accessor :logger, :instance_writer &#8658; false
443: cattr_accessor :configurations, :instance_writer &#8658; false
450: cattr_accessor :primary_key_prefix_type, :instance_writer &#8658; false
456: cattr_accessor :table_name_prefix, :instance_writer &#8658; false
461: cattr_accessor :table_name_suffix, :instance_writer &#8658; false
467: cattr_accessor :pluralize_table_names, :instance_writer &#8658; false
473: cattr_accessor :colorize_logging, :instance_writer &#8658; false
478: cattr_accessor :default_timezone, :instance_writer &#8658; false
487: cattr_accessor :schema_format , :instance_writer &#8658; false
491: cattr_accessor :timestamped_migrations , :instance_writer &#8658; false</p></div>
<div class="para"><p>activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
11: cattr_accessor :connection_handler, :instance_writer &#8658; 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 &#8658; 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 &#8658; false</p></div>
<div class="para"><p>activerecord/Rakefile
142: rdoc.options &lt;&lt; <em>&#8212;line-numbers</em> &lt;&lt; <em>&#8212;inline-source</em> &lt;&lt; <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 &lt;&lt; <em>&#8212;line-numbers</em> &lt;&lt; <em>&#8212;inline-source</em> &lt;&lt; <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 &#8658; false</p></div>
<div class="para"><p>activesupport/test/core_ext/module/synchronization_test.rb
6: @target.cattr_accessor :mutex, :instance_writer &#8658; false</p></div>
<div class="para"><p>railties/doc/guides/html/creating_plugins.html
786: cattr_accessor &lt;span style="color: #990000"&gt;:&lt;/span&gt;yaffle_text_field&lt;span style="color: #990000"&gt;,&lt;/span&gt; &lt;span style="color: #990000"&gt;:&lt;/span&gt;yaffle_date_field
860: cattr_accessor &lt;span style="color: #990000"&gt;:&lt;/span&gt;yaffle_text_field&lt;span style="color: #990000"&gt;,&lt;/span&gt; &lt;span style="color: #990000"&gt;:&lt;/span&gt;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 &lt;&lt; <em>&#8212;line-numbers</em> &lt;&lt; <em>&#8212;inline-source</em> &lt;&lt; <em>&#8212;accessor</em> &lt;&lt; <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 &lt;&lt; <em>-A cattr_accessor=object</em></p></div>
</div>
</div>
</div>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -939,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>
@@ -1062,7 +1062,7 @@ http://www.gnu.org/software/src-highlite -->
<div class="ilist"><ul>
<li>
<p>
<a href="http://github.com/drnic/rails-footnotes/tree/master">Footnotes</a>: Every Rails page has footnotes that link give request information and link back to your source via TextMate.
<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>

View File

@@ -198,9 +198,6 @@ ul#navMain {
<div id="sidebar">
<h2>Chapters</h2>
<ol>
<li>
<a href="#_in_the_beginning_8230">In the beginning&#8230;</a>
</li>
<li>
<a href="#_the_sample_models">The Sample Models</a>
</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 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>
</div>
<h2 id="_in_the_beginning_8230">1. In the beginning&#8230;</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">
@@ -381,6 +416,14 @@ http://www.gnu.org/software/src-highlite -->
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"&gt;]</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">
@@ -423,15 +466,21 @@ http://www.gnu.org/software/src-highlite -->
<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 &#8658; "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 =&gt; ["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 =&gt; ["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 &#8658; "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 &#8658; ["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 &#8658; ["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
@@ -521,7 +570,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="color: #990000">[</span><span style="color: #FF0000">"created_at &gt;= ? AND created_at &lt;= ?"</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
@@ -533,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 &#8658; "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 &#8658; "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 &#8658; "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 &amp; Offset</h2>
<h2 id="_limit_amp_offset">7. Limit &amp; 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
@@ -575,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">
@@ -595,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
@@ -605,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">=&gt;</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
@@ -616,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">
@@ -630,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 &#8658; :address)</tt>. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all), :include &#8658; [: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 &#8658; :address)</tt>. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include &#8658; [: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
@@ -679,7 +728,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="color: #990000">[</span><span style="color: #FF0000">"orders.created_at &gt;= ? AND orders.created_at &lt;= ?"</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 &#8658; ["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>
@@ -704,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 &#8658; <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">
@@ -714,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
@@ -727,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
@@ -743,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">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>gender <span style="color: #990000">=&gt;</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
@@ -754,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">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>active <span style="color: #990000">=&gt;</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 &#8658; ["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 &#8658; ["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
@@ -771,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">=&gt;</span> <span style="color: #990000">[</span><span style="color: #FF0000">"age &gt; ?"</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
@@ -792,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
@@ -804,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
@@ -826,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
@@ -838,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">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>gender <span style="color: #990000">=&gt;</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">
@@ -849,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
@@ -869,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">=&gt;</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>
@@ -907,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
@@ -921,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
@@ -931,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
@@ -941,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
@@ -952,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: 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: 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 by Ryan Bigg
</p>
</li>
<li>

View File

@@ -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

View File

@@ -1305,6 +1305,14 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt>&lt;%= render :partial =&gt; "product", :collection =&gt; @products, :as =&gt; :item %&gt;
</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>

View File

@@ -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>

View File

@@ -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">=&gt;</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">=&gt;</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 ==&gt; magazines_photos_path(2)
/photos/3 ==&gt; 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 ==&gt; publisher_magazine_photo_path(1,2,3)
/magazines/2/photos/3 ==&gt; magazine_photo_path(2,3)
/photos/3 ==&gt; 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

View File

@@ -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>
@@ -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,78 +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 &amp; 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">
<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
@@ -461,16 +407,16 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #FF0000">&lt;% earth_size = 20 -%&gt;</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">&lt;%= earth_size / 50 %&gt;</span>
brightest_on<span style="color: #990000">:</span> <span style="color: #FF0000">&lt;%= 113.days.ago.to_s(:db) %&gt;</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">&lt;%= earth_size / 2 %&gt;</span>
brightest_on<span style="color: #990000">:</span> <span style="color: #FF0000">&lt;%= 67.days.ago.to_s(:db) %&gt;</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">&lt;%= earth_size - 69 %&gt;</span>
brightest_on<span style="color: #990000">:</span> <span style="color: #FF0000">&lt;%= 13.days.from_now.to_s(:db) %&gt;</span>
</tt></pre></div></div>
<div class="para"><p>Anything encased within the</p></div>
<div class="listingblock">
@@ -480,8 +426,8 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #FF0000">&lt;% %&gt;</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>
@@ -500,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
@@ -513,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&#8230; 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
@@ -527,13 +472,22 @@ 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">
<pre><tt>$ script/generate model Post
<pre><tt>$ script/generate scaffold post title:string body:text
...
create app/models/post.rb
create test/unit/post_test.rb
@@ -611,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 &#8212;tasks &#8212;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
@@ -642,34 +635,34 @@ Finished in 0.023513 seconds.
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">
<pre><tt>$ ruby unit/post_test.rb
<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']:
&lt;nil&gt; expected to not be nil.
&lt;false&gt; is not true.
2 tests, 2 assertions, 1 failures, 0 errors</tt></pre>
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">
@@ -677,30 +670,60 @@ test_should_have_atleast_one_post(PostTest)
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">
<pre><tt>$ ruby unit/post_test.rb
<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.
&lt;nil&gt; expected to not be nil.
Saved the post without a title.
&lt;false&gt; is not true.
2 tests, 2 assertions, 1 failures, 0 errors</tt></pre>
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">&lt;</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
@@ -716,29 +739,21 @@ http://www.gnu.org/software/src-highlite -->
<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">
<pre><tt>$ ruby unit/post_test.rb
<pre><tt>$ ruby unit/post_test.rb -n test_should_report_error
Loaded suite unit/post_test
Started
FE.
Finished in 0.108389 seconds.
E
Finished in 0.195757 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.
&lt;nil&gt; expected to not be nil.
2) Error:
1) Error:
test_should_report_error(PostTest):
NameError: undefined local variable or method `some_undefined_variable' for #&lt;PostTest:0x304a7b0&gt;
NameError: undefined local variable or method `some_undefined_variable' for #&lt;PostTest:0x2cc9de8&gt;
/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>
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">
@@ -749,17 +764,9 @@ NameError: undefined local variable or method `some_undefined_variable' for #&lt
<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">
@@ -943,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"
@@ -1063,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">&lt;</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
@@ -1142,6 +1123,29 @@ 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">=&gt;</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">=&gt;</span> <span style="color: #FF0000">'booya!'</span><span style="color: #FF0000">}</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">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">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>title <span style="color: #990000">=&gt;</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>
@@ -1564,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">&lt;</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">=&gt;</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">=&gt;</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">&lt;</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">=&gt;</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">=&gt;</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">=&gt;</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">=&gt;</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">=&gt;</span> <span style="color: #FF0000">"posts"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"show"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=&gt;</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 &#8212; like every other part of your Rails application &#8212; 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>
@@ -1587,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 &#8212; 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
@@ -1629,7 +1782,7 @@ 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
@@ -1652,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 &#8212;tasks &#8212;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>
@@ -1707,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>

View File

@@ -118,11 +118,12 @@ There are two big additions to talk about here: transactional migrations and poo
=== Transactional Migrations
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 +rake db:migrate:redo+ 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 only*. The code is extensible to other database types in the future.
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 +rake db:migrate:redo+ 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.
* Lead Contributor: link:http://adam.blog.heroku.com/[Adam Wiggins]
* More information:
- link:http://adam.blog.heroku.com/past/2008/9/3/ddl_transactions/[DDL Transactions]
- link:http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/[A major milestone for DB2 on Rails]
=== Connection Pooling
@@ -208,11 +209,11 @@ Active Record association proxies now respect the scope of methods on the proxie
== Action Controller
On the controller side, there are a couple of changes that will help tidy up your routes.
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.
=== Shallow Route Nesting
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 _can_ supply more information.
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.
[source, ruby]
-------------------------------------------------------
@@ -249,7 +250,17 @@ map.resources :photos, :collection => { :search => [:get, :post] }
* Lead Contributor: link:http://brennandunn.com/[Brennan Dunn]
Action Controller now offers good support for HTTP conditional GET requests, as well as some other additions.
=== Resources With Specific Actions
By default, when you use +map.resources+ 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 +:only+ and +:except+ 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 +:all+ or +:none+ options. These options are inherited by nested resources.
[source, ruby]
-------------------------------------------------------
map.resources :photos, :only => [:index, :show]
map.resources :products, :except => :destroy
-------------------------------------------------------
* Lead Contributor: link:http://experthuman.com/[Tom Stuart]
=== Other Action Controller Changes

View File

@@ -6,7 +6,7 @@ Rails comes with built-in HTTP Basic authentication. This is an authentication s
-------------------------------------
class AdminController < ApplicationController
USERNAME, PASSWORD = "humbaba", "f59a4805511bf4bb61978445a5380c6c"
USERNAME, PASSWORD = "humbaba", "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
before_filter :authenticate
@@ -14,7 +14,7 @@ private
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == USERNAME && Digest::MD5.hexdigest(password) == PASSWORD
username == USERNAME && Digest::SHA1.hexdigest(password) == PASSWORD
end
end

View File

@@ -1,6 +1,6 @@
== Methods and Actions ==
A controller is a Ruby class which inherits from ApplicationController 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 Rails creates an instance of that controller and runs the method corresponding to the action (the method with the same name as the action).
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.
[source, ruby]
----------------------------------------------
@@ -10,7 +10,7 @@ class ClientsController < ApplicationController
def new
end
# These methods are responsible for producing output
# Action methods are responsible for producing output
def edit
end
@@ -23,9 +23,9 @@ private
end
----------------------------------------------
Private methods in a controller are also used as filters, which will be covered later in this guide.
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.
As an example, if the user goes to `/clients/new` in your application to add a new client, Rails will create a ClientsController instance will be created and run the `new` method. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client:
As an example, if a user goes to `/clients/new` in your application to add a new client, Rails will create an instance of ClientsController and run the `new` method. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client:
[source, ruby]
----------------------------------------------

View File

@@ -43,6 +43,8 @@ The params hash is not limited to one-dimensional keys and values. It can contai
GET /clients?ids[]=1&ids[]=2&ids[]=3
-------------------------------------
NOTE: 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.
The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
To send a hash you include the key name inside the brackets:
@@ -56,7 +58,9 @@ To send a hash you include the key name inside the brackets:
</form>
-------------------------------------
The value of `params[:client]` when this form is submitted will be `{:name => "Acme", :phone => "12345", :address => {:postcode => "12345", :city => "Carrot City"}}`. Note the nested hash in `params[:client][:address]`.
The value of `params[:client]` when this form is submitted will be `{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}`. Note the nested hash in `params[:client][:address]`.
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.
=== Routing Parameters ===
@@ -78,7 +82,7 @@ You can set global default parameters that will be used when generating URLs wit
------------------------------------
class ApplicationController < ActionController::Base
#The options parameter is the hash passed in to url_for
#The options parameter is the hash passed in to +url_for+
def default_url_options(options)
{:locale => I18n.locale}
end
@@ -86,4 +90,4 @@ class ApplicationController < ActionController::Base
end
------------------------------------
These options will be used as a starting-point when generating, so it's possible they'll be overridden by url_for. 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.
These options will be used as a starting-point when generating, so it's possible they'll be overridden by +url_for+. 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.

View File

@@ -4,7 +4,7 @@ In every controller there are two accessor methods pointing to the request and t
=== The +request+ Object ===
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 link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[API documentation]. Among the properties that you can access on this object:
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 link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[API documentation]. Among the properties that you can access on this object are:
* host - The hostname used for this request.
* domain - The hostname without the first segment (usually "www").

View File

@@ -1,15 +1,15 @@
== Session ==
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:
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:
* CookieStore - Stores everything on the client.
* DRBStore - Stores the data on a DRb client.
* MemCacheStore - Stores the data in MemCache.
* DRbStore - Stores the data on a DRb server.
* MemCacheStore - Stores the data in a memcache.
* ActiveRecordStore - Stores the data in a database using Active Record.
All session stores store either the session ID or the entire session in a cookie - Rails does not allow the session ID to be passed in any other way. Most stores also use this key to locate the session data on the server.
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).
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 but not edit it. 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 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.
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.
Read more about session storage in the link:../security.html[Security Guide].
@@ -56,7 +56,7 @@ end
In your controller you can access the session through the `session` instance method.
NOTE: There are two `session` 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.
NOTE: There are two `session` 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.
Session values are stored using key/value pairs like a hash:
@@ -129,7 +129,7 @@ class LoginsController < ApplicationController
end
------------------------------------------
The `destroy` action redirects to the application's `root_url`, 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:
The `destroy` action redirects to the application's `root_url`, 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:
------------------------------------------
<html>

View File

@@ -48,7 +48,7 @@ class ClientsController < ApplicationController
end
----------------------------
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 `stream` option or adjust the block size with the `buffer_size` option.
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 `:stream` option or adjust the block size with the `:buffer_size` option.
WARNING: 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.

View File

@@ -12,13 +12,392 @@ After reading this guide and trying out the presented concepts, we hope that you
* Create special classes that encapsulate common behaviour for your callbacks
* Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations.
== Active Record Validations
== Motivations to validate your Active Record objects
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.
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:
* 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.
* 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.
* 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.
== How it works
=== When does validation happens?
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 +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it'll be recorded to it's table. Active Record uses the +new_record?+ instance method to discover if an object is already in the database or not. Consider the following simple and very creative Active Record class:
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
end
------------------------------------------------------------------
We can see how it works by looking at the following script/console output:
------------------------------------------------------------------
>> 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
------------------------------------------------------------------
Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+, +update_attribute+ or +update_attributes+) 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.
=== The meaning of 'valid'
For verifying if an object is valid, Active Record uses the +valid?+ 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 +errors+ instance method. The proccess is really simple: If the +errors+ 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 +errors+ collection.
== The declarative validation helpers
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 +errors+ collection, this message being associated with the field being validated.
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.
All these helpers accept the +:on+ and +:message+ options, which define when the validation should be applied and what message should be added to the +errors+ collection when it fails, respectively. The +:on+ option takes one the values +:save+ (it's the default), +:create+ or +:update+. There is a default error message for each one of the validation helpers. These messages are used when the +:message+ option isn't used. Let's take a look at each one of the available helpers, listed in alphabetic order.
=== The +validates_acceptance_of+ helper
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 'acceptance' 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).
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_acceptance_of :terms_of_service
end
------------------------------------------------------------------
The default error message for +validates_acceptance_of+ is "_must be accepted_"
+validates_acceptance_of+ can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it.
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_acceptance_of :terms_of_service, :accept => 'yes'
end
------------------------------------------------------------------
=== The +validates_associated+ helper
== Credits
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, +valid?+ will be called upon each one of the associated objects.
[source, ruby]
------------------------------------------------------------------
class Library < ActiveRecord::Base
has_many :books
validates_associated :books
end
------------------------------------------------------------------
This validation will work with all the association types.
CAUTION: Pay attention not to use +validates_associated+ on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.
The default error message for +validates_associated+ is "_is invalid_". Note that the errors for each failed validation in the associated objects will be set there and not in this model.
=== The +validates_confirmation_of+ helper
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 '_confirmation' appended.
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_confirmation_of :email
end
------------------------------------------------------------------
In your view template you could use something like
------------------------------------------------------------------
<%= text_field :person, :email %>
<%= text_field :person, :email_confirmation %>
------------------------------------------------------------------
NOTE: This check is performed only if +email_confirmation+ 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 +validates_presence_of+ later on this guide):
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_confirmation_of :email
validates_presence_of :email_confirmation
end
------------------------------------------------------------------
The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_"
=== The +validates_each+ helper
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 +validates_each+ will be tested against it. In the following example, we don't want names and surnames to begin with lower case.
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_each :name, :surname do |model, attr, value|
model.errors.add(attr, 'Must start with upper case') if value =~ /^[a-z]/
end
end
------------------------------------------------------------------
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.
=== The +validates_exclusion_of+ helper
This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
[source, ruby]
------------------------------------------------------------------
class MovieFile < ActiveRecord::Base
validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed"
end
------------------------------------------------------------------
The +validates_exclusion_of+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask.
The default error message for +validates_exclusion_of+ is "_is not included in the list_".
=== The +validates_format_of+ helper
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 +:with+ option.
[source, ruby]
------------------------------------------------------------------
class Product < ActiveRecord::Base
validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed"
end
------------------------------------------------------------------
The default error message for +validates_format_of+ is "_is invalid_".
=== The +validates_inclusion_of+ helper
This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
[source, ruby]
------------------------------------------------------------------
class Coffee < ActiveRecord::Base
validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size"
end
------------------------------------------------------------------
The +validates_inclusion_of+ helper has an option +:in+ that receives the set of values that will be accepted. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask.
The default error message for +validates_inclusion_of+ is "_is not included in the list_".
=== The +validates_length_of+ helper
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.
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_length_of :name, :minimum => 2
validates_length_of :bio, :maximum => 500
validates_length_of :password, :in => 6..20
validates_length_of :registration_number, :is => 6
end
------------------------------------------------------------------
The possible length constraint options are:
* +:minimum+ - The attribute cannot have less than the specified length.
* +:maximum+ - The attribute cannot have more than the specified length.
* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
* +:is+ - The attribute length must be equal to a given value.
The default error messages depend on the type of length validation being performed. You can personalize these messages, using the +:wrong_length+, +:too_long+ and +:too_short+ options and the +%d+ format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the +:message+ option to specify an error message.
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_length_of :bio, :too_long => "you're writing too much. %d characters is the maximum allowed."
end
------------------------------------------------------------------
This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to.
=== The +validates_numericallity_of+ helper
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 +:integer_only+ option set to true, you can specify that only integral numbers are allowed.
If you use +:integer_only+ set to +true+, then it will use the +$$/\A[+\-]?\d+\Z/$$+ regular expression to validate the attribute's value. Otherwise, it will try to convert the value using +Kernel.Float+.
[source, ruby]
------------------------------------------------------------------
class Player < ActiveRecord::Base
validates_numericallity_of :points
validates_numericallity_of :games_played, :integer_only => true
end
------------------------------------------------------------------
The default error message for +validates_numericallity_of+ is "_is not a number_".
=== The +validates_presence_of+ helper
This helper validates that the attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty).
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_presence_of :name, :login, :email
end
------------------------------------------------------------------
NOTE: 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.
[source, ruby]
------------------------------------------------------------------
class LineItem < ActiveRecord::Base
belongs_to :order
validates_presence_of :order_id
end
------------------------------------------------------------------
NOTE: 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
The default error message for +validates_presence_of+ is "_can't be empty_".
=== The +validates_uniqueness_of+ helper
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.
[source, ruby]
------------------------------------------------------------------
class Account < ActiveRecord::Base
validates_uniqueness_of :email
end
------------------------------------------------------------------
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.
There is a +:scope+ option that you can use to specify other attributes that must be used to define uniqueness:
[source, ruby]
------------------------------------------------------------------
class Holiday < ActiveRecord::Base
validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year"
end
------------------------------------------------------------------
There is also a +:case_sensitive+ option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_uniqueness_of :name, :case_sensitive => false
end
------------------------------------------------------------------
The default error message for +validates_uniqueness_of+ is "_has already been taken_".
== Common validation options
There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which we'll cover right at the next topic.
=== The +:allow_nil+ option
You may use the +:allow_nil+ option everytime you just want to trigger a validation if the value being validated is not +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+.
[source, ruby]
------------------------------------------------------------------
class Coffee < ActiveRecord::Base
validates_inclusion_of :size, :in => %w(small medium large),
:message => "%s is not a valid size", :allow_nil => true
end
------------------------------------------------------------------
=== The +:message+ option
As stated before, the +:message+ option lets you specify the message that will be added to the +errors+ collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.
=== The +:on+ option
As stated before, the +:on+ 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 +:on =$$>$$ :create+ to run the validation only when a new record is created or +:on =$$>$$ :update+ to run the validation only when a record is updated.
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value
validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age'
validates_presence_of :name, :on => :save # => that's the default
end
------------------------------------------------------------------
== Conditional validation
Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a Ruby Proc. You may use the +:if+ option when you want to specify when the validation *should* happen. If you want to specify when the validation *should not* happen, then you may use the +:unless+ option.
=== Using a symbol with the +:if+ and +:unless+ options
You can associated the +:if+ and +:unless+ 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.
[source, ruby]
------------------------------------------------------------------
class Order < ActiveRecord::Base
validates_presence_of :card_number, :if => :paid_with_card?
def paid_with_card?
payment_type == "card"
end
end
------------------------------------------------------------------
=== Using a string with the +:if+ and +:unless+ options
You can also use a string that will be evaluated using +:eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_presence_of :surname, :if => "name.nil?"
end
------------------------------------------------------------------
=== Using a Proc object with the +:if+ and :+unless+ options
Finally, it's possible to associate +:if+ and +:unless+ 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.
[source, ruby]
------------------------------------------------------------------
class Account < ActiveRecord::Base
validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? }
end
------------------------------------------------------------------
== Writing your own validation methods
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 +validate+, +validate_on_create+ or +validate_on_update+ 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 +errors+ collection.
[source, ruby]
------------------------------------------------------------------
class Invoice < ActiveRecord::Base
def validate_on_create
errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
end
end
------------------------------------------------------------------
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 +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names.
[source, ruby]
------------------------------------------------------------------
class Invoice < ActiveRecord::Base
validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
def expiration_date_cannot_be_in_the_past
errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
end
def discount_cannot_be_greater_than_total_value
errors.add(:discount, "can't be greater than total value") unless discount <= total_value
end
end
------------------------------------------------------------------
== Changelog

View File

@@ -10,59 +10,65 @@ need to return to those hungry web clients in the shortest time possible.
This is an introduction to the three types of caching techniques that Rails
provides by default without the use of any third party plugins.
To get started make sure Base.perform_caching is set to true for your
environment.
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.
[source, ruby]
-----------------------------------------------------
Base.perform_caching = true
config.action_controller.perform_caching = true
-----------------------------------------------------
=== Page Caching
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.
So, how do you enable this super-fast cache behavior? Simple, let's say you
have a controller called ProductController and a 'list' action that lists all
have a controller called ProductsController and a 'list' action that lists all
the products
[source, ruby]
-----------------------------------------------------
class ProductController < ActionController
class ProductsController < ActionController
cache_page :list
caches_page :index
def list; end
def index; end
end
-----------------------------------------------------
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.
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.
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
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.
The page caching mechanism will automatically add a .html exxtension to
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
configuration setting ActionController::Base.page_cache_extension.
In order to expire this page when a new product is added we could extend our
example controler like this:
[source, ruby]
-----------------------------------------------------
class ProductController < ActionController
class ProductsController < ActionController
cache_page :list
caches_page :list
def list; end
@@ -80,11 +86,11 @@ to expire cached objects when things change. This is covered in the section on S
=== Action Caching
One of the issues with page caching is that you cannot use it for pages that
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.
@@ -95,10 +101,10 @@ object, but still cache those pages:
[source, ruby]
-----------------------------------------------------
class ProductController < ActionController
class ProductsController < ActionController
before_filter :authenticate, :only => [ :edit, :create ]
cache_page :list
caches_page :list
caches_action :edit
def list; end
@@ -120,7 +126,7 @@ or the number of items in the cart can be left uncached. This feature is
available as of Rails 2.2.
[More: more examples? Walk-through of action caching from request to response?
[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?]
@@ -132,15 +138,15 @@ 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.
differently Rails provides a mechanism called Fragment Caching.
Fragment caching allows a fragment of view logic to be wrapped in a cache
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.
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:
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:
[source, ruby]
-----------------------------------------------------
@@ -158,7 +164,7 @@ this piece of code:
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:
want to cache multiple fragments per action, you should provide an action_suffix to the cache call:
[source, ruby]
-----------------------------------------------------
@@ -225,10 +231,10 @@ following:
[source, ruby]
-----------------------------------------------------
class ProductController < ActionController
class ProductsController < ActionController
before_filter :authenticate, :only => [ :edit, :create ]
cache_page :list
caches_page :list
caches_action :edit
cache_sweeper :store_sweeper, :only => [ :create ]
@@ -257,10 +263,10 @@ For example:
[source, ruby]
-----------------------------------------------------
class ProductController < ActionController
class ProductsController < ActionController
before_filter :authenticate, :only => [ :edit, :create ]
cache_page :list
caches_page :list
caches_action :edit
cache_sweeper :store_sweeper, :only => [ :create ]

View File

@@ -0,0 +1,147 @@
A Guide to The Rails Command Line
=================================
Rails comes with every command line tool you'll need to
* Create a Rails application
* Generate models, controllers, database migrations, and unit tests
* Start a development server
* Mess with objects through an interactive shell
* Profile and benchmark your new creation
... and much, much more! (Buy now!)
This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.
== Command Line Basics ==
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:
* console
* server
* rake
* generate
* rails
Let's create a simple Rails application to step through each of these commands in context.
=== rails ===
The first thing we'll want to do is create a new Rails application by running the `rails` command after installing Rails.
NOTE: You know you need the rails gem installed by typing `gem install rails` first, right? Okay, okay, just making sure.
[source,shell]
------------------------------------------------------
$ rails commandsapp
create
create app/controllers
create app/helpers
create app/models
...
...
create log/production.log
create log/development.log
create log/test.log
------------------------------------------------------
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.
NOTE: This output will seem very familiar when we get to the `generate` command. Creepy foreshadowing!
=== server ===
Let's try it! The `server` 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.
NOTE: WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section]
Here we'll flex our `server` command, which without any prodding of any kind will run our new shiny Rails app:
[source,shell]
------------------------------------------------------
$ cd commandsapp
$ ./script/server
=> Booting WEBrick...
=> Rails 2.2.0 application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with --help for options
[2008-11-04 10:11:38] INFO WEBrick 1.3.1
[2008-11-04 10:11:38] INFO ruby 1.8.5 (2006-12-04) [i486-linux]
[2008-11-04 10:11:38] INFO WEBrick::HTTPServer#start: pid=18994 port=3000
------------------------------------------------------
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 http://localhost:3000. I'll wait.
See? Cool! It doesn't do much yet, but we'll change that.
=== generate ===
The `generate` command uses templates to create a whole lot of things. You can always find out what's available by running `generate` by itself. Let's do that:
[source,shell]
------------------------------------------------------
$ ./script/generate
Usage: ./script/generate generator [options] [args]
...
...
Installed Generators
Builtin: controller, integration_test, mailer, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration
...
...
------------------------------------------------------
NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
Using generators will save you a large amount of time by writing *boilerplate code* 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?
Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
NOTE: 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 `rails` or `./script/generate`). For others, you can try adding `--help` or `-h` to the end, as in `./script/server --help`.
[source,shell]
------------------------------------------------------
$ ./script/generate controller
Usage: ./script/generate controller ControllerName [options]
...
...
Example:
`./script/generate controller CreditCard open debit credit close`
Credit card controller with URLs like /credit_card/debit.
Controller: app/controllers/credit_card_controller.rb
Views: app/views/credit_card/debit.html.erb [...]
Helper: app/helpers/credit_card_helper.rb
Test: test/functional/credit_card_controller_test.rb
Modules Example:
`./script/generate controller 'admin/credit_card' suspend late_fee`
Credit card admin controller with URLs /admin/credit_card/suspend.
Controller: app/controllers/admin/credit_card_controller.rb
Views: app/views/admin/credit_card/debit.html.erb [...]
Helper: app/helpers/admin/credit_card_helper.rb
Test: test/functional/admin/credit_card_controller_test.rb
------------------------------------------------------
Ah, the controller generator is expecting parameters in the form of `generate controller ControllerName action1 action2`. Let's make a `Greetings` controller with an action of *hello*, which will say something nice to us.
[source,shell]
------------------------------------------------------
$ ./script/generate controller Greeting hello
exists app/controllers/
exists app/helpers/
create app/views/greeting
exists test/functional/
create app/controllers/greetings_controller.rb
create test/functional/greetings_controller_test.rb
create app/helpers/greetings_helper.rb
create app/views/greetings/hello.html.erb
------------------------------------------------------
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!

View File

@@ -1,32 +1,40 @@
== Add an `acts_as_yaffle` method to ActiveRecord ==
== Add an `acts_as_yaffle` method to Active Record ==
A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_yaffle` that adds a `squawk` method to your models.
A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models.
To keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in your plugin's test directory and require your test helper.
To begin, set up your files so that you have:
*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
class ActsAsYaffleTest < Test::Unit::TestCase
end
------------------------------------------------------
*vendor/plugins/yaffle/lib/yaffle.rb*
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/lib/acts_as_yaffle.rb
require 'yaffle/acts_as_yaffle'
------------------------------------------------------
*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
[source, ruby]
------------------------------------------------------
module Yaffle
# your code will go here
end
------------------------------------------------------
One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so:
Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.
One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so:
*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
[source, ruby]
------------------------------------------------------
@@ -50,52 +58,45 @@ end
With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`).
Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail.
=== Add a class method ===
Back in your `acts_as_yaffle` file, update ClassMethods like so:
This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
To start out, write a failing test that shows the behavior you'd like:
*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
[source, ruby]
------------------------------------------------------
module ClassMethods
def acts_as_yaffle(options = {})
send :include, InstanceMethods
end
end
------------------------------------------------------
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:
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
class Wickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_tweet
end
class ActsAsYaffleTest < Test::Unit::TestCase
load_schema
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
assert_equal "last_squawked_at", Hickwall.yaffle_date_field
end
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
end
end
------------------------------------------------------
To make these tests pass, you could modify your `acts_as_yaffle` file like so:
*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
@@ -103,70 +104,66 @@ module Yaffle
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field, :yaffle_date_field
cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
send :include, InstanceMethods
end
end
module InstanceMethods
end
end
ActiveRecord::Base.send :include, Yaffle
------------------------------------------------------
Now you can add tests for the instance methods, and the instance method itself:
=== Add an instance method ===
This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database.
To start out, write a failing test that shows the behavior you'd like:
*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
class Wickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_tweet
end
class ActsAsYaffleTest < Test::Unit::TestCase
load_schema
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
assert_equal "last_squawked_at", Hickwall.yaffle_date_field
end
def test_a_wickwalls_yaffle_text_field_should_be_last_squawk
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at
assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
end
def test_hickwalls_squawk_should_populate_last_squawk
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal "squawk! Hello World", hickwall.last_squawk
end
def test_hickwalls_squawk_should_populate_last_squawked_at
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal Date.today, hickwall.last_squawked_at
end
def test_wickwalls_squawk_should_populate_last_tweet
wickwall = Wickwall.new
wickwall.squawk("Hello World")
assert_equal "squawk! Hello World", wickwall.last_tweet
end
end
def test_wickwalls_squawk_should_populate_last_tweeted_at
wickwall = Wickwall.new
wickwall.squawk("Hello World")
assert_equal Date.today, wickwall.last_tweeted_at
end
assert_equal "squawk! Hello World", wickwall.last_tweet
end
end
------------------------------------------------------
Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this:
*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
@@ -174,9 +171,8 @@ module Yaffle
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field, :yaffle_date_field
cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
send :include, InstanceMethods
end
end
@@ -184,10 +180,12 @@ module Yaffle
module InstanceMethods
def squawk(string)
write_attribute(self.class.yaffle_text_field, string.to_squawk)
write_attribute(self.class.yaffle_date_field, Date.today)
end
end
end
ActiveRecord::Base.send :include, Yaffle
------------------------------------------------------
Note the use of `write_attribute` to write to the field in model.
.Editor's note:
NOTE: The use of `write_attribute` 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 `send("#{self.class.yaffle_text_field}=", string.to_squawk)`.

View File

@@ -1,861 +0,0 @@
Creating Plugin Basics
====================
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.
In this tutorial you will learn how to create a plugin that includes:
Core Extensions - extending String:
# Anywhere
"hello".squawk # => "squawk! hello! squawk!"
An `acts_as_yaffle` method for Active Record models that adds a "squawk" method:
class Hickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_sang_at
end
Hickwall.new.squawk("Hello World")
A view helper that will print out squawking info:
squawk_info_for(@hickwall)
A generator that creates a migration to add squawk columns to a model:
script/generate yaffle hickwall
A custom generator command:
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
m.yaffle_definition
end
end
end
A custom route method:
ActionController::Routing::Routes.draw do |map|
map.yaffles
end
In addition you'll learn how to:
* test your plugins
* work with init.rb, how to store model, views, controllers, helpers and even other plugins in your plugins
* create documentation for your plugin.
* write custom rake tasks in your plugin
Create the basic app
---------------------
In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app:
> The following instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
rails plugin_demo
cd plugin_demo
script/generate scaffold bird name:string
rake db:migrate
script/server
Then navigate to [http://localhost:3000/birds](http://localhost:3000/birds). Make sure you have a functioning rails app before continuing.
Create the plugin
-----------------------
The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either CamelCased or under_scored, as an argument. Pass --with-generator to add an example generator also.
This creates a plugin in vendor/plugins including an init.rb and README as well as standard lib, task, and test directories.
Examples:
./script/generate plugin BrowserFilters
./script/generate plugin BrowserFilters --with-generator
Later in the plugin we will create a generator, so go ahead and add the --with-generator option now:
script/generate plugin yaffle --with-generator
You should see the following output:
create vendor/plugins/yaffle/lib
create vendor/plugins/yaffle/tasks
create vendor/plugins/yaffle/test
create vendor/plugins/yaffle/README
create vendor/plugins/yaffle/MIT-LICENSE
create vendor/plugins/yaffle/Rakefile
create vendor/plugins/yaffle/init.rb
create vendor/plugins/yaffle/install.rb
create vendor/plugins/yaffle/uninstall.rb
create vendor/plugins/yaffle/lib/yaffle.rb
create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
create vendor/plugins/yaffle/test/core_ext_test.rb
create vendor/plugins/yaffle/generators
create vendor/plugins/yaffle/generators/yaffle
create vendor/plugins/yaffle/generators/yaffle/templates
create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE
For this plugin you won't need the file vendor/plugins/yaffle/lib/yaffle.rb so you can delete that.
rm vendor/plugins/yaffle/lib/yaffle.rb
> Editor's note: 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 `require "yaffle"`
> 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
Setup the plugin for testing
------------------------
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.
To setup your plugin to allow for easy testing you'll need to add 3 files:
* A database.yml file with all of your connection strings
* A schema.rb file with your table definitions
* A test helper that sets up the database before your tests
For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files:
# File: vendor/plugins/yaffle/test/database.yml
sqlite:
:adapter: sqlite
:dbfile: yaffle_plugin.sqlite.db
sqlite3:
:adapter: sqlite3
:dbfile: yaffle_plugin.sqlite3.db
postgresql:
:adapter: postgresql
:username: postgres
:password: postgres
:database: yaffle_plugin_test
:min_messages: ERROR
mysql:
:adapter: mysql
:host: localhost
:username: rails
:password:
:database: yaffle_plugin_test
# File: vendor/plugins/yaffle/test/test_helper.rb
ActiveRecord::Schema.define(:version => 0) do
create_table :hickwalls, :force => true do |t|
t.string :name
t.string :last_squawk
t.datetime :last_squawked_at
end
create_table :wickwalls, :force => true do |t|
t.string :name
t.string :last_tweet
t.datetime :last_tweeted_at
end
end
# File: vendor/plugins/yaffle/test/test_helper.rb
ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
require 'test/unit'
require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
db_adapter = ENV['DB']
# no db passed, try one of these fine config-free DBs before bombing.
db_adapter ||=
begin
require 'rubygems'
require 'sqlite'
'sqlite'
rescue MissingSourceFile
begin
require 'sqlite3'
'sqlite3'
rescue MissingSourceFile
end
end
if db_adapter.nil?
raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
end
ActiveRecord::Base.establish_connection(config[db_adapter])
load(File.dirname(__FILE__) + "/schema.rb")
require File.dirname(__FILE__) + '/../init.rb'
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
class Wickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at
end
Add a `to_squawk` method to String
-----------------------
To update a core class you will have to:
* Write tests for the desired functionality
* Create a file for the code you wish to use
* Require that file from your init.rb
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 init.rb. The file you are going to add for this tutorial is `lib/core_ext.rb`
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:
# File: vendor/plugins/yaffle/test/core_ext_test.rb
require 'test/unit'
class CoreExtTest < Test::Unit::TestCase
# Replace this with your real tests.
def test_this_plugin
flunk
end
end
Start off by removing the default test, and adding a require statement for your test helper.
# File: vendor/plugins/yaffle/test/core_ext_test.rb
require 'test/unit'
require File.dirname(__FILE__) + '/test_helper.rb'
class CoreExtTest < Test::Unit::TestCase
end
Navigate to your plugin directory and run `rake test`
cd vendor/plugins/yaffle
rake test
Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file `lib/core_ext.rb` and re-run the tests. You should see a different error message:
1.) Failure ...
No tests were specified
Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word "squawk! ". The test will look something like this:
# File: vendor/plugins/yaffle/init.rb
class CoreExtTest < Test::Unit::TestCase
def test_string_should_respond_to_squawk
assert_equal true, "".respond_to?(:to_squawk)
end
def test_string_prepend_empty_strings_with_the_word_squawk
assert_equal "squawk!", "".to_squawk
end
def test_string_prepend_non_empty_strings_with_the_word_squawk
assert_equal "squawk! Hello World", "Hello World".to_squawk
end
end
# File: vendor/plugins/yaffle/init.rb
require "core_ext"
# File: vendor/plugins/yaffle/lib/core_ext.rb
String.class_eval do
def to_squawk
"squawk! #{self}".strip
end
end
When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly.
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:
script/console
>> "Hello World".to_squawk
=> "squawk! Hello World"
If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.
Add an `acts_as_yaffle` method to ActiveRecord
-----------------------
A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_yaffle` that adds a squawk method to your models.
To keep things clean, create a new test file called `acts_as_yaffle_test.rb` in your plugin's test directory and require your test helper.
# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
class ActsAsYaffleTest < Test::Unit::TestCase
end
# File: vendor/plugins/lib/acts_as_yaffle.rb
module Yaffle
end
One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so:
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
# any method placed here will apply to classes, like Hickwall
def acts_as_something
send :include, InstanceMethods
end
end
module InstanceMethods
# any method placed here will apply to instaces, like @hickwall
end
end
With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`).
Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail.
Back in your `acts_as_yaffle` file, update ClassMethods like so:
module ClassMethods
def acts_as_yaffle(options = {})
send :include, InstanceMethods
end
end
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:
# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
assert_equal "last_squawked_at", Hickwall.yaffle_date_field
end
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
end
end
To make these tests pass, you could modify your `acts_as_yaffle` file like so:
# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field, :yaffle_date_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
send :include, InstanceMethods
end
end
module InstanceMethods
end
end
Now you can add tests for the instance methods, and the instance method itself:
# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
assert_equal "last_squawked_at", Hickwall.yaffle_date_field
end
def test_a_wickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at
assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
end
def test_hickwalls_squawk_should_populate_last_squawk
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal "squawk! Hello World", hickwall.last_squawk
end
def test_hickwalls_squawk_should_populate_last_squawked_at
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal Date.today, hickwall.last_squawked_at
end
def test_wickwalls_squawk_should_populate_last_tweet
wickwall = Wickwall.new
wickwall.squawk("Hello World")
assert_equal "squawk! Hello World", wickwall.last_tweet
end
def test_wickwalls_squawk_should_populate_last_tweeted_at
wickwall = Wickwall.new
wickwall.squawk("Hello World")
assert_equal Date.today, wickwall.last_tweeted_at
end
end
# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field, :yaffle_date_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
send :include, InstanceMethods
end
end
module InstanceMethods
def squawk(string)
write_attribute(self.class.yaffle_text_field, string.to_squawk)
write_attribute(self.class.yaffle_date_field, Date.today)
end
end
end
Note the use of write_attribute to write to the field in model.
Create a view helper
-----------------------
Creating a view helper is a 3-step process:
* Add an appropriately named file to the lib directory
* Require the file and hooks in init.rb
* Write the tests
First, create the test to define the functionality you want:
# File: vendor/plugins/yaffle/test/view_helpers_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
include YaffleViewHelper
class ViewHelpersTest < Test::Unit::TestCase
def test_squawk_info_for_should_return_the_text_and_date
time = Time.now
hickwall = Hickwall.new
hickwall.last_squawk = "Hello World"
hickwall.last_squawked_at = time
assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall)
end
end
Then add the following statements to init.rb:
# File: vendor/plugins/yaffle/init.rb
require "view_helpers"
ActionView::Base.send :include, YaffleViewHelper
Then add the view helpers file and
# File: vendor/plugins/yaffle/lib/view_helpers.rb
module YaffleViewHelper
def squawk_info_for(yaffle)
returning "" do |result|
result << yaffle.read_attribute(yaffle.class.yaffle_text_field)
result << ", "
result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s
end
end
end
You can also test this in script/console by using the "helper" method:
script/console
>> helper.squawk_info_for(@some_yaffle_instance)
Create a migration generator
-----------------------
When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin.
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.
Type:
script/generate
You should see the line:
Plugins (vendor/plugins): yaffle
When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:
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
Now you can add code to your generator:
# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
:migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
}
end
end
private
def custom_file_name
custom_name = class_name.underscore.downcase
custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
end
def yaffle_local_assigns
returning(assigns = {}) do
assigns[:migration_action] = "add"
assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
assigns[:table_name] = custom_file_name
assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime")
end
end
end
Note that you need to be aware of whether or not table names are pluralized.
This does a few things:
* Reuses the built in rails migration_template method
* Reuses the built-in rails migration template
When you run the generator like
script/generate yaffle bird
You will see a new file:
# File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
class AddYaffleFieldsToBirds < ActiveRecord::Migration
def self.up
add_column :birds, :last_squawk, :string
add_column :birds, :last_squawked_at, :datetime
end
def self.down
remove_column :birds, :last_squawked_at
remove_column :birds, :last_squawk
end
end
Add a custom generator command
------------------------
You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps:
1. Add the require and hook statements to init.rb
2. Create the commands - creating 3 sets, Create, Destroy, List
3. Add the method to your generator
Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
# File: vendor/plugins/yaffle/init.rb
require "commands"
Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
# File: vendor/plugins/yaffle/lib/commands.rb
require 'rails_generator'
require 'rails_generator/commands'
module Yaffle #:nodoc:
module Generator #:nodoc:
module Commands #:nodoc:
module Create
def yaffle_definition
file("definition.txt", "definition.txt")
end
end
module Destroy
def yaffle_definition
file("definition.txt", "definition.txt")
end
end
module List
def yaffle_definition
file("definition.txt", "definition.txt")
end
end
end
end
end
# File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
Yaffle is a bird
# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
m.yaffle_definition
end
end
end
This example just uses the built-in "file" method, but you could do anything that ruby allows.
Add a Custom Route
------------------------
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 [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)
# File: vendor/plugins/yaffle/test/routing_test.rb
require "#{File.dirname(__FILE__)}/test_helper"
class RoutingTest < Test::Unit::TestCase
def setup
ActionController::Routing::Routes.draw do |map|
map.yaffles
end
end
def test_yaffles_route
assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index"
end
private
# yes, I know about assert_recognizes, but it has proven problematic to
# use in these tests, since it uses RouteSet#recognize (which actually
# tries to instantiate the controller) and because it uses an awkward
# parameter order.
def assert_recognition(method, path, options)
result = ActionController::Routing::Routes.recognize_path(path, :method => method)
assert_equal options, result
end
end
# File: vendor/plugins/yaffle/init.rb
require "routing"
ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
# File: vendor/plugins/yaffle/lib/routing.rb
module Yaffle #:nodoc:
module Routing #:nodoc:
module MapperExtensions
def yaffles
@set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"})
end
end
end
end
# File: config/routes.rb
ActionController::Routing::Routes.draw do |map|
...
map.yaffles
end
You can also see if your routes work by running `rake routes` from your app directory.
Generate RDoc Documentation
-----------------------
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.
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:
* Your name
* How to install
* How to add the functionality to the app (several examples of common use cases)
* Warning, gotchas or tips that might help save users time
Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.
Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.
Once your comments are good to go, navigate to your plugin directory and run
rake rdoc
Work with init.rb
------------------------
The plugin initializer script init.rb is invoked via `eval` (not require) so it has slightly different behavior.
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:
The first way is to explicitly define the top-level module space for all modules and classes, like ::Hash
# File: vendor/plugins/yaffle/init.rb
class ::Hash
def is_a_special_hash?
true
end
end
OR you can use `module_eval` or `class_eval`
# File: vendor/plugins/yaffle/init.rb
Hash.class_eval do
def is_a_special_hash?
true
end
end
Store models, views, helpers, and controllers in your plugins
------------------------
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:
# File: vendor/plugins/yaffle/init.rb
%w{ models controllers helpers }.each do |dir|
path = File.join(directory, 'lib', dir)
$LOAD_PATH << path
Dependencies.load_paths << path
Dependencies.load_once_paths.delete(path)
end
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.
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.
Write custom rake tasks in your plugin
-------------------------
When you created the plugin with the built-in rails generator, it generated a rake file for you in `vendor/plugins/yaffle/tasks/yaffle.rake`. Any rake task you add here will be available to the app.
Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
# File: vendor/plugins/yaffle/tasks/yaffle.rake
namespace :yaffle do
desc "Prints out the word 'Yaffle'"
task :squawk => :environment do
puts "squawk!"
end
end
When you run `rake -T` from your plugin you will see
yaffle:squawk "Prints out..."
You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.
Store plugins in alternate locations
-------------------------
You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb
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.
You can even store plugins inside of other plugins for complete plugin madness!
config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")
Create your own Plugin Loaders and Plugin Locators
------------------------
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.
Use Custom Plugin Generators
------------------------
If you are an RSpec fan, you can install the `rspec_plugin_generator`, which will generate the spec folder and database for you.
[http://github.com/pat-maddox/rspec-plugin-generator/tree/master](http://github.com/pat-maddox/rspec-plugin-generator/tree/master)
References
------------------------
* [http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i](http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i)
* [http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii](http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii)
* [http://github.com/technoweenie/attachment_fu/tree/master](http://github.com/technoweenie/attachment_fu/tree/master)
* [http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html](http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html)
Appendices
------------------------
The final plugin should have a directory structure that looks something like this:
|-- MIT-LICENSE
|-- README
|-- Rakefile
|-- generators
| `-- yaffle
| |-- USAGE
| |-- templates
| | `-- definition.txt
| `-- yaffle_generator.rb
|-- init.rb
|-- install.rb
|-- lib
| |-- acts_as_yaffle.rb
| |-- commands.rb
| |-- core_ext.rb
| |-- routing.rb
| `-- view_helpers.rb
|-- tasks
| `-- yaffle_tasks.rake
|-- test
| |-- acts_as_yaffle_test.rb
| |-- core_ext_test.rb
| |-- database.yml
| |-- debug.log
| |-- routing_test.rb
| |-- schema.rb
| |-- test_helper.rb
| `-- view_helpers_test.rb
|-- uninstall.rb
`-- yaffle_plugin.sqlite3.db

View File

@@ -0,0 +1,59 @@
== Add a controller ==
This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
You can test your plugin's controller as you would test any other controller:
*vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:*
[source, ruby]
----------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
require 'woodpeckers_controller'
require 'action_controller/test_process'
class WoodpeckersController; def rescue_action(e) raise e end; end
class WoodpeckersControllerTest < Test::Unit::TestCase
def setup
@controller = WoodpeckersController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_index
get :index
assert_response :success
end
end
----------------------------------------------
This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with `rake`, you can make it pass like so:
*vendor/plugins/yaffle/lib/yaffle.rb:*
[source, ruby]
----------------------------------------------
%w{ models controllers }.each do |dir|
path = File.join(File.dirname(__FILE__), 'app', dir)
$LOAD_PATH << path
ActiveSupport::Dependencies.load_paths << path
ActiveSupport::Dependencies.load_once_paths.delete(path)
end
----------------------------------------------
*vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:*
[source, ruby]
----------------------------------------------
class WoodpeckersController < ActionController::Base
def index
render :text => "Squawk!"
end
end
----------------------------------------------
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 http://localhost:3000/woodpeckers to see your controller in action.

View File

@@ -0,0 +1,123 @@
== Extending core classes ==
This section will explain how to add a method to String that will be available anywhere in your rails app by:
* Writing tests for the desired behavior
* Creating and requiring the correct files
=== Creating the test ===
In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions:
*vendor/plugins/yaffle/test/core_ext_test.rb*
[source, ruby]
--------------------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
class CoreExtTest < Test::Unit::TestCase
def test_to_squawk_prepends_the_word_squawk
assert_equal "squawk! Hello World", "Hello World".to_squawk
end
end
--------------------------------------------------------
Navigate to your plugin directory and run `rake test`:
--------------------------------------------------------
cd vendor/plugins/yaffle
rake test
--------------------------------------------------------
The test above should fail with the message:
--------------------------------------------------------
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'
--------------------------------------------------------
Great - now you are ready to start development.
=== Organize your files ===
A common pattern in rails plugins is to set up the file structure like this:
--------------------------------------------------------
|-- lib
| |-- yaffle
| | `-- core_ext.rb
| `-- yaffle.rb
--------------------------------------------------------
The first thing we need to to is to require our 'lib/yaffle.rb' file from 'rails/init.rb':
*vendor/plugins/yaffle/rails/init.rb*
[source, ruby]
--------------------------------------------------------
require 'yaffle'
--------------------------------------------------------
Then in 'lib/yaffle.rb' require 'lib/core_ext.rb':
*vendor/plugins/yaffle/lib/yaffle.rb*
[source, ruby]
--------------------------------------------------------
require "yaffle/core_ext"
--------------------------------------------------------
Finally, create the 'core_ext.rb' file and add the 'to_squawk' method:
*vendor/plugins/yaffle/lib/yaffle/core_ext.rb*
[source, ruby]
--------------------------------------------------------
String.class_eval do
def to_squawk
"squawk! #{self}".strip
end
end
--------------------------------------------------------
To test that your method does what it says it does, run the unit tests with `rake` from your plugin directory. To see this in action, fire up a console and start squawking:
--------------------------------------------------------
$ ./script/console
>> "Hello World".to_squawk
=> "squawk! Hello World"
--------------------------------------------------------
=== Working with init.rb ===
When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior.
Under certain circumstances if you reopen classes or modules in 'init.rb' 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 `init.rb`, as shown above.
If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval` to avoid any issues:
*vendor/plugins/yaffle/init.rb*
[source, ruby]
---------------------------------------------------
Hash.class_eval do
def is_a_special_hash?
true
end
end
---------------------------------------------------
Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`:
*vendor/plugins/yaffle/init.rb*
[source, ruby]
---------------------------------------------------
class ::Hash
def is_a_special_hash?
true
end
end
---------------------------------------------------

View File

@@ -2,10 +2,10 @@
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 http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
*vendor/plugins/yaffle/test/routing_test.rb*
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/test/routing_test.rb
require "#{File.dirname(__FILE__)}/test_helper"
class RoutingTest < Test::Unit::TestCase
@@ -33,18 +33,18 @@ class RoutingTest < Test::Unit::TestCase
end
--------------------------------------------------------
*vendor/plugins/yaffle/init.rb*
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
require "routing"
ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
--------------------------------------------------------
*vendor/plugins/yaffle/lib/routing.rb*
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/lib/routing.rb
module Yaffle #:nodoc:
module Routing #:nodoc:
module MapperExtensions
@@ -56,10 +56,10 @@ module Yaffle #:nodoc:
end
--------------------------------------------------------
*config/routes.rb*
[source, ruby]
--------------------------------------------------------
# File: config/routes.rb
ActionController::Routing::Routes.draw do |map|
...
map.yaffles

View File

@@ -0,0 +1 @@
http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins

View File

@@ -1,26 +1,41 @@
== Add a custom generator command ==
You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps:
You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
1. Add the require and hook statements to init.rb.
2. Create the commands - creating 3 sets, Create, Destroy, List.
3. Add the method to your generator.
This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file.
Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
To start, add the following test method:
*vendor/plugins/yaffle/test/generator_test.rb*
[source, ruby]
-----------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
require "commands"
Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
def test_generates_definition
Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
definition = File.read(File.join(fake_rails_root, "definition.txt"))
assert_match /Yaffle\:/, definition
end
-----------------------------------------------------------
Run `rake` to watch the test fail, then make the test pass add the following:
*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt*
-----------------------------------------------------------
Yaffle: A bird
-----------------------------------------------------------
*vendor/plugins/yaffle/lib/yaffle.rb*
[source, ruby]
-----------------------------------------------------------
# File: vendor/plugins/yaffle/lib/commands.rb
require "yaffle/commands"
-----------------------------------------------------------
*vendor/plugins/yaffle/lib/commands.rb*
[source, ruby]
-----------------------------------------------------------
require 'rails_generator'
require 'rails_generator/commands'
@@ -44,26 +59,31 @@ module Yaffle #:nodoc:
file("definition.txt", "definition.txt")
end
end
module Update
def yaffle_definition
file("definition.txt", "definition.txt")
end
end
end
end
end
Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update
-----------------------------------------------------------
-----------------------------------------------------------
# File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
Finally, call your new method in the manifest:
Yaffle is a bird
-----------------------------------------------------------
*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
[source, ruby]
-----------------------------------------------------------
# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
m.yaffle_definition
end
end
-----------------------------------------------------------
This example just uses the built-in "file" method, but you could do anything that Ruby allows.

View File

@@ -0,0 +1,51 @@
== Add a helper ==
This section describes how to add a helper named 'WoodpeckersHelper' 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.
You can test your plugin's helper as you would test any other helper:
*vendor/plugins/yaffle/test/woodpeckers_helper_test.rb*
[source, ruby]
---------------------------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
include WoodpeckersHelper
class WoodpeckersHelperTest < Test::Unit::TestCase
def test_tweet
assert_equal "Tweet! Hello", tweet("Hello")
end
end
---------------------------------------------------------------
This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with `rake`, you can make it pass like so:
*vendor/plugins/yaffle/lib/yaffle.rb:*
[source, ruby]
----------------------------------------------
%w{ models controllers helpers }.each do |dir|
path = File.join(File.dirname(__FILE__), 'app', dir)
$LOAD_PATH << path
ActiveSupport::Dependencies.load_paths << path
ActiveSupport::Dependencies.load_once_paths.delete(path)
end
ActionView::Base.send :include, WoodpeckersHelper
----------------------------------------------
*vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:*
[source, ruby]
----------------------------------------------
module WoodpeckersHelper
def tweet(text)
"Tweet! #{text}"
end
end
----------------------------------------------
Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.

View File

@@ -1,81 +1,49 @@
The Basics of Creating Rails Plugins
====================================
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.
A Rails plugin is either an extension or a modification of the core framework. Plugins provide:
In this tutorial you will learn how to create a plugin that includes:
* a way for developers to share bleeding-edge ideas without hurting the stable code base
* a segmented architecture so that units of code can be fixed or updated on their own release schedule
* an outlet for the core developers so that they dont have to include every cool new feature under the sun
* Core Extensions - extending String with a `to_squawk` method:
+
[source, ruby]
-------------------------------------------
# Anywhere
"hello!".to_squawk # => "squawk! hello!"
-------------------------------------------
After reading this guide you should be familiar with:
* Creating a plugin from scratch
* Writing and running tests for the plugin
* Storing models, views, controllers, helpers and even other plugins in your plugins
* Writing generators
* Writing custom Rake tasks in your plugin
* Generating RDoc documentation for your plugin
* Avoiding common pitfalls with 'init.rb'
* An `acts_as_yaffle` method for ActiveRecord models that adds a `squawk` method:
+
[source, ruby]
-------------------------------------------
class Hickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_sang_at
end
This guide describes how to build a test-driven plugin that will:
Hickwall.new.squawk("Hello World")
-------------------------------------------
* Extend core ruby classes like Hash and String
* Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins
* Add a view helper that can be used in erb templates
* Add a new generator that will generate a migration
* Add a custom generator command
* A custom route method that can be used in routes.rb
* A view helper that will print out squawking info:
+
[source, ruby]
-------------------------------------------
squawk_info_for(@hickwall)
-------------------------------------------
* A generator that creates a migration to add squawk columns to a model:
+
-------------------------------------------
script/generate yaffle hickwall
-------------------------------------------
* A custom generator command:
+
[source, ruby]
-------------------------------------------
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
m.yaffle_definition
end
end
-------------------------------------------
* A custom route method:
+
[source, ruby]
-------------------------------------------
ActionController::Routing::Routes.draw do |map|
map.yaffles
end
-------------------------------------------
In addition you'll learn how to:
* test your plugins.
* work with 'init.rb', how to store model, views, controllers, helpers and even other plugins in your plugins.
* create documentation for your plugin.
* write custom Rake tasks in your plugin.
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.
include::preparation.txt[]
include::test_setup.txt[]
include::string_to_squawk.txt[]
include::core_ext.txt[]
include::acts_as_yaffle.txt[]
include::view_helper.txt[]
include::migration_generator.txt[]
include::custom_generator.txt[]
include::generator_method.txt[]
include::models.txt[]
include::controllers.txt[]
include::helpers.txt[]
include::custom_route.txt[]

View File

@@ -1,42 +1,79 @@
== Create a migration generator ==
== Create a generator ==
When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin.
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 'vendor/plugins/yaffle/generators/yaffle'.
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.
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.
Type:
To create a generator you must:
script/generate
* Add your instructions to the 'manifest' method of the generator
* Add any necessary template files to the templates directory
* Test the generator manually by running various combinations of `script/generate` and `script/destroy`
* Update the USAGE file to add helpful documentation for your generator
You should see the line:
=== Testing generators ===
Plugins (vendor/plugins): yaffle
Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:
* Creates a new fake rails root directory that will serve as destination
* Runs the generator forward and backward, making whatever assertions are necessary
* Removes the fake rails root
------------------------------------------------------------------
Description:
Creates a migration that adds yaffle squawk fields to the given model
For the generator in this section, the test could look something like this:
Example:
./script/generate yaffle hickwall
This will create:
db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
------------------------------------------------------------------
Now you can add code to your generator:
*vendor/plugins/yaffle/test/yaffle_generator_test.rb*
[source, ruby]
------------------------------------------------------------------
# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
require File.dirname(__FILE__) + '/test_helper.rb'
require 'rails_generator'
require 'rails_generator/scripts/generate'
require 'rails_generator/scripts/destroy'
class GeneratorTest < Test::Unit::TestCase
def fake_rails_root
File.join(File.dirname(__FILE__), 'rails_root')
end
def file_list
Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
end
def setup
FileUtils.mkdir_p(fake_rails_root)
@original_files = file_list
end
def teardown
FileUtils.rm_r(fake_rails_root)
end
def test_generates_correct_file_name
Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
new_file = (file_list - @original_files).first
assert_match /add_yaffle_fields_to_bird/, new_file
end
end
------------------------------------------------------------------
You can run 'rake' 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.
=== Adding to the manifest ===
This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. To start, update your generator file to look like this:
*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
[source, ruby]
------------------------------------------------------------------
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
:migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
}
}
end
end
@@ -52,38 +89,68 @@ class YaffleGenerator < Rails::Generator::NamedBase
assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
assigns[:table_name] = custom_file_name
assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime")
end
end
end
------------------------------------------------------------------
Note that you need to be aware of whether or not table names are pluralized.
The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template.
This does a few things:
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.
* Reuses the built in rails `migration_template` method.
* Reuses the built-in rails migration template.
=== Manually test the generator ===
When you run the generator like
To run the generator, type the following at the command line:
script/generate yaffle bird
------------------------------------------------------------------
./script/generate yaffle bird
------------------------------------------------------------------
You will see a new file:
and you will see a new file:
*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb*
[source, ruby]
------------------------------------------------------------------
# File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
class AddYaffleFieldsToBirds < ActiveRecord::Migration
def self.up
add_column :birds, :last_squawk, :string
add_column :birds, :last_squawked_at, :datetime
end
def self.down
remove_column :birds, :last_squawked_at
remove_column :birds, :last_squawk
end
end
------------------------------------------------------------------
=== The USAGE file ===
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:
------------------------------------------------------------------
script/generate
------------------------------------------------------------------
You should see something like this:
------------------------------------------------------------------
Installed Generators
Plugins (vendor/plugins): yaffle
Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration
------------------------------------------------------------------
When you run `script/generate yaffle` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle/USAGE' file.
For this plugin, update the USAGE file looks like this:
------------------------------------------------------------------
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
------------------------------------------------------------------

View File

@@ -0,0 +1,76 @@
== Add a model ==
This section describes how to add a model named 'Woodpecker' 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:
---------------------------------------------------------
vendor/plugins/yaffle/
|-- lib
| |-- app
| | |-- controllers
| | |-- helpers
| | |-- models
| | | `-- woodpecker.rb
| | `-- views
| |-- yaffle
| | |-- acts_as_yaffle.rb
| | |-- commands.rb
| | `-- core_ext.rb
| `-- yaffle.rb
---------------------------------------------------------
As always, start with a test:
*vendor/plugins/yaffle/yaffle/woodpecker_test.rb:*
[source, ruby]
----------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
class WoodpeckerTest < Test::Unit::TestCase
load_schema
def test_woodpecker
assert_kind_of Woodpecker, Woodpecker.new
end
end
----------------------------------------------
This is just a simple test to make sure the class is being loaded correctly. After watching it fail with `rake`, you can make it pass like so:
*vendor/plugins/yaffle/lib/yaffle.rb:*
[source, ruby]
----------------------------------------------
%w{ models }.each do |dir|
path = File.join(File.dirname(__FILE__), 'app', dir)
$LOAD_PATH << path
ActiveSupport::Dependencies.load_paths << path
ActiveSupport::Dependencies.load_once_paths.delete(path)
end
----------------------------------------------
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 'load_once_paths' 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.
*vendor/plugins/yaffle/lib/app/models/woodpecker.rb:*
[source, ruby]
----------------------------------------------
class Woodpecker < ActiveRecord::Base
end
----------------------------------------------
Finally, add the following to your plugin's 'schema.rb':
*vendor/plugins/yaffle/test/schema.rb:*
[source, ruby]
----------------------------------------------
ActiveRecord::Schema.define(:version => 0) do
create_table :woodpeckers, :force => true do |t|
t.string :name
end
end
----------------------------------------------
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.

View File

@@ -1,36 +1,5 @@
== Odds and ends ==
=== Work with init.rb ===
The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior.
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:
The first way is to explicitly define the top-level module space for all modules and classes, like `::Hash`:
[source, ruby]
---------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
class ::Hash
def is_a_special_hash?
true
end
end
---------------------------------------------------
OR you can use `module_eval` or `class_eval`:
---------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
Hash.class_eval do
def is_a_special_hash?
true
end
end
---------------------------------------------------
=== Generate RDoc Documentation ===
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.
@@ -50,38 +19,16 @@ Once your comments are good to go, navigate to your plugin directory and run:
rake rdoc
=== Store models, views, helpers, and controllers in your plugins ===
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:
[source, ruby]
---------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
%w{ models controllers helpers }.each do |dir|
path = File.join(directory, 'lib', dir)
$LOAD_PATH << path
Dependencies.load_paths << path
Dependencies.load_once_paths.delete(path)
end
---------------------------------------------------------
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.
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.
=== Write custom Rake tasks in your plugin ===
When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app.
Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
*vendor/plugins/yaffle/tasks/yaffle.rake*
[source, ruby]
---------------------------------------------------------
# File: vendor/plugins/yaffle/tasks/yaffle.rake
namespace :yaffle do
desc "Prints out the word 'Yaffle'"
task :squawk => :environment do

View File

@@ -1,169 +0,0 @@
== Preparation ==
=== Create the basic app ===
In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app:
------------------------------------------------
rails plugin_demo
cd plugin_demo
script/generate scaffold bird name:string
rake db:migrate
script/server
------------------------------------------------
Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing.
NOTE: 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.
=== Create the plugin ===
The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also.
This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories.
Examples:
----------------------------------------------
./script/generate plugin BrowserFilters
./script/generate plugin BrowserFilters --with-generator
----------------------------------------------
Later in the plugin we will create a generator, so go ahead and add the `\--with-generator` option now:
----------------------------------------------
script/generate plugin yaffle --with-generator
----------------------------------------------
You should see the following output:
----------------------------------------------
create vendor/plugins/yaffle/lib
create vendor/plugins/yaffle/tasks
create vendor/plugins/yaffle/test
create vendor/plugins/yaffle/README
create vendor/plugins/yaffle/MIT-LICENSE
create vendor/plugins/yaffle/Rakefile
create vendor/plugins/yaffle/init.rb
create vendor/plugins/yaffle/install.rb
create vendor/plugins/yaffle/uninstall.rb
create vendor/plugins/yaffle/lib/yaffle.rb
create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
create vendor/plugins/yaffle/test/core_ext_test.rb
create vendor/plugins/yaffle/generators
create vendor/plugins/yaffle/generators/yaffle
create vendor/plugins/yaffle/generators/yaffle/templates
create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE
----------------------------------------------
For this plugin you won't need the file 'vendor/plugins/yaffle/lib/yaffle.rb' so you can delete that.
----------------------------------------------
rm vendor/plugins/yaffle/lib/yaffle.rb
----------------------------------------------
.Editor's note:
NOTE: 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 `require "yaffle"`. 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
=== Setup the plugin for testing ===
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.
To setup your plugin to allow for easy testing you'll need to add 3 files:
* A 'database.yml' file with all of your connection strings.
* A 'schema.rb' file with your table definitions.
* A test helper that sets up the database before your tests.
For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files:
*vendor/plugins/yaffle/test/database.yml:*
----------------------------------------------
sqlite:
:adapter: sqlite
:dbfile: yaffle_plugin.sqlite.db
sqlite3:
:adapter: sqlite3
:dbfile: yaffle_plugin.sqlite3.db
postgresql:
:adapter: postgresql
:username: postgres
:password: postgres
:database: yaffle_plugin_test
:min_messages: ERROR
mysql:
:adapter: mysql
:host: localhost
:username: rails
:password:
:database: yaffle_plugin_test
----------------------------------------------
*vendor/plugins/yaffle/test/test_helper.rb:*
[source, ruby]
----------------------------------------------
ActiveRecord::Schema.define(:version => 0) do
create_table :hickwalls, :force => true do |t|
t.string :name
t.string :last_squawk
t.datetime :last_squawked_at
end
create_table :wickwalls, :force => true do |t|
t.string :name
t.string :last_tweet
t.datetime :last_tweeted_at
end
end
# File: vendor/plugins/yaffle/test/test_helper.rb
ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
require 'test/unit'
require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
db_adapter = ENV['DB']
# no db passed, try one of these fine config-free DBs before bombing.
db_adapter ||=
begin
require 'rubygems'
require 'sqlite'
'sqlite'
rescue MissingSourceFile
begin
require 'sqlite3'
'sqlite3'
rescue MissingSourceFile
end
end
if db_adapter.nil?
raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
end
ActiveRecord::Base.establish_connection(config[db_adapter])
load(File.dirname(__FILE__) + "/schema.rb")
require File.dirname(__FILE__) + '/../init.rb'
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
class Wickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at
end
----------------------------------------------

View File

@@ -1,103 +0,0 @@
== Add a `to_squawk` method to String ==
To update a core class you will have to:
* Write tests for the desired functionality.
* Create a file for the code you wish to use.
* Require that file from your 'init.rb'.
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 'init.rb'. The file you are going to add for this tutorial is 'lib/core_ext.rb'.
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:
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/test/core_ext_test.rb
require 'test/unit'
class CoreExtTest < Test::Unit::TestCase
# Replace this with your real tests.
def test_this_plugin
flunk
end
end
--------------------------------------------------------
Start off by removing the default test, and adding a require statement for your test helper.
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/test/core_ext_test.rb
require 'test/unit'
require File.dirname(__FILE__) + '/test_helper.rb'
class CoreExtTest < Test::Unit::TestCase
end
--------------------------------------------------------
Navigate to your plugin directory and run `rake test`:
--------------------------------------------------------
cd vendor/plugins/yaffle
rake test
--------------------------------------------------------
Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file 'lib/core_ext.rb' and re-run the tests. You should see a different error message:
--------------------------------------------------------
1.) Failure ...
No tests were specified
--------------------------------------------------------
Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word ``squawk!''. The test will look something like this:
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
class CoreExtTest < Test::Unit::TestCase
def test_string_should_respond_to_squawk
assert_equal true, "".respond_to?(:to_squawk)
end
def test_string_prepend_empty_strings_with_the_word_squawk
assert_equal "squawk!", "".to_squawk
end
def test_string_prepend_non_empty_strings_with_the_word_squawk
assert_equal "squawk! Hello World", "Hello World".to_squawk
end
end
--------------------------------------------------------
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
require "core_ext"
--------------------------------------------------------
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/lib/core_ext.rb
String.class_eval do
def to_squawk
"squawk! #{self}".strip
end
end
--------------------------------------------------------
When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly.
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:
--------------------------------------------------------
$ ./script/console
>> "Hello World".to_squawk
=> "squawk! Hello World"
--------------------------------------------------------
If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.

View File

@@ -0,0 +1,230 @@
== Preparation ==
=== Create the basic app ===
The examples in this guide require that you have a working rails application. To create a simple rails app execute:
------------------------------------------------
gem install rails
rails yaffle_guide
cd yaffle_guide
script/generate scaffold bird name:string
rake db:migrate
script/server
------------------------------------------------
Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing.
.Editor's note:
NOTE: 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.
=== Generate the plugin skeleton ===
Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also.
This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories.
Examples:
----------------------------------------------
./script/generate plugin yaffle
./script/generate plugin yaffle --with-generator
----------------------------------------------
To get more detailed help on the plugin generator, type `./script/generate plugin`.
Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now:
----------------------------------------------
./script/generate plugin yaffle --with-generator
----------------------------------------------
You should see the following output:
----------------------------------------------
create vendor/plugins/yaffle/lib
create vendor/plugins/yaffle/tasks
create vendor/plugins/yaffle/test
create vendor/plugins/yaffle/README
create vendor/plugins/yaffle/MIT-LICENSE
create vendor/plugins/yaffle/Rakefile
create vendor/plugins/yaffle/init.rb
create vendor/plugins/yaffle/install.rb
create vendor/plugins/yaffle/uninstall.rb
create vendor/plugins/yaffle/lib/yaffle.rb
create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
create vendor/plugins/yaffle/test/core_ext_test.rb
create vendor/plugins/yaffle/generators
create vendor/plugins/yaffle/generators/yaffle
create vendor/plugins/yaffle/generators/yaffle/templates
create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE
----------------------------------------------
To begin just change one thing - move 'init.rb' to 'rails/init.rb'.
=== Setup the plugin for testing ===
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.
To setup your plugin to allow for easy testing you'll need to add 3 files:
* A 'database.yml' file with all of your connection strings
* A 'schema.rb' file with your table definitions
* A test helper method that sets up the database
*vendor/plugins/yaffle/test/database.yml:*
----------------------------------------------
sqlite:
:adapter: sqlite
:dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
sqlite3:
:adapter: sqlite3
:dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
postgresql:
:adapter: postgresql
:username: postgres
:password: postgres
:database: yaffle_plugin_test
:min_messages: ERROR
mysql:
:adapter: mysql
:host: localhost
:username: root
:password: password
:database: yaffle_plugin_test
----------------------------------------------
For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:
*vendor/plugins/yaffle/test/schema.rb:*
[source, ruby]
----------------------------------------------
ActiveRecord::Schema.define(:version => 0) do
create_table :hickwalls, :force => true do |t|
t.string :name
t.string :last_squawk
t.datetime :last_squawked_at
end
create_table :wickwalls, :force => true do |t|
t.string :name
t.string :last_tweet
t.datetime :last_tweeted_at
end
create_table :woodpeckers, :force => true do |t|
t.string :name
end
end
----------------------------------------------
*vendor/plugins/yaffle/test/test_helper.rb:*
[source, ruby]
----------------------------------------------
ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
require 'test/unit'
require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
def load_schema
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
db_adapter = ENV['DB']
# no db passed, try one of these fine config-free DBs before bombing.
db_adapter ||=
begin
require 'rubygems'
require 'sqlite'
'sqlite'
rescue MissingSourceFile
begin
require 'sqlite3'
'sqlite3'
rescue MissingSourceFile
end
end
if db_adapter.nil?
raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
end
ActiveRecord::Base.establish_connection(config[db_adapter])
load(File.dirname(__FILE__) + "/schema.rb")
require File.dirname(__FILE__) + '/../rails/init.rb'
end
----------------------------------------------
Now whenever you write a test that requires the database, you can call 'load_schema'.
=== Run the plugin tests ===
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 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with:
*vendor/plugins/yaffle/test/yaffle_test.rb:*
[source, ruby]
----------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
class YaffleTest < Test::Unit::TestCase
load_schema
class Hickwall < ActiveRecord::Base
end
class Wickwall < ActiveRecord::Base
end
def test_schema_has_loaded_correctly
assert_equal [], Hickwall.all
assert_equal [], Wickwall.all
end
end
----------------------------------------------
To run this, go to the plugin directory and run `rake`:
----------------------------------------------
cd vendor/plugins/yaffle
rake
----------------------------------------------
You should see output like:
----------------------------------------------
/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
----------------------------------------------
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:
----------------------------------------------
rake DB=sqlite
rake DB=sqlite3
rake DB=mysql
rake DB=postgresql
----------------------------------------------
Now you are ready to test-drive your plugin!

View File

@@ -1,61 +0,0 @@
== Create a `squawk_info_for` view helper ==
Creating a view helper is a 3-step process:
* Add an appropriately named file to the 'lib' directory.
* Require the file and hooks in 'init.rb'.
* Write the tests.
First, create the test to define the functionality you want:
[source, ruby]
---------------------------------------------------------------
# File: vendor/plugins/yaffle/test/view_helpers_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
include YaffleViewHelper
class ViewHelpersTest < Test::Unit::TestCase
def test_squawk_info_for_should_return_the_text_and_date
time = Time.now
hickwall = Hickwall.new
hickwall.last_squawk = "Hello World"
hickwall.last_squawked_at = time
assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall)
end
end
---------------------------------------------------------------
Then add the following statements to init.rb:
[source, ruby]
---------------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
require "view_helpers"
ActionView::Base.send :include, YaffleViewHelper
---------------------------------------------------------------
Then add the view helpers file and
[source, ruby]
---------------------------------------------------------------
# File: vendor/plugins/yaffle/lib/view_helpers.rb
module YaffleViewHelper
def squawk_info_for(yaffle)
returning "" do |result|
result << yaffle.read_attribute(yaffle.class.yaffle_text_field)
result << ", "
result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s
end
end
end
---------------------------------------------------------------
You can also test this in script/console by using the `helper` method:
---------------------------------------------------------------
$ ./script/console
>> helper.squawk_info_for(@some_yaffle_instance)
---------------------------------------------------------------

View File

@@ -595,7 +595,7 @@ To list all active catchpoints use `catch`.
There are two ways to resume execution of an application that is stopped in the debugger:
* `continue` [line-specification] (or `c`): resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed. The optional argument line-specification allows you to specify a line number to set a one-time breakpoint which is deleted when that breakpoint is reached.
* `finish` [frame-number] (or `fin`): 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.
* `finish` [frame-number] (or `fin`): 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.
=== Editing
@@ -704,7 +704,7 @@ For further information on how to install Valgrind and use with Ruby, refer to l
There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:
* link:http://github.com/drnic/rails-footnotes/tree/master[Footnotes]: Every Rails page has footnotes that link give request information and link back to your source via TextMate.
* link:http://github.com/drnic/rails-footnotes/tree/master[Footnotes]: Every Rails page has footnotes that give request information and link back to your source via TextMate.
* link:http://github.com/ntalbott/query_trace/tree/master[Query Trace]: Adds query origin tracing to your logs.
* link:http://github.com/dan-manges/query_stats/tree/master[Query Stats]: A Rails plugin to track database queries.
* link:http://code.google.com/p/query-reviewer/[Query Reviewer]: 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.

View File

@@ -1,21 +1,17 @@
Rails Finders
=============
This guide is all about the +find+ method defined in +ActiveRecord::Base+, finding on associations, and associated goodness such as named scopes. You will learn how to be a find master.
This guide covers the +find+ method defined in +ActiveRecord::Base+, as well as other ways of finding particular instances of your models. By using this guide, you will be able to:
== In the beginning...
* Find records using a variety of methods and conditions
* Specify the order, retrieved attributes, grouping, and other properties of the found records
* Use eager loading to cut down on the number of database queries in your application
* Use dynamic finders
* Create named scopes to add custom finding behavior to your models
* Check for the existence of particular records
* Perform aggregate calculations on Active Record models
In the beginning there was SQL. SQL looked like this:
[source,sql]
-------------------------------------------------------
SELECT * FROM clients
SELECT * FROM clients WHERE id = '1'
SELECT * FROM clients LIMIT 0,1
SELECT * FROM clients ORDER BY id DESC LIMIT 0,1
-------------------------------------------------------
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.
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.
== The Sample Models
@@ -78,6 +74,8 @@ SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2))
Note that if you pass in a list of numbers that the result will be returned as an array, not as a single +Client+ object.
NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception.
If you wanted to find the first client you would simply type +Client.first+ and that would find the first client created in your clients table:
-------------------------------------------------------
@@ -124,13 +122,17 @@ Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.fin
== Conditions
The +find+ method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.
=== Pure String Conditions ===
If you'd like to add conditions to your find, you could just specify them in there, just like +Client.first(:conditions => "orders_count = '2'")+. This will find all clients where the +orders_count+ field's value is 2.
WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, +Client.first(:conditions => "name LIKE '%#{params[:name]}%'")+ is not safe. See the next section for the preferred way to handle conditions using an array.
=== Array Conditions ===
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.
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.
The reason for doing code like:
@@ -234,7 +236,7 @@ To select certain fields, you can use the select option like this: +Client.first
== Limit & Offset
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:
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:
[source, ruby]
-------------------------------------------------------
@@ -280,14 +282,14 @@ SELECT * FROM +orders+ GROUP BY date(created_at)
== Read Only
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 +Active Record::ReadOnlyRecord+ error. To set this option, specify it like this:
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 +Active Record::ReadOnlyRecord+ exception. To set this option, specify it like this:
[source, ruby]
-------------------------------------------------------
Client.first(:readonly => true)
-------------------------------------------------------
If you assign this record to a variable +client+, calling the following code will raise an ActiveRecord::ReadOnlyRecord:
If you assign this record to a variable +client+, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception:
[source, ruby]
-------------------------------------------------------
@@ -310,11 +312,11 @@ end
== Making It All Work Together
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.
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.
== Eager Loading
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 +Client.all(:include => :address)+. 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:
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 +Client.all(:include => :address)+. 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:
[source, sql]
-------------------------------------------------------
@@ -386,11 +388,11 @@ If you'd like to use your own SQL to find records a table you can use +find_by_s
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
-------------------------------------------------------
+find_by_sql+ provides you with a simple way of making custom calls to the database and retreiving instantiated objects.
+find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
== +select_all+ ==
+find_by_sql+ has a close relative called +select_all+. +select_all+ will retreive objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
+find_by_sql+ has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
[source, ruby]
-------------------------------------------------------
@@ -399,11 +401,15 @@ Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
== Working with Associations
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 +Client.find(params[:id]).orders.find_by_sent_and_received(true, false)+. Having this find method available on associations is extremely helpful when using nested controllers.
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 +Client.find(params[:id]).orders.find_by_sent_and_received(true, false)+. Having this find method available on associations is extremely helpful when using nested controllers.
== Named Scopes
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:
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.
=== Simple Named Scopes
Suppose want to find all clients who are male. You could use this code:
[source, ruby]
-------------------------------------------------------
@@ -412,7 +418,7 @@ class Client < ActiveRecord::Base
end
-------------------------------------------------------
And you could call it like +Client.males.all+ to get all the clients who are male. Please note that if you do not specify the +all+ on the end you will get a +Scope+ object back, not a set of records which you do get back if you put the +all+ on the end.
Then you could call +Client.males.all+ to get all the clients who are male. Please note that if you do not specify the +all+ on the end you will get a +Scope+ object back, not a set of records which you do get back if you put the +all+ on the end.
If you wanted to find all the clients who are active, you could use this:
@@ -423,7 +429,9 @@ class Client < ActiveRecord::Base
end
-------------------------------------------------------
You can call this new named_scope by doing +Client.active.all+ and this will do the same query as if we just used +Client.all(:conditions => ["active = ?", true])+. 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 +Client.active.first+.
You can call this new named_scope with +Client.active.all+ and this will do the same query as if we just used +Client.all(:conditions => ["active = ?", true])+. 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 +Client.active.first+.
=== Combining Named Scopes
If you wanted to find all the clients who are active and male you can stack the named scopes like this:
@@ -439,6 +447,8 @@ If you would then like to do a +all+ on that scope, you can. Just like an associ
Client.males.active.all(:conditions => ["age > ?", params[:age]])
-------------------------------------------------------
=== Runtime Evaluation of Named Scope Conditions
Consider the following code:
[source, ruby]
@@ -459,6 +469,8 @@ end
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.
=== Named Scopes with Multiple Models
In a named scope you can use +:include+ and +:joins+ options just like in find.
[source, ruby]
@@ -471,6 +483,8 @@ end
This method, called as +Client.active_within_2_weeks.all+, will return all clients who have placed orders in the past 2 weeks.
=== Arguments to Named Scopes
If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:
[source, ruby]
@@ -493,7 +507,9 @@ This will work with +Client.recent(2.weeks.ago).all+ and +Client.recent.all+, wi
Remember that named scopes are stackable, so you will be able to do +Client.recent(2.weeks.ago).unlocked.all+ to find all clients created between right now and 2 weeks ago and have their locked field set to false.
Finally, if you wish to define named scopes on the fly you can use the scoped method:
=== Anonymous Scopes
All Active Record models come with a named scope named +scoped+, which allows you to create anonymous scopes. For example:
[source, ruby]
-------------------------------------------------------
@@ -504,6 +520,15 @@ class Client < ActiveRecord::Base
end
-------------------------------------------------------
Anonymous scopes are most useful to create scopes "on the fly":
[source, ruby]
-------------------------------------------------------
Client.scoped(:conditions => { :gender => "male" })
-------------------------------------------------------
Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.
== Existence of Objects
If you simply want to check for the existence of the object there's a method called +exists?+. 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.
@@ -513,7 +538,7 @@ If you simply want to check for the existence of the object there's a method cal
Client.exists?(1)
-------------------------------------------------------
The above code will check for the existance of a clients table record with the id of 1 and return true if it exists.
The above code will check for the existence of a clients table record with the id of 1 and return true if it exists.
[source, ruby]
-------------------------------------------------------
@@ -630,8 +655,9 @@ Thanks to Mike Gunderloy for his tips on creating this guide.
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket]
* October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section.
* October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point.
* November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
* October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg
* October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg
* October 26, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
* October 22, 2008: Calculations complete, first complete draft by Ryan Bigg
* October 21, 2008: Extended named scope section by Ryan Bigg

View File

@@ -186,7 +186,7 @@ If you open this file in a new Rails application, you'll see a default database
==== Configuring a SQLite Database
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.
Rails comes with built-in support for link:http://www.sqlite.org/[SQLite], 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.
Here's the section of the default configuration file with connection information for the development environment:
@@ -480,7 +480,7 @@ This code sets the +@posts+ instance variable to an array of all posts in the da
TIP: For more information on finding records with Active Record, see link:../finders.html[Active Record Finders].
The +respond_to+ block handles both HTML and XML calls to this action. If you borwse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ 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 +app/view/posts/index.html.erb+:
The +respond_to+ block handles both HTML and XML calls to this action. If you browse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ 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 +app/view/posts/index.html.erb+:
[source, ruby]
-------------------------------------------------------

View File

@@ -877,6 +877,8 @@ When a partial is called with a pluralized collection, then the individual insta
With this change, you can access an instance of the +@products+ collection as the +item+ local variable within the partial.
TIP: Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by +_counter+. For example, if you're rendering +@products+, within the partial you can refer to +product_counter+ to tell you how many times the partial has been rendered.
You can also specify a second partial to be rendered between instances of the main partial by using the +:spacer_template+ option:
[source, html]
@@ -933,6 +935,7 @@ In this case, Rails will use the customer or employee partials as appropriate fo
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket]
* November 9, 2008: Added partial collection counter by link:../authors.html#mgunderloy[Mike Gunderloy]
* November 1, 2008: Added +:js+ option for +render+ by link:../authors.html#mgunderloy[Mike Gunderloy]
* October 16, 2008: Ready for publication by link:../authors.html#mgunderloy[Mike Gunderloy]
* October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)

View File

@@ -1,6 +1,6 @@
[[foreign_key]]
== Active Record and Referential Integrity ==
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.
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.
Validations such as `validates_uniqueness_of` are one way in which models can enforce data integrity. The `:dependent` 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.

View File

@@ -7,7 +7,7 @@ There is no need (and it is error prone) to deploy a new instance of an app by r
For example, this is how the test database is created: the current development database is dumped (either to `schema.rb` or `development.sql`) and then loaded into the test database.
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 http://agilewebdevelopment.com/plugins/annotate_models[annotate_models] plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.
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 http://agilewebdevelopment.com/plugins/annotate_models[annotate_models] plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.
=== Types of schema dumps ===
There are two ways to dump the schema. This is set in `config/environment.rb` by the `config.active_record.schema_format` setting, which may be either `:sql` or `:ruby`.

View File

@@ -229,6 +229,8 @@ Although the conventions of RESTful routing are likely to be sufficient for many
* +:path_names+
* +:path_prefix+
* +:name_prefix+
* +:only+
* +:except+
You can also add additional routes via the +:member+ and +:collection+ options, which are discussed later in this guide.
@@ -400,6 +402,30 @@ This combination will give you route helpers such as +photographer_photos_path+
NOTE: You can also use +:name_prefix+ with non-RESTful routes.
==== Using :only and :except
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 +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option specifies that only certain routes should be generated:
[source, ruby]
-------------------------------------------------------
map.resources :photos, :only => [:index, :show]
-------------------------------------------------------
With this declaration, a +GET+ request to +/photos+ would succeed, but a +POST+ request to +/photos+ (which would ordinarily be routed to the create action) will fail.
The +:except+ option specifies a route or list of routes that should _not_ be generated:
[source, ruby]
-------------------------------------------------------
map.resources :photos, :except => :destroy
-------------------------------------------------------
In this case, all of the normal routes except the route for +destroy+ (a +DELETE+ request to +/photos/_id_+) will be generated.
In addition to an action or a list of actions, you can also supply the special symbols +:all+ or +:none+ to the +:only+ and +:except+ options.
TIP: If your application has many RESTful routes, using +:only+ and +:accept+ to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
=== Nested Resources
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
@@ -535,17 +561,7 @@ This will enable recognition of (among others) these routes:
/photos/3 ==> photo_path(3)
-------------------------------------------------------
With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you _can_ 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:
-------------------------------------------------------
/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)
-------------------------------------------------------
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.
If you like, you can combine shallow nesting with the +:has_one+ and +:has_many+ options:
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 +:has_one+ and +:has_many+ options:
[source, ruby]
-------------------------------------------------------

View File

@@ -11,18 +11,17 @@ This guide won't teach you to write a Rails application; it assumes basic famili
== Why Write Tests for your Rails Applications? ==
* 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.
* Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
* By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
* 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.
* By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
* Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
== Before you Start Writing Tests ==
== Introduction to Testing ==
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.
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.
=== The 3 Environments ===
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.
Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups:
@@ -55,11 +54,11 @@ For good tests, you'll need to give some thought to setting up test data. In Rai
==== What Are Fixtures? ====
_Fixtures_ 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: *YAML* or *CSV*.
_Fixtures_ 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: *YAML* or *CSV*. In this guide we will use *YAML* which is the preferred format.
You'll find fixtures under your +test/fixtures+ directory. When you run +script/generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory.
==== YAML the Camel is a Mammal with Enamel ====
==== YAML ====
YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in +users.yml+).
@@ -69,13 +68,11 @@ Here's a sample YAML fixture file:
---------------------------------------------
# low & behold! I am a YAML comment!
david:
id: 1
name: David Heinemeier Hansson
birthday: 1979-10-15
profession: Systems development
steve:
id: 2
name: Steve Ross Kellock
birthday: 1974-09-27
profession: guy with keyboard
@@ -83,55 +80,24 @@ steve:
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.
==== Comma Seperated ====
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 'test/fixtures' directory, but these end with the +.csv+ file extension (as in +celebrity_holiday_figures.csv+).
A CSV fixture looks like this:
--------------------------------------------------------------
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"
--------------------------------------------------------------
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:
* Leading and trailing spaces are trimmed from each value when it is imported
* If you use a comma as data, the cell must be encased in quotes
* If you use a quote as data, you must escape it with a 2nd quote
* Don't use blank lines
* Nulls can be defined by including no data between a pair of commas
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:
* +celebrity-holiday-figures-1+
* +celebrity-holiday-figures-2+
* +celebrity-holiday-figures-3+
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.
==== ERb'in It Up ====
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.
I'll demonstrate with a YAML file:
[source, ruby]
--------------------------------------------------------------
<% earth_size = 20 -%>
mercury:
id: 1
size: <%= earth_size / 50 %>
brightest_on: <%= 113.days.ago.to_s(:db) %>
venus:
id: 2
size: <%= earth_size / 2 %>
brightest_on: <%= 67.days.ago.to_s(:db) %>
mars:
id: 3
size: <%= earth_size - 69 %>
brightest_on: <%= 13.days.from_now.to_s(:db) %>
--------------------------------------------------------------
Anything encased within the
@@ -141,7 +107,7 @@ Anything encased within the
<% %>
------------------------
tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively.
tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The +brightest_on+ attribute will also be evaluated and formatted by Rails to be compatible with the database.
==== Fixtures in Action ====
@@ -164,9 +130,7 @@ users(:david)
users(:david).id
--------------------------------------------------------------
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!
Now you can get at the methods only available to that class.
Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
[source, ruby]
--------------------------------------------------------------
@@ -177,14 +141,18 @@ david = users(:david).find
email(david.girlfriend.email, david.location_tonight)
--------------------------------------------------------------
== Unit Testing Your Models ==
== Unit Testing your Models ==
In Rails, unit tests are what you write to test your models.
When you create a model using +script/generate+, among other things it creates a test stub in the +test/unit+ folder, as well as a fixture for the model:
For this guide we will be using Rails _scaffolding_. 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.
NOTE: For more information on Rails _scaffolding_, refer to link:../getting_started_with_rails.html[Getting Started with Rails]
When you use +script/generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
-------------------------------------------------------
$ script/generate model Post
$ script/generate scaffold post title:string body:text
...
create app/models/post.rb
create test/unit/post_test.rb
@@ -243,6 +211,36 @@ This line of code is called an _assertion_. An assertion is a line of code that
Every test contains one or more assertions. Only when all the assertions are successful the test passes.
=== Preparing you Application for Testing ===
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:
[source, shell]
-------------------------------------------------------
$ rake db:migrate
...
$ rake db:test:load
-------------------------------------------------------
Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run +db:test:prepare+ as it first checks for pending migrations and warns you appropriately.
NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
==== Rake Tasks for Preparing you Application for Testing ==
[grid="all"]
--------------------------------`----------------------------------------------------
Tasks Description
------------------------------------------------------------------------------------
+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.
------------------------------------------------------------------------------------
TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
=== Running Tests ===
Running a test is as simple as invoking the file containing the test cases through Ruby:
@@ -277,65 +275,90 @@ Finished in 0.023513 seconds.
The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case:
To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
[source,ruby]
--------------------------------------------------
def test_should_have_atleast_one_post
post = Post.find(:first)
assert_not_nil post
def test_should_not_save_post_without_title
post = Post.new
assert !post.save
end
--------------------------------------------------
If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:
Let us run this newly added test.
-------------------------------------------------------
$ ruby unit/post_test.rb
$ 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
1 tests, 1 assertions, 1 failures, 0 errors
-------------------------------------------------------
In the output, +F+ denotes a failure. You can see the corresponding trace shown under +1)+ 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:
[source,ruby]
--------------------------------------------------
def test_should_have_atleast_one_post
post = Post.find(:first)
assert_not_nil post, "Should not be nil as Posts table should have atleast one post"
def test_should_not_save_post_without_title
post = Post.new
assert !post.save, "Saved the post without a title"
end
--------------------------------------------------
Running this test shows the friendlier assertion message:
-------------------------------------------------------
$ ruby unit/post_test.rb
$ 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
-------------------------------------------------------
Now to get this test to pass we can add a model level validation for the _title_ field.
[source,ruby]
--------------------------------------------------
class Post < ActiveRecord::Base
validates_presence_of :title
end
--------------------------------------------------
Now the test should pass. Let us verify by running the test again:
-------------------------------------------------------
$ 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
-------------------------------------------------------
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 _Test-Driven Development_ (TDD).
TIP: Many Rails developers practice _Test-Driven Development_ (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 link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
To see how an error gets reported, here's a test containing an error:
[source,ruby]
@@ -350,29 +373,21 @@ end
Now you can see even more output in the console from running the tests:
-------------------------------------------------------
$ ruby unit/post_test.rb
$ ruby unit/post_test.rb -n test_should_report_error
Loaded suite unit/post_test
Started
FE.
Finished in 0.108389 seconds.
E
Finished in 0.195757 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.
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
1 tests, 0 assertions, 0 failures, 1 errors
-------------------------------------------------------
Notice the 'E' in the output. It denotes a test with error.
@@ -383,8 +398,6 @@ NOTE: The execution of each test method stops as soon as any error or a assertio
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.
TIP: Many Rails developers practice _test-driven development_ (TDD), in which the tests are written _before_ 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 link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
=== Assertions Available ===
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.
@@ -454,32 +467,9 @@ You should test for things such as:
* was the correct object stored in the response template?
* was the appropriate message displayed to the user in the view
When you use +script/generate+ to create a controller, it automatically creates a functional test for that controller in +test/functional+. For example, if you create a post controller:
Now that we have used Rails scaffold generator for our +Post+ resource, it has already created the controller code and functional tests. You can take look at the file +posts_controller_test.rb+ in the +test/functional+ directory.
[source, shell]
-------------------------------------------------------
$ script/generate controller post
...
create app/controllers/post_controller.rb
create test/functional/post_controller_test.rb
...
-------------------------------------------------------
Now if you take a look at the file +posts_controller_test.rb+ in the +test/functional+ directory, you should see:
[source,ruby]
--------------------------------------------------
require 'test_helper'
class PostsControllerTest < ActionController::TestCase
# Replace this with your real tests.
def test_truth
assert true
end
end
--------------------------------------------------
Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:
Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
[source,ruby]
--------------------------------------------------
@@ -513,6 +503,23 @@ Another example: Calling the +:view+ action, passing an +id+ of 12 as the +param
get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
--------------------------------------------------
NOTE: If you try running +test_should_create_post+ test from +posts_controller_test.rb+ it will fail on account of the newly added model level validation and rightly so.
Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
[source,ruby]
--------------------------------------------------
def test_should_create_post
assert_difference('Post.count') do
post :create, :post => { :title => 'Some title'}
end
assert_redirected_to post_path(assigns(:post))
end
--------------------------------------------------
Now you can try running all the tests and they should pass.
=== Available Request Types for Functional Tests ===
If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 5 request types supported in Rails functional tests:
@@ -756,6 +763,130 @@ class UserFlowsTest < ActionController::IntegrationTest
end
--------------------------------------------------
== Rake Tasks for Running your Tests ==
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.
[grid="all"]
--------------------------------`----------------------------------------------------
Tasks Description
------------------------------------------------------------------------------------
+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_+)
------------------------------------------------------------------------------------
== Brief Note About Test::Unit ==
Ruby ships with a boat load of libraries. One little gem of a library is +Test::Unit+, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in +Test::Unit::Assertions+. The class +ActiveSupport::TestCase+ which we have been using in our unit and functional tests extends +Test::Unit::TestCase+ that it is how we can use all the basic assertions in our tests.
NOTE: For more information on +Test::Unit+, refer to link:http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/[test/unit Documentation]
== Setup and Teardown ==
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 +Posts+ controller:
[source,ruby]
--------------------------------------------------
require 'test_helper'
class PostsControllerTest < ActionController::TestCase
# called before every single test
def setup
@post = posts(:one)
end
# called after every single test
def teardown
# as we are re-initializing @post before every test
# setting it to nil here is not essential but I hope
# you understand how you can use the teardown method
@post = nil
end
def test_should_show_post
get :show, :id => @post.id
assert_response :success
end
def test_should_destroy_post
assert_difference('Post.count', -1) do
delete :destroy, :id => @post.id
end
assert_redirected_to posts_path
end
end
--------------------------------------------------
Above, the +setup+ method is called before each test and so +@post+ is available for each of the tests. Rails implements +setup+ and +teardown+ as ActiveSupport::Callbacks. Which essentially means you need not only use +setup+ and +teardown+ as methods in your tests. You could specify them by using:
* a block
* a method (like in the earlier example)
* a method name as a symbol
* a lambda
Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
[source,ruby]
--------------------------------------------------
require '../test_helper'
class PostsControllerTest < ActionController::TestCase
# called before every single test
setup :initialize_post
# called after every single test
def teardown
@post = nil
end
def test_should_show_post
get :show, :id => @post.id
assert_response :success
end
def test_should_update_post
put :update, :id => @post.id, :post => { }
assert_redirected_to post_path(assigns(:post))
end
def test_should_destroy_post
assert_difference('Post.count', -1) do
delete :destroy, :id => @post.id
end
assert_redirected_to posts_path
end
private
def initialize_post
@post = posts(:one)
end
end
--------------------------------------------------
== Testing Routes ==
Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default +show+ action of +Posts+ controller above should look like:
[source,ruby]
--------------------------------------------------
def test_should_route_to_post
assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
end
--------------------------------------------------
== Testing Your Mailers ==
Testing mailer classes requires some specific tools to do a thorough job.
@@ -845,30 +976,6 @@ class UserControllerTest < ActionController::TestCase
end
----------------------------------------------------------------
== Rake Tasks for Testing
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.
[grid="all"]
--------------------------------`----------------------------------------------------
Tasks Description
------------------------------------------------------------------------------------
+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.
------------------------------------------------------------------------------------
TIP: You can see all these rake task and their descriptions by running +rake --tasks --describe+
== Other Testing Approaches
The built-in +test/unit+ 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:
@@ -882,6 +989,7 @@ The built-in +test/unit+ based testing is not the only way to test Rails applica
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8[Lighthouse ticket]
* November 13, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)
* October 14, 2008: Edit and formatting pass by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
* October 12, 2008: First draft by link:../authors.html#asurve[Akashay Surve] (not yet approved for publication)
* October 12, 2008: First draft by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)