<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog - ShiftEleven &#187; Ruby on Rails</title>
	<atom:link href="http://shifteleven.com/articles/category/ruby-on-rails/feed" rel="self" type="application/rss+xml" />
	<link>http://shifteleven.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Sat, 19 Sep 2009 11:19:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0-alpha</generator>
		<item>
		<title>Making ActiveRecord faster by NOT indexing</title>
		<link>http://shifteleven.com/articles/2008/04/29/making-activerecord-faster-by-not-indexing</link>
		<comments>http://shifteleven.com/articles/2008/04/29/making-activerecord-faster-by-not-indexing#comments</comments>
		<pubDate>Tue, 29 Apr 2008 16:55:14 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[ActiveRecord]]></category>
		<category><![CDATA[indexing]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[singletableinheritance]]></category>

		<guid isPermaLink="false">http://shifteleven.com/?p=64</guid>
		<description><![CDATA[Usually one of the first things I read about on how to speed up ActiveRecord is to index my columns to speed up the lookup of items.  &#8220;Of course!&#8221;  But could indexing too much be harmful
Essentially, if your column is an enum, then indexing it could actually cause MySQL to do more work. [...]]]></description>
			<content:encoded><![CDATA[<p>Usually one of the first things I read about on how to speed up ActiveRecord is to index my columns to speed up the lookup of items.  &#8220;Of course!&#8221;  <a href="http://www.mysqlperformanceblog.com/2007/08/28/do-you-always-need-index-on-where-column/?">But could indexing too much be harmful</a></p>
<p>Essentially, if your column is an enum, then indexing it could actually cause MySQL to do more work.  Why?  Because the data set is so large, the MySQL ends up doing a full scan.  So things like keeping track if something is active (1 or 0) then you can expect indexing to hurt.</p>
<p>So how does this effect ActiveRecord?  Well, if you&#8217;re keeping track of whether a user is active or not you would not want to index that column alone.  Nor would you want to index a <code>type</code> column if you were using single table inheritance, again, because there isn&#8217;t a lot of variance in the type.</p>
<p>So make sure that you index the right things, like IDs and leave the enum-like columns alone.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2008/04/29/making-activerecord-faster-by-not-indexing/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RailsForge Needs Your Help</title>
		<link>http://shifteleven.com/articles/2007/07/04/railsforge-needs-your-help</link>
		<comments>http://shifteleven.com/articles/2007/07/04/railsforge-needs-your-help#comments</comments>
		<pubDate>Wed, 04 Jul 2007 19:59:01 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/articles/2007/07/04/railsforge-needs-your-help</guid>
		<description><![CDATA[RailsForge is hosting a survey to see what you, the Rails community, would like in a site for rails gems and plugin management.
So if you have some free time, please take the survey to help this project turn into something that you actually want to use :)
]]></description>
			<content:encoded><![CDATA[<p><a href="http://railsforge.com">RailsForge</a> is hosting a survey to see what you, the Rails community, would like in a site for rails gems and plugin management.</p>
<p>So if you have some free time, please take <a href="http://railsforge.com">the survey</a> to help this project turn into something that you actually want to use :)</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2007/07/04/railsforge-needs-your-help/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Customize Your Rake Files</title>
		<link>http://shifteleven.com/articles/2007/03/05/customize-your-rake-files</link>
		<comments>http://shifteleven.com/articles/2007/03/05/customize-your-rake-files#comments</comments>
		<pubDate>Tue, 06 Mar 2007 00:07:15 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[rake]]></category>
		<category><![CDATA[rcov]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/?p=27</guid>
		<description><![CDATA[Rcov is a handy tool to make sure that your tests have at least run every line of code in your application.  This is very useful if you have forgotten to write a test for a method, or if inside of a method, you forgot to test a conditional statement.  Because I find [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://eigenclass.org/hiki.rb?rcov">Rcov</a> is a handy tool to make sure that your tests have at least run every line of code in your application.  This is very useful if you have forgotten to write a test for a method, or if inside of a method, you forgot to test a conditional statement.  Because I find this handy, I incorporate the <a href="http://blog.codahale.com/2006/05/26/rails-plugin-rails_rcov/">rcov plugin</a> in my rails applications.</p>
<p>Running <code>rake test:functionals:rcov</code>, my report shows me a long list of items, some of which I don&#8217;t want to see.  I don&#8217;t want to see the coverage of my models in the report.  I should get that report by running <code>rake test:units:rcov</code>.  Luckily, the plugin allows for me to set arguments like <code>SHOW_ONLY="app/models"</code>.  But get this, I&#8217;m lazy and I don&#8217;t want to type that argument let alone remember it every time I want to run the rcov tests. What to do?</p>
<p><span id="more-27"></span></p>
<h3>Rake It Up</h3>
<p>The options are simply environment variables.  By using <code>rake</code>, we can create some tasks that set these environment variables.  So here&#8217;s what mine looks like:</p>
<pre class="ruby" title="code">task :default_rcov_params_for_units do
  RCOV_PARAMS = ENV['RCOV_PARAMS'] = "--sort=coverage"
  SHOW_ONLY = ENV['SHOW_ONLY'] = "app/models|lib|app/concerns|app/helpers"
end

task :default_rcov_params_for_functionals do
  RCOV_PARAMS = ENV['RCOV_PARAMS'] = "--sort=coverage"
  SHOW_ONLY = ENV['SHOW_ONLY'] = "app/controllers"
end</pre>
<p>That means now I can do something like <code>rake default_rcov_params_for_units test:units:rcov</code>.  Good, but there is better.  We can have <code>default_rcov_params_for_units</code> become a prerequisite for test:units:rcov.  That will make it happen automagically.</p>
<pre class="ruby" title="code">namespace :test do
  namespace :units do
    desc 'With RCOV_PARAMS="--sort=coverage" SHOW_ONLY="app/models|lib|app/concerns|app/helpers"'
    task :rcov =&gt; [:default_rcov_params_for_units]
  end

  desc 'With RCOV_PARAMS="--sort=coverage" SHOW_ONLY="app/controllers"'
  namespace :functionals do
    task :rcov =&gt; [:default_rcov_params_for_functionals]
  end
end</pre>
<h3>Follow Up</h3>
<p>Tada! That was easy.  This is one example of customizing your rake profile.  Don&#8217;t be <a href="http://errtheblog.com/post/33">afraid to try other methods</a> as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2007/03/05/customize-your-rake-files/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Blocks and Helpers, a Lovely Combination</title>
		<link>http://shifteleven.com/articles/2007/01/22/blocks-and-helpers-a-lovely-combination</link>
		<comments>http://shifteleven.com/articles/2007/01/22/blocks-and-helpers-a-lovely-combination#comments</comments>
		<pubDate>Tue, 23 Jan 2007 01:49:36 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[block]]></category>
		<category><![CDATA[DRY]]></category>
		<category><![CDATA[helper]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/?p=25</guid>
		<description><![CDATA[Blocks rock and I couldn&#8217;t agree more.  The functional programming aspect of ruby has started to interest me more and more.  Blocks are used all over the place, with respond_to, collect, returning and ActionView::Helpers::FormHelper#form_for.
Sometimes, a design requires a little extra markup, perhaps something to get that rounded corner to work or what-have you. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://weblog.jamisbuck.org/2007/1/19/blocks-rock">Blocks rock</a> and I couldn&#8217;t agree more.  The <a href="http://tech.rufy.com/2006/11/functional-programming-in-ruby.html">functional programming aspect of ruby</a> has started to interest me more and more.  Blocks are used all over the place, with <a href="http://api.rubyonrails.com/classes/ActionController/MimeResponds/InstanceMethods.html#M000080,"><code>respond_to</code></a>, <a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M003163,"><code>collect</code></a>, <a href="http://errtheblog.com/post/29,"><code>returning</code></a> and <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/FormHelper.html#M000491."><code>ActionView::Helpers::FormHelper#form_for</code></a><code>.</code></p>
<p>Sometimes, a design requires a little extra markup, perhaps something to get that rounded corner to work or what-have you.  Now let&#8217;s say this piece of code requires certain classes, a certain kind of structure, including a tile, and has to be used in many places, something like a sidebar piece.  Instead of copying and pasting this structure over and over, you can use a helper to make you life easier, and if you combine it with a block, it will just feel even more painless.</p>
<p><span id="more-25"></span></p>
<h3>The Setup</h3>
<pre class="html" title="code">&lt;div class="sidebar"&gt;
  &lt;div class="bottom"&gt;
    &lt;h3&gt;Title&lt;/h3&gt;
    &lt;div class="body"&gt;
      &lt;p&gt;Some Content&lt;/p&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<p>There are two elements which must change; the title and the contents of the body.  The title should simply be just some text that goes in between the <code>h3</code> tag.  The contents of the body could be anything, in this case, it is the paragraph tag and everything inside.</p>
<h3>Creating a Helper without a Block</h3>
<p>Since we have these two varying things, we could create a helper method to encapsulate our structure.  The first parameter of the helper will be the title while the second parameter will be the contents of the body.</p>
<pre class="ruby" title="code">def sidebar(title, body)
  content_tag(
    'div',
    content_tag(
      'div',
      content_tag('h3', title) + content_tag('div', body, :class =&gt; 'body'),
      :class =&gt; 'bottom'
    ),
    :class =&gt; 'sidebar'
  )
end</pre>
<p>That looks pretty easy.  Now let&#8217;s look at the interface for this helper</p>
<pre class="html" title="code">&lt;%= sidebar('Hello World',
  '&lt;p&gt;It is one of these "Hello World" things again.&lt;/p&gt;') %&gt;</pre>
<p>Not too shabby, but what if we wanted to do an unordered list?</p>
<pre class="ruby" title="code">&lt;%= sidebar(
  'Hello World',
  '&lt;ul&gt;' +
    '&lt;li&gt;Item&lt;/li&gt;' +
    '&lt;li&gt;Item&lt;/li&gt;' +
    '&lt;li&gt;Item&lt;/li&gt;' +
  '&lt;/ul&gt;'
) %&gt;</pre>
<p>This feels pretty clunky and <a href="http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/">ERB</a> is completely ignored.  Instead of this procedural way of thinking, why not see what a block can do for us?</p>
<h3>Creating a Helper +with+ a Block</h3>
<p>For this to work, we will still need the first parameter to be the title, but the body will be passed in as a block to be processed from within our helper.  The block we create will be ERB code, this will feel more natural to the person who has to implement the code.  The magic to get this done comes from the <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/TextHelper.html#M000611"><code>concat</code></a> method of <code>ActionView::Helpers::TextHelper</code> module.</p>
<pre class="ruby" title="code">def sidebar(title, &amp;block)
  raise ArgumentError, "Missing block" unless block_given?

  start = &lt;&lt;-END
    &lt;div class="sidebar"&gt;
      &lt;div class="bottom"&gt;
        &lt;h3&gt;#{title}&lt;/h3&gt;
        &lt;div class="body"&gt;
  END
  concat(start, block.binding)

  block.call

  end = &lt;&lt;-END
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  END
  concat(end, block.binding)

end</pre>
<p>This may look slightly odd, but I assure you, the interface makes up for it.</p>
<pre class="html" title="code">&lt;% sidebar('Hello World') do %&gt;
  &lt;p&gt;And now back to the way I was doing things before&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;Item&lt;/li&gt;
    &lt;li&gt;Item&lt;/li&gt;
    &lt;li&gt;Item&lt;/li&gt;
  &lt;/ul&gt;
&lt;% end %&gt;</pre>
<h3>The Benefits</h3>
<ul>
<li>The implementation code is more readable</li>
<li>It gives you one place to make your common edits</li>
<li>It keeps your code <a href="http://www.artima.com/intv/dry.html">DRY(don&#8217;t repeat yourself)</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2007/01/22/blocks-and-helpers-a-lovely-combination/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Trusting in Exceptions To Do What They Do</title>
		<link>http://shifteleven.com/articles/2006/12/03/trusting-in-exceptions-to-do-what-they-do</link>
		<comments>http://shifteleven.com/articles/2006/12/03/trusting-in-exceptions-to-do-what-they-do#comments</comments>
		<pubDate>Sun, 03 Dec 2006 23:22:35 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[ActiveRecord]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[RecordNotFound]]></category>
		<category><![CDATA[rescue]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/?p=20</guid>
		<description><![CDATA[Nobody likes to see exceptions when running an application;  it means something went wrong and you should have been on top of it.  But with that, often times I find people will write code to prevent exceptions rather than just allowing them to occur and then using it in their favor.
Take this bit [...]]]></description>
			<content:encoded><![CDATA[<p>Nobody likes to see exceptions when running an application;  it means something went wrong and you should have been on top of it.  But with that, often times I find people will write code to prevent exceptions rather than just allowing them to occur and then using it in their favor.</p>
<p>Take this bit of ruby code in a rails controller as an example:</p>
<pre class="ruby" title="code">class ArticlesController &lt; ApplicationController
  def show
    @article = Article.find(params[:id])
  end
end</pre>
<p>That&#8217;s pretty solid, but what happens if someone passes in an ID that does not exist?  Well in rails&#8217; production mode, it would return a <a href="http://en.wikipedia.org/wiki/404_error.">404 error</a></p>
<p>Makes sense!  That article doesn&#8217;t exist, so it can&#8217;t be found.  I have dabbled with a little SEO(Search Engine Optimization) and usability and just a 404 isn&#8217;t cutting it for me.  I think we can redirect our user back on a right track.  For one, we know the user is trying to read an article, so why not redirect the user to a list of all the articles and give them a little warning?</p>
<p><span id="more-20"></span></p>
<h3>Solution One</h3>
<p>First check that the article exists, and if not, redirect the user to the index page.</p>
<pre class="ruby" title="code">def show
  if Article.exists?(params[:id])
    @article = Article.find(params[:id])
  else
    flash[:error] = 'That article does not exist'
    redirect_to :action =&gt; 'index'
  end
end</pre>
<p>While this works, this requires two queries to our database; one to check it&#8217;s existence and one to load it.  I think there is a better way, and its secret is to go with the flow of the code.</p>
<h3>Solution Two</h3>
<p>One thing<br />
<a href="http://weblog.jamisbuck.org/2006/11/20/under-the-hood-activerecord-base-find-part-2">ActiveRecord::Base#find</a> does do is raise an exception when it cannot find anything, an ActiveRecord::RecordNotFound exception.  We can use this bit of knowledge to re-write that method to something a little simpler by trusting it to throw an exception and then for us to rescue it.</p>
<pre class="ruby" title="code">def show
  @article = Article.find(params[:id])
rescue ActiveRecord::RecordNotFound
  flash[:error] = 'That article does not exist'
  redirect_to :action =&gt; 'index'
end</pre>
<p>One call to the database and fewer lines of code (not a lot, but still).  This time, that nasty little error has been used in our favor; but  one mustn&#8217;t get lazy when using <code>rescue</code> statements.</p>
<h3>Don&#8217;t Get Lazy</h3>
<p>Notice that I used the constant <code>ActiveRecord::RecordNotFound</code> with the statement.  Sure, I could have just written <code>rescue</code>, but that hurts us in two ways.  First, it becomes less readable without it.  Having the <code>RecordNotFound</code> is pretty obvious as to the reason we are executing that statement.  Secondly, it can introduce unwanted side effects.</p>
<pre class="ruby" title="code">def show
  @article = Article.find(params[:id])
  some_illegal_operation
rescue
  flash[:error] = 'That article does not exist'
  redirect_to :action =&gt; 'index'
end</pre>
<p>Whenever that method is called, it will always redirect the user to the index page with that error message.  Because we&#8217;ve rescued all errors, we&#8217;re not getting any notice about how our <code>some_illegal_operation</code> has caused us grief.  This makes debugging and management harder.</p>
<p>The lesson being, don&#8217;t be lazy in those rescues.  Try to avoid a blanket rescue statement if you can.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/12/03/trusting-in-exceptions-to-do-what-they-do/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>DRYing Up respond_to</title>
		<link>http://shifteleven.com/articles/2006/11/26/drying-up-respond_to</link>
		<comments>http://shifteleven.com/articles/2006/11/26/drying-up-respond_to#comments</comments>
		<pubDate>Sun, 26 Nov 2006 23:34:58 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[respond_to]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/?p=19</guid>
		<description><![CDATA[Now that that release candidate for rails 1.2 is out, people are going to have even more reasons to use the respond_to method in their controller methods.  With that, there may come some unsettling feeling that you&#8217;re just repeating yourself over and over again.
def index
  @articles = Article.find(:all)
  respond_to do &#124;format&#124;
  [...]]]></description>
			<content:encoded><![CDATA[<p>Now that that <a href="http://blog.rubyonrails.org/2006/11/23/rails-1-2-release-candidate-1">release candidate for rails 1.2</a> is out, people are going to have even more reasons to use the <code>respond_to</code> method in their controller methods.  With that, there may come some unsettling feeling that you&#8217;re just repeating yourself over and over again.</p>
<pre class="ruby" title="code">def index
  @articles = Article.find(:all)
  respond_to do |format|
    format.html
    format.xml { render :xml =&gt; @articles.to_xml }
  end
end

def show
  @article = Article.find(params[:id])
  respond_to do |format|
    format.html
    format.xml { render :xml =&gt; @article.to_xml }
  end
end</pre>
<p>If we want to use the <code>respond_to</code>, we have to make sure it&#8217;s in all of our methods.  Wouldn&#8217;t it be easier to just do something like this?</p>
<pre class="ruby" title="code">def index
  @articles = Article.find(:all)
  format.html
  format.xml { render :xml =&gt; @articles.to_xml }
end</pre>
<p>Doing it this way, we don&#8217;t have to write 2 extra lines per method, and we don&#8217;t increase our indentation.  While that&#8217;s not a huge thing, I still just don&#8217;t like to constantly write out those lines when I don&#8217;t have to when I think we can build something a little trickier.  <span id="more-19"></span></p>
<h3>The Breakdown</h3>
<p>In the simplified example I gave above, we have several things that we need to accomplish.  One is to wrap our methods with a <code>respond_to</code> by using <a href="http://www.rubycentral.com/book/classes.html."><code>alias_method</code></a> Well, it&#8217;s actually not that simple because <code>respond_to</code> is a block and we will need to do some trickery there.  Another task is we need to create a <code>format</code> method.  Since we won&#8217;t be calling <code>format</code> with a block parameter, we need to make a method which will do the dirty work for us.  Finally, we need to make a tweak to <code>ActionController::MimeResponders::Respond#respond</code> for some of the other things that we are doing.</p>
<h4>Adding <code>wrap_respond_to_in</code> to our ApplicationController</h4>
<p>To start things off, we need to make a class method, which I have dubbed <code>wrap_respond_to_in</code> (I would <strong>love</strong> suggestions for names here).</p>
<pre class="ruby" title="code">class &lt;&lt; self
  def wrap_respond_to_in(*actions)
    if actions.include?(:all)
      # Also remove #rescue_action because this gets set in tests. Also include some of my friendly #find methods.
      actions = actions + self.public_instance_methods - ApplicationController.public_instance_methods - ['rescue_action'] - [:all]
      [:find_collection, :find_new, :find_member].each do |finder|
        actions &lt;&lt; finder if method_defined?(finder)
      end
    end

    # Returns the appropriate Responder format based on the action.
    define_method(:format) do
      @format.last rescue nil
    end

    for action in actions
      action = action.to_sym

      module_eval &lt;&lt;-END
        alias_method(:__#{action.to_i}__, :#{action.to_s})
        private :__#{action.to_i}__

        def #{action.to_s}(*args)
          result = nil      # This is the result of whatever method this wraps
          respond_to do |format|
            @format ||= []
            @format.push(format)
            result = __#{action.to_i}__(*args)
            @format.pop
          end
          return result
        end
      END
    end
  end
end</pre>
<p>Let&#8217;s break this down by section.  First things first, the method&#8217;s arguments should be a list of symbols for the names of the methods we would like to use our <code>respond_to</code> shorthand.  Because I would like to use this shorthand for all of my action methods, I have included the notion of sending <code>:all</code> as a parameter.  This will make sure that all of the public methods and some protected methods that I use (<code>find_member</code>, <code>find_collection</code>, and <code>find_new</code>).  Again, I like to keep things DRY(Don&#8217;t Repeat Yourself).  Next we define a method called <code>format</code>.  This will be an accessor to the last element of our <code>format</code> instance variable array.  More on this later.  After we have defined that, we need to loop through all of our methods that we want to use <code>respond_to</code>.  In each loop, we need to make an alias for our methods.  This is so that we can re-write the method, yet still keep a copy of the original code.  Next we overwrite the method.  As you can see here, this is where we put the <code>respond_to</code> block.  Now in this block, we have access to the <code>format</code> variable.  Next we push this value into our <code>format</code> instance variable.  The reasoning for using an array is to accommodate for a nested set of calls.  After we push <code>format</code> onto <code>format</code>, we then call our original method, which uses the shorthand and save that to to a variable.  Once that is done, we pop off the last value we put into the format@ variable, since we are done with it.  Finally, return the result of our original method.  This is the backbone for what we need to do.  Now we need to implement it.</p>
<h4>Tweaking ActionController::MimeResponds::Responder</h4>
<p>Because we now have assumed that all of our methods are going to use <code>respond_to</code>, we need to make a way out if for some reason we don&#8217;t need to use said method.  This would mean that our method exists without calling the <code>format</code> method.  In order to do that, we can use the following code:</p>
<pre class="ruby" title="code">module ActionController #:nodoc:
  module MimeResponds #:nodoc:
    class Responder
      alias_method :__respond_without_check_for_empty_order__, :respond
      private :__respond_without_check_for_empty_order__

      def respond
        return if @order.empty?
        __respond_and_check_for_empty_order__
      end
    end
  end
end</pre>
<p>We simply do a check to see if order is empty.  If so, that means our <code>format</code> method was never called, so we just simply need to exit out of the <code>respond</code> method.  I put this in my <code>lib</code> directory and make sure that my app requires this after rails has been loaded.</p>
<h4>Using <code>wrap_respond_to_in</code></h4>
<p>Quite simply all we need to do to use it is to call it, <strong>but we must do so after we have defined all of our methods for which we want to use this technique</strong></p>
<p>.</p>
<pre class="ruby" title="code">class Articles &lt; ApplicationController
  before_filter :find_member, :only =&gt; [:show]

  def show
    format.html
    format.xml { render :xml =&gt; @article.to_xml }
  end

  protected
    def find_member
      @article = Article.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      format.html do
        flash[:error] = "Article was not found"
        redirect_to articles_url
      end
      format.xml { head :status =&gt; 404 }
    end

    wrap_respond_to_in :all
end</pre>
<p>While this is not a complete controller, it does show you how to use it.</p>
<h3>Final Words</h3>
<p>There&#8217;s no reason to put a <code>respond_to</code> call in all of the methods when there is a way around it.  Once I figure out how to get SVN(subversion) working with <a href="http://www.dreamhost.com/,">Dreamhost</a> I am going to put this into a plugin for all to use.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/11/26/drying-up-respond_to/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Did You Know? Validating belongs_to Relationships</title>
		<link>http://shifteleven.com/articles/2006/11/08/did-you-know-validating-belongs_to-relationships</link>
		<comments>http://shifteleven.com/articles/2006/11/08/did-you-know-validating-belongs_to-relationships#comments</comments>
		<pubDate>Thu, 09 Nov 2006 01:41:52 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[belongs_to]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/articles/2006/11/08/did-you-know-validating-belongs_to-relationships</guid>
		<description><![CDATA[This is one of those things that is probably obvious to some, and just not known to some.  I was in that latter description up until a few minutes ago.  It&#8217;s that you can easily validate any belongs_to relationship by simply using valdiates_presence_of
.
class Comment &#60; ActiveRecord::Base
  belongs_to :article

  validates_presence_of :article
end
If you [...]]]></description>
			<content:encoded><![CDATA[<p>This is one of those things that is probably obvious to some, and just not known to some.  I was in that latter description up until a few minutes ago.  It&#8217;s that you can easily validate any <code>belongs_to</code> relationship by simply using <code>valdiates_presence_of</code></p>
<p>.</p>
<pre class="ruby" title="code">class Comment &lt; ActiveRecord::Base
  belongs_to :article

  validates_presence_of :article
end</pre>
<p>If you instantiate a new <code>Comment</code>, and don&#8217;t assign an <code>Article</code> to the comment instance, the record won&#8217;t save.  I have to say, that seemed pretty obvious.  But there is another interesting piece to this.  Say I passed the <code>article_id</code> in the <code>params</code> and tried to assign that to our instance</p>
<pre class="ruby" title="code">comment = Comment.new
comment.article_id = params[:article_id]</pre>
<p>If <code>article_id</code> corresponds to a real article in our database, then <code>comment.article</code> will have be assigned an <code>Article</code> with that <code>id</code>.  Now if <code>params[:article_id]</code> happens to be some id which doesn&#8217;t exist, like <code>99999999999</code>, then <code>comment.article</code> will be <code>nil</code> and thus the record fails validation.  This means that you don&#8217;t have to test for the existence of the <code>Article</code> against your records because rails will do this for you when it checks to see if <code>comment.article</code> is nil or not.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/11/08/did-you-know-validating-belongs_to-relationships/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Loading Your Rails Environment Into a Script</title>
		<link>http://shifteleven.com/articles/2006/10/08/loading-your-rails-environment-into-a-script</link>
		<comments>http://shifteleven.com/articles/2006/10/08/loading-your-rails-environment-into-a-script#comments</comments>
		<pubDate>Mon, 09 Oct 2006 03:08:52 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[script]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/articles/2006/10/08/loading-your-rails-environment-into-a-script</guid>
		<description><![CDATA[This is a fairly simple little tidbit, but still useful.  Sometimes I want to have a script for my rails application, like running some reports on the data.  There are two basic ways to do this: write a task(rake), or create a new ruby script file, like in the scripts directory.
If you want [...]]]></description>
			<content:encoded><![CDATA[<p>This is a fairly simple little tidbit, but still useful.  Sometimes I want to have a script for my rails application, like running some reports on the data.  There are two basic ways to do this: write a task(rake), or create a new ruby script file, like in the scripts directory.</p>
<p>If you want to do the latter, then there are two lines you my want to put at the top of your script.</p>
<pre class="ruby" title="code">ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'development'
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")</pre>
<p>The first line allows us to supply which environment we would like to run the script in.  Say the script is called <code>process.rb</code>, we could call the script like <code>./process.rb production</code> and now the environment is set to production.</p>
<p>The second line loads the environment file.  Now all of rails, your models, libraries, and plugins are available to you.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/10/08/loading-your-rails-environment-into-a-script/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Loading Fixtures in a Migration</title>
		<link>http://shifteleven.com/articles/2006/09/28/loading-fixtures-in-a-migration</link>
		<comments>http://shifteleven.com/articles/2006/09/28/loading-fixtures-in-a-migration#comments</comments>
		<pubDate>Thu, 28 Sep 2006 20:57:23 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[fixtures]]></category>
		<category><![CDATA[migration]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/articles/2006/09/28/loading-fixtures-in-a-migration</guid>
		<description><![CDATA[I love migrations I think they are one of the best things about rails.  I love that I can count on any changes I&#8217;ve done in the database to be consistent across all other databases that I use.  Love it.
Sometimes I find that I want pre-load my database with some data, like categories [...]]]></description>
			<content:encoded><![CDATA[<p>I love <a href="http://wiki.rubyonrails.org/rails/pages/UnderstandingMigrations.">migrations</a> I think they are one of the best things about rails.  I love that I can count on any changes I&#8217;ve done in the database to be consistent across all other databases that I use.  Love it.</p>
<p>Sometimes I find that I want pre-load my database with some data, like categories that I have.  For testing purposes, I have already created this data in my fixture; now I just want to load that fixture into my database from a migration call.</p>
<p>I know that there is a <code>rake</code> task for this, so I looked into that code and came up with a little something.</p>
<p><span id="more-14"></span></p>
<pre class="ruby" title="code">require 'active_record/fixtures'

class CreateCategories &lt; ActiveRecord::Migration
  def self.up
    create_table :categories do |t|
      t.column :name, :string
    end

    Fixtures.create_fixtures('test/fixtures', File.basename("categories.yml", '.*'))
  end

  def self.down
    drop_table :categories
  end
end</pre>
<p>First I had to require <code>active_record/fixtures</code>.  This allows me to call the <code>Fixtures#create_fixtures</code> method, which load my data.  Now I can gaurantee that my fixture data will be loaded for any environment.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/09/28/loading-fixtures-in-a-migration/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Sleeping Easier with Migrations</title>
		<link>http://shifteleven.com/articles/2006/09/28/sleeping-easier-with-migrations</link>
		<comments>http://shifteleven.com/articles/2006/09/28/sleeping-easier-with-migrations#comments</comments>
		<pubDate>Thu, 28 Sep 2006 20:48:33 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[migration]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/articles/2006/09/28/sleeping-easier-with-migrations</guid>
		<description><![CDATA[As a rails user who loves migrations, I have noticed that all of the migrations are prefixed with three decimal places, like 001_create_sessions.rb or something of that nature.  That got me thinking, what would happen after I had 999 migrations?
That sets of the paranoia level up because who knows, I may need 1001 migrations! [...]]]></description>
			<content:encoded><![CDATA[<p>As a <a href="http://www.rubyonrails.org">rails</a> user who loves migrations, I have noticed that all of the migrations are prefixed with three decimal places, like <code>001_create_sessions.rb</code> or something of that nature.  That got me thinking, what would happen after I had 999 migrations?</p>
<p>That sets of the paranoia level up because who knows, I may need 1001 migrations!  So to settle this once and for all, I wrote a script that would generate 999 migrations for me.  I ran the 1000 migration and then it created <code>1001_test1001.rb</code>.</p>
<p>Good news! Rails doesn&#8217;t constrain its migrations to a 3 decimal place prefix.  So pointless&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/09/28/sleeping-easier-with-migrations/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
