<?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>Thinking In Rails &#187; Code</title>
	<atom:link href="http://thinkinginrails.com/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://thinkinginrails.com</link>
	<description>A Perl Programmer&#039;s Exploration of The World of Ruby on Rails</description>
	<lastBuildDate>Fri, 20 Jan 2012 19:17:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>When and Where to use Caching In Rails</title>
		<link>http://thinkinginrails.com/2010/05/when-and-where-to-use-caching-in-rails/</link>
		<comments>http://thinkinginrails.com/2010/05/when-and-where-to-use-caching-in-rails/#comments</comments>
		<pubDate>Tue, 11 May 2010 21:08:11 +0000</pubDate>
		<dc:creator>alan</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Help]]></category>

		<guid isPermaLink="false">http://thinkinginrails.com/?p=455</guid>
		<description><![CDATA[(Alternative title to this post: Rails Caching Enlightenment Through Perl) This entire post will either make you think I’m a horrible web programmer, or hopefully, show you the deep and meaningful insights that I’ve managed to eke out from the experience. Server Crashes Are Bad Last night I was up coding, but sadly, not rails [...]]]></description>
			<content:encoded><![CDATA[<p>(Alternative title to this post: <em>Rails Caching Enlightenment Through Perl</em>)</p>
<p><a href="http://thinkinginrails.com/wp-content/uploads/2010/05/copypaper.gif"></a>This entire post will either make you think I’m a horrible web programmer, or hopefully, show you the deep and meaningful insights that I’ve managed to eke out from the experience.</p>
<p><strong>Server Crashes Are Bad</strong><br />
<a href="http://thinkinginrails.com/wp-content/uploads/2010/05/6a0112796e0b0a28a40120a725222d970b.gif"><img class="alignright size-full wp-image-463" title="Angry Client" src="http://thinkinginrails.com/wp-content/uploads/2010/05/6a0112796e0b0a28a40120a725222d970b.gif" alt="" width="181" height="231" /></a>Last night I was up coding, but sadly, not rails code. Yesterday I had a call from a client telling me that the website had crashed, and <em>their</em> clients were pissed off because this happened just when they had put out their weekly newsletter. The server (a virtual hosted system hosted at GoDaddy) had locked up tight, rendering all the sites that were on the server un-reachable.</p>
<p>The server was rebooted, and digging into it there was no clear reason why it had crashed, which is of course not what they wanted to hear. I had a development server set up at home, so I did a bit of testing to see if I could duplicate it. The server was old and slow (not even dual core), but usable as a Linux workstation, so I figured that if I could make the site feel faster here, the gains on the production server would be huge.</p>
<p><strong>Determining A Baseline</strong><br />
First was to hit it with the trusted <a href="http://httpd.apache.org/docs/2.0/programs/ab.html">Apache Benchmark</a> utility, I started with a perfectly reasonable 10 concurrent connections for 1000 hits hitting the landing page that was sent out in the newsletter, and probably one of the more intensive pages DB and logic wise on the site.</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">$ ab -c 10 -n 1000 “http://site.com/page.html?id=117”</pre></div></div>

<p>Looking at my system monitor, I immediately saw my CPU use jump to 100%, disk access go from a blip here and there to constant, and the machine ground to a halt.</p>
<p>I hit ctrl-c pretty fast.</p>
<p>OK, problem found, the site is a vampire and sucks the life out of the server. I played with a few different settings and eventually ended up using 5 concurrent connections and 20 hits “-c 5 -n 20” which gave me an average 2000-4000ms to serve pages, about 1 request a second.</p>
<p>Horrible right? Before you put me against the wall to keep me from doing <em>any</em> web programming again, remember this is a really old server. Please? Maybe one smoke before it’s time for me to go?</p>
<p><strong>Small Fixes, Small Gains</strong><br />
So there were three things that I figured I needed to look at:</p>
<ol>
<li> Use the <a href="http://developer.yahoo.com/yslow/">YSlow </a><a href="http://developer.yahoo.com/yslow/">plugin</a> to find some small gains</li>
<li> Finally see if there are any just bad code that could be refactored out, loops within loops, useless re-calculation, etc.</li>
<li> Re-examine the number of queries going on on the page</li>
</ol>
<p>YSlow gave me a <a href="http://developer.yahoo.com/performance/rules.html">few things to do</a>. Setting the expires header for images, moving CSS and JS to the top and bottom of the page, and a couple of other minor things that gave me no real gains via ab.</p>
<p>Surprisingly, there weren’t any low hanging fruit for bad code or useless loops within loops. This sucked, mostly because that meant me going through and re-looking at SQL and refactoring that, which I’m not sure about you, but that doesn’t sound like fun to me.<br />
Somewhat more surprisingly there were only a couple of extra queries, mostly related to the ORM I was using, <a href="http://search.cpan.org/dist/Class-DBI/">Class::DBI</a> and some just silly things. Sadly none of these gave me any more gains.</p>
<p>One thing I did find was where the issues were. When I commented out the main grid of items that is the focus on the page, the page response went from 2000-4000ms response time to 200. Hmm&#8230;, so what to do with this.  What if I could make it so the time to generate the main product grid didn&#8217;t happen?  So I commented out the dynamic code, and copied in the HTML produced (from the view source window in firefox) to see if it was the dynamic generation (which wasn&#8217;t <em>really</em> that complex from what I could see).  Again, 200-400ms time, serving 9-10 requests a second, with almost no CPU or disk impact.</p>
<p>OK, so I thought what if there was a way to pre-generate the HTML periodically, and then have the perl code load that instead of doing it dynamically each time.  That almost sounds like&#8230;.. &#8220;<strong>caching</strong>&#8220;.  Huh, almost like something that should be built in.</p>
<p><strong>Enter Caching</strong><br />
<a href="http://thinkinginrails.com/wp-content/uploads/2010/05/copypaper.gif"><img class="alignright" title="Copy Paper" src="http://thinkinginrails.com/wp-content/uploads/2010/05/copypaper-300x202.gif" alt="" width="300" height="202" /></a>Honestly my experiences with caching have been minimal, most of the time I am trying to <strong>prevent</strong> caching (for re-uploaded images with the same filename, that sort of thing), and also it just hadn&#8217;t come up yet, probably because most of the sites I have worked on don&#8217;t get huge enough traffic to require it.  Luckily I had just read something about Caching in the <a href="http://www.masonhq.com/docs/manual/Devel.html">HTML::Mason developer docs</a> while finding some information for something else.</p>
<p>HTML::Mason has the concept of &#8220;components&#8221;, similar to partials in the rails world.  You&#8217;d call something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="perl" style="font-family:monospace;">blah blah
<span style="color: #339933;">&lt;</span> <span style="color: #339933;">&amp;</span> <span style="color: #ff0000;">&quot;/comp/gallery.mc&quot;</span><span style="color: #339933;">,</span> id <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">$id</span><span style="color: #339933;">,</span> page <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">$cur_page</span><span style="color: #339933;">,</span> title <span style="color: #339933;">=&gt;</span> <span style="color: #ff0000;">&quot;TiR&quot;</span> <span style="color: #339933;">&amp;&gt;</span>
blah blah</pre></div></div>

<p>When the page is rendered it would call the gallery.mc component with the given arguments, render it, running whatever code is in there (<a href="http://www.masonhq.com/">HTML::Mason</a> isn&#8217;t the nice separated MVC that Rails is, so there&#8217;s potentially lots of controller code in your pages and components) and replacing the &lt; &amp; &amp;&gt; with the output.  The documents have a nice section on the built in page and component (think fragment) <a href="http://www.masonhq.com/docs/manual/Devel.html#data_caching">caching</a> where all you need to do is to add this code to the top of your component&#8217;s &#8220;init&#8221; section:</p>

<div class="wp_syntax"><div class="code"><pre class="perl" style="font-family:monospace;"><span style="color: #000066;">return</span> <span style="color: #b1b100;">if</span> <span style="color: #0000ff;">$m</span><span style="color: #339933;">-&gt;</span><span style="color: #006600;">cache_self</span><span style="color: #009900;">&#40;</span>key <span style="color: #339933;">=&gt;</span> <span style="color: #ff0000;">'fookey'</span><span style="color: #339933;">,</span> expires_in <span style="color: #339933;">=&gt;</span> <span style="color: #ff0000;">'3 hours'</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>other options<span style="color: #339933;">...</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This lets your component see if it&#8217;s already in the cache, and not expired, and if it is, serves that, and if not, renders and then caches itself with the given key.  The only tricky part is figuring out the right cache key to ensure it&#8217;s unique for each section of code.  I ended up writing something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="perl" style="font-family:monospace;"><span style="color: #0000ff;">$key</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">&quot;gallery|$id|$cur_page|$title&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">return</span> <span style="color: #b1b100;">if</span> <span style="color: #0000ff;">$m</span><span style="color: #339933;">-&gt;</span><span style="color: #006600;">cache_self</span><span style="color: #009900;">&#40;</span>key <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">$key</span><span style="color: #339933;">,</span> expires_in <span style="color: #339933;">=&gt;</span> <span style="color: #ff0000;">'10 minutes'</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>other options<span style="color: #339933;">...</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This makes the cache key a hash of the arguments sent to the component, ensuring that each differently rendered version of the page will get a different cache key. Not perfect I&#8217;m sure, but a nice mix of good caching and safety.</p>
<p>Running &#8216;ab&#8217; again I found that while the first couple of requests still took 2000-4000ms to run, subsequent pages were served in the 200-400ms range, and the CPU and disk load was <em>way</em> down.</p>
<p><strong>WTF &#8211; This is a Rails Blog</strong><br />
So why am I telling you all this Perl stuff? It’s because this is related more to web programming and programmer mindset than Perl or HTML::Mason.  You could replace &#8220;perl&#8221; with &#8220;ruby&#8221;, &#8220;component&#8221; with &#8220;partial&#8221; and &#8220;HTML::Mason&#8221; with &#8220;Rails&#8221; and get the same idea.</p>
<p>Because everything ran fine when the site was under development and only two or three people were hitting it I didn&#8217;t have to worry about caching or performance issues.  In fact, I didn&#8217;t even <strong>think</strong> about performance because thigns &#8220;just worked&#8221;.  When things did go badly (again, server crashes == pissed off clients), I had to scramble to find a solution (luckily only one night of work).</p>
<p>I&#8217;m still doing testing with the new caching code, but I expect to put it online tonight or tomorrow, and look forward to the before and after numbers on the production server.</p>
<p><strong>Lessons Learned</strong><br />
My lessons learned:</p>
<ul>
<li> Watch <strong>from the start</strong> for cachable pieces of code.  Big complex SQL queries or complex logic that can be created once a week, day or even every minute is a candidate.  In Rails it can be as simple as surrounding the code with &lt; % cache do %&gt; .. &lt; % end %&gt;.</li>
<li> Test performance from the onset.  Learn to love <a href="http://httpd.apache.org/docs/2.0/programs/ab.html">Apache Benchmark</a> and start hitting your sites potential hot pages from the start, and watch and learn what causes reponsiveness to go down.</li>
</ul>
<p><strong>Resources</strong><br />
For those of you wanting some actual <em>rails</em> resources to learn more about this stuff, have a look at the following:</p>
<ul>
<li> <a href="http://www.cyberciti.biz/tips/howto-performance-benchmarks-a-web-server.html">Understanding &#8216;ab&#8217; results</a> &#8211; Nice resource for how to read that output.</li>
<li> <a href="http://guides.rails.info/caching_with_rails.html">Caching with Rails</a> &#8211; The rails guides documentation with details on page, fragment, action caching and everything in between.</li>
<li> <a href="http://thewebfellas.com/blog/2008/6/9/rails-2-1-now-with-better-integrated-caching">Rails 2.1 Caching</a> &#8211; A bit older, but a nice list of the caching capabilities introduced and available in Rails 2.1, still pretty relevant.</li>
<li> <a href="http://railslab.newrelic.com/scaling-rails">The Scaling Rails Podcast Series</a> &#8211; Fantastic information in here, I recommend watching all of them, if you can&#8217;t, hit #2, 3, 5, 6, 7 for caching, and then #15 and 16 for load testing with ab and friends.</li>
</ul>
<div>Any other resources or hints as to how to deal with caching in Rails (or Perl for that matter! <img src='http://thinkinginrails.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ?</div>
]]></content:encoded>
			<wfw:commentRss>http://thinkinginrails.com/2010/05/when-and-where-to-use-caching-in-rails/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Evolving A Simple Twitter to Blog Ruby Program Part 1</title>
		<link>http://thinkinginrails.com/2010/05/evolving-a-simple-twitter-to-blog-ruby-program-part-1/</link>
		<comments>http://thinkinginrails.com/2010/05/evolving-a-simple-twitter-to-blog-ruby-program-part-1/#comments</comments>
		<pubDate>Wed, 05 May 2010 04:14:57 +0000</pubDate>
		<dc:creator>alan</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Instructions]]></category>

		<guid isPermaLink="false">http://thinkinginrails.com/?p=365</guid>
		<description><![CDATA[In a "quick" and dirty exercise I built a little ruby program to grab my twitter posts and colate them into a list for posting a "tweets of the week" type blog post.  It was a lot more about figuring out how to do it than the actual output (I'd hope you just follow me on twitter than rely on me posting my tweets here).  Tonight at the FV.rb meeting @dkubb helped me a lot in pointing out some glaring non-rubyisms and I thought that going through some of the changes might help others moving from "old school" programming (structured, functional, perl-y) to "new hotness" programming (object oriented, yeilds, and awesomeness).]]></description>
			<content:encoded><![CDATA[<p>In a &#8220;quick&#8221; and dirty exercise I built a little ruby program to grab my twitter posts and colate them into a list for posting a &#8220;tweets of the week&#8221; type blog post.  It was a lot more about figuring out how to do it than the actual output (I&#8217;d hope you just <a href="http://twitter.com/thinkinginrails">follow me</a> on twitter than rely on me posting my tweets here).  Tonight at the FV.rb meeting <a href="http://twitter.com/dkubb">@dkubb</a> helped me a lot in pointing out some glaring non-rubyisms and I thought that going through some of the changes might help others moving from &#8220;old school&#8221; programming (structured, functional, perl-y) to &#8220;new hotness&#8221; programming (object oriented, yeilds, and awesomeness).</p>
<p>I started out with <a href="http://gist.github.com/382571/5c87bd0bd5c59bef4d00c1357420d9cfac309699">this code</a> in a gist.  Nothing hugely bad, it pulls in either a URL or a file, parses the XML for the status updates, and for each one does some HTML replacement (@user, #hash, and URLs get auto-linked) and then spits out some HTML that can be copied and pasted into a blog entry.</p>
<p><strong>Starting Off</strong></p>
<p>The first step was figuring out how to parse the XML.   A bit of googling <a href="http://www.rubyinside.com/ruby-xml-performance-benchmarks-1641.html">found</a> <a href="http://railstips.org/blog/archives/2008/08/11/parsing-xml-with-ruby/">some</a> possibilities.  <a href="http://hpricot.com/">Hpricot</a>, <a href="http://libxml.rubyforge.org/">libxml-ruby</a>, and <a href="http://rdoc.info/projects/brynary/nokogiri">Nokogiri</a>.  The first post I saw noted that libxml-ruby was the fastest, which makes sense as it&#8217;ll be pretty close to the bare metal C libraries, so I took a run with that.  Not great success, the biggest challenge was figuring out how Ruby dealt with XML structure.  There was a lot of mucking around in IRB.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> <span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'xml'</span>
 <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> parser = <span style="color:#6666ff; font-weight:bold;">XML::Parser</span>.<span style="color:#9900CC;">file</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'twitter.xml'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
 <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#008000; font-style:italic;">#&lt;LibXML::XML::Parser:0x101170140 @context=#&lt;LibXML::XML::Parser::Context:0x101170168&gt;</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> doc = parser.<span style="color:#9900CC;">parse</span>
<span style="color:#008000; font-style:italic;"># snip xml spew to STDOUT</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> doc.<span style="color:#9966CC; font-weight:bold;">class</span>
 <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#6666ff; font-weight:bold;">LibXML::XML::Document</span>
<span style="color:#008000; font-style:italic;"># Hmm.... does find work?</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> s = doc.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'/status'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
 <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#008000; font-style:italic;">#&lt;LibXML::XML::XPath::Object:0x1018ff398&gt;</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> s.<span style="color:#9900CC;">methods</span>
<span style="color:#008000; font-style:italic;"># snip list of methods, and searching for what to do</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> s.<span style="color:#9900CC;">each</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>node<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#CC0066; font-weight:bold;">puts</span> node.<span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#006600; font-weight:bold;">&#125;</span>
 <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">nil</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> s.<span style="color:#9900CC;">each</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>node<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#CC0066; font-weight:bold;">puts</span> node.<span style="color:#9900CC;">inspect</span> <span style="color:#006600; font-weight:bold;">&#125;</span>
 <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">nil</span>
<span style="color:#008000; font-style:italic;"># WTF? OK, so what now then?</span></pre></div></div>

<p>It was a bit frustrating, though probably mostly because I just didn&#8217;t grok how the XML was being represented internally, and thinking of it more like a Perl hash-of-hashes than whatever libxml-ruby was using.  So I moved on.  (Ironically while re-doing some of this for this article I went back and was running the commands figuring now I would get it, and failed miserably <img src='http://thinkinginrails.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Next I looked at <a href="http://hpricot.com/">Hpricot</a>, but the syntax in the readme and examples scared me away.</p>
<p><strong>Starting Progress on the First Iteration</strong></p>
<p>Someone at work suggested that Nokogiri was the way to go, and realizing that parsing a few kb of XML probably wasn&#8217;t going to run me into any performance issues, I took a run at it with this.  I soon found that having a static XML file would be the easiest for testing, so I saved twitter.xml in the same directory as I was running IRB out of and played some more.</p>
<p>Much better.  Then to find out to get a list of the statuses:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> <span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'nokogiri'</span>
 <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> doc = <span style="color:#6666ff; font-weight:bold;">Nokogiri::XML</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC00FF; font-weight:bold;">File</span>.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'twitter.xml'</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#008000; font-style:italic;"># snip</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> doc.<span style="color:#9966CC; font-weight:bold;">class</span>
 <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#6666ff; font-weight:bold;">Nokogiri::XML::Document</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> doc.<span style="color:#9900CC;">xpath</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'/status'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
 <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> doc.<span style="color:#9900CC;">xpath</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'//status'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#008000; font-style:italic;"># snip lots more xml spew and more testing until...</span>
ruby<span style="color:#006600; font-weight:bold;">-</span>1.8.7<span style="color:#006600; font-weight:bold;">-</span>p249 <span style="color:#006600; font-weight:bold;">&gt;</span> doc.<span style="color:#9900CC;">xpath</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'//status'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">each</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>node<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#CC0066; font-weight:bold;">puts</span> node.<span style="color:#9900CC;">xpath</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;.//text&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">first</span>.<span style="color:#9900CC;">content</span> <span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#008000; font-style:italic;"># snip lovely output of each of the tweets in the xml file</span></pre></div></div>

<p>Ok, so now I could run &#8220;.each()&#8221; on this, having discovered that the xpath() function basically allowed me to get a list of XML nodes with that path, and <em>then</em> I could get a list of node data from that, remembering to use the &#8220;start from current node&#8221; syntax (using the &#8216;.&#8217; to represent the current location in the tree).</p>
<p>The next steps were (relatively) easy.  Looping through each status, get some information (time, status ID, content, etc), format that into HTML, find and implement a couple of &#8220;convert @user to an HTML link&#8221; bits of code I <a href="http://stackoverflow.com/questions/2034580/i-am-creating-a-twitter-clone-in-ruby-on-rails-how-do-i-code-it-so-that-the">found online</a>, and voila, first iteration was completed and working.</p>
<p><strong>Now With Some Expert Advice</strong></p>
<p>So after reading the <a href="http://blog.sirupsen.dk/me/what-i-wish-a-ruby-programmer-had-told-me-one-year-ago/">What I wish I had been told a year ago</a> post, I figured the next stage was to convert it to a class, make it more ruby-y, and give it some tests.  Dan Kubb of <a href="http://datamapper.org/">DataMapper</a> fame thankfully answered my question to help and moved me on to <a href="https://gist.github.com/382571/5c87bd0bd5c59bef4d00c1357420d9cfac309699">this current version</a> with some helpful advice.</p>
<p>I&#8217;ll continue this later on this week with Part 2, in which I iterate into more awesomeness!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkinginrails.com/2010/05/evolving-a-simple-twitter-to-blog-ruby-program-part-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Is A Site For Ruby Idioms Needed? [Update: Yes!]</title>
		<link>http://thinkinginrails.com/2010/05/a-site-for-ruby-idioms/</link>
		<comments>http://thinkinginrails.com/2010/05/a-site-for-ruby-idioms/#comments</comments>
		<pubDate>Mon, 03 May 2010 17:59:25 +0000</pubDate>
		<dc:creator>alan</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Resources]]></category>

		<guid isPermaLink="false">http://thinkinginrails.com/?p=385</guid>
		<description><![CDATA[I&#8217;ve noticed lately that there is definitely a &#8220;Ruby way&#8221; to write Ruby code. When I first read Effective Perl Programming years and years ago I went from writing code that looks like this (note that I know the &#8220;FILE&#8221; is wrong, but the wordpress auto-syntax highlighter thingy doesn&#8217;t seem to deal well with the [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve noticed lately that there is definitely a &#8220;Ruby way&#8221; to write Ruby code.  When I first read Effective Perl Programming years and years ago I went from writing code that looks like this (note that I know the &#8220;FILE&#8221; is wrong, but the wordpress auto-syntax highlighter thingy doesn&#8217;t seem to deal well with the correct bracketed syntax):</p>

<div class="wp_syntax"><div class="code"><pre class="perl" style="font-family:monospace;"><span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #b1b100;">my</span> <span style="color: #0000ff;">$line</span> <span style="color: #339933;">=</span> FILE <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">$line</span> <span style="color: #339933;">=~</span> <span style="color: #009966; font-style: italic;">/foo/</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000066;">print</span> <span style="color: #ff0000;">&quot;$line&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>(which isn&#8217;t all that un-perl-y to begin with, but that&#8217;s 15 years of perl in my brain stopping me from writing really un-idiomatic code) to far more idiomatic:</p>

<div class="wp_syntax"><div class="code"><pre class="perl" style="font-family:monospace;"><span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>FILE<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000066;">print</span> <span style="color: #b1b100;">if</span> <span style="color: #009966; font-style: italic;">/foo/</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The point being that there are certain conventions and ways that your programming style will adapt to the given language.  The following loop</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #0000dd;">10</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Is perfectly natural in C, but if you saw it in perl or ruby, while it might be perfectly valid, it would look <em>way</em> out of place in either language, and you&#8217;d get funny looks if you presented it to a code review.</p>
<p>In ruby some of these would be to not do this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">t.<span style="color:#CC0066; font-weight:bold;">gsub!</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/</span><span style="color:#006600; font-weight:bold;">&#40;</span>http<span style="color:#006600; font-weight:bold;">|</span>https<span style="color:#006600; font-weight:bold;">&#41;</span>biglonguglyandhardlyworksregex<span style="color:#006600; font-weight:bold;">/</span>, <span style="color:#996600;">&quot;&lt;a href=&quot;</span>\<span style="color:#996600;">&quot;&gt;<span style="color:#000099;">\1</span>&lt;/a&gt;&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>But instead do this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">    <span style="color:#CC00FF; font-weight:bold;">URI</span>.<span style="color:#9900CC;">extract</span><span style="color:#006600; font-weight:bold;">&#40;</span>t, <span style="color:#006600; font-weight:bold;">%</span>w<span style="color:#006600; font-weight:bold;">&#91;</span> http https ftp <span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>url<span style="color:#006600; font-weight:bold;">|</span>
      t.<span style="color:#CC0066; font-weight:bold;">gsub!</span><span style="color:#006600; font-weight:bold;">&#40;</span>url, <span style="color:#996600;">&quot;&lt;a href=&quot;</span>\<span style="color:#996600;">&quot;&gt;#{url}&lt;/a&gt;&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Or maybe instead of this</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">sum = <span style="color:#006666;">0</span>
list = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">2</span>,<span style="color:#006666;">3</span><span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#9966CC; font-weight:bold;">for</span> i <span style="color:#9966CC; font-weight:bold;">in</span> list <span style="color:#9966CC; font-weight:bold;">do</span>
  sum <span style="color:#006600; font-weight:bold;">+</span>= i
<span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#008000; font-style:italic;"># sum is now 6</span></pre></div></div>

<p>you use the must more awesomeer (yes it&#8217;s a word)</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">list = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">2</span>,<span style="color:#006666;">3</span><span style="color:#006600; font-weight:bold;">&#93;</span>
sum = list.<span style="color:#9900CC;">inject</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>s,v<span style="color:#006600; font-weight:bold;">|</span> s <span style="color:#006600; font-weight:bold;">+</span> v <span style="color:#006600; font-weight:bold;">&#125;</span> <span style="color:#008000; font-style:italic;"># sum =&amp;gt; 6</span></pre></div></div>

<p>Of course, you can write bad code in almost any language pretty easily (note how I&#8217;m not making a php/python/<a href="http://en.wikipedia.org/wiki/Whitespace_%28programming_language%29">whitespace</a>/<a href="http://en.wikipedia.org/wiki/Brainfuck">brainfuck</a> joke here!)</p>
<p>So my question is this.  Is there some grand collection of these Ruby idioms?  Is there a need for them?  Would a fusion of <a href="http://stackoverflow.com">StackOverflow</a> and <a href="http://refactormycode.com/">Refactor My Code</a> be a useful collection to have somewhere?  Or are the resources out there (which are a bit scattered) good enough?</p>
<p>So far I&#8217;ve found:</p>
<ul>
<li>This StackOverflow list of peoples <a href="http://stackoverflow.com/questions/613985/common-ruby-idioms">favorite Ruby Idioms</a></li>
<li>A <a href="http://cbcg.net/talks/rubyidioms/">presentation</a> from 2005</li>
<li>Yehuda&#8217;s <a href="http://yehudakatz.com/2009/11/12/better-ruby-idioms/">list from late 2009</a> isn&#8217;t <em>quite</em> what I was looking for, but shouldn&#8217;t be ignored</li>
</ul>
<p>Alternatively there are a lot of places where you can read other&#8217;s code to learn idiomatic Ruby by osmosis.  Github, RefactorMyCode, the popular Gems in the community, <a href="http://rubyquiz.com/">The Ruby Quiz</a> are all great resources for this.</p>
<p>My vision is a melding of StackOverflow (maybe using their new StackExchange community software?) and Refactor My Code where you can search for an idiom or programming operation based on code, Class, or tag, vote, and comment or submit a different version.  Sort of like a Perl Golf contest except instead of the fewest keystrokes being the goal it&#8217;s the cleanest/nicest/most effective way of doing the operation.</p>
<p>So what do you think, would this be useful to work on with the Ruby community, or is there enough information out there already that is google-able enough?  Everyone will also have their own way of doing things, but Ruby <em>is</em> an opinionated language (or is that only Rails?) so maybe there is One (or two) &#8220;correct&#8221; ways to do things.</p>
<p>Your thoughts appreciated.</p>
<p><strong>Update</strong> &#8211; So a bit of discussion here, and lots of great comments on <a href="http://thinkinginrails.com/2010/05/a-site-for-ruby-idioms/">proggit</a> show me that this idea does deserve a go of it.  I&#8217;ve registered <a href="http://ruby-idioms.com">ruby-idioms.com</a> (pointed here for now) and hope to have something up in the next couple of weeks, and will take a few beta tests to have a run at it.  Keep an eye here for any news by subscribing to the <a href="http://thinkinginrails.com/feed/">RSS</a> or following me on <a href="http://twitter.com/thinkinginrails">Twitter</a>.  Thanks everyone!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkinginrails.com/2010/05/a-site-for-ruby-idioms/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>More on Using Enums For Constant Data in Rails</title>
		<link>http://thinkinginrails.com/2010/04/more-on-using-enums-for-constant-data-in-rails/</link>
		<comments>http://thinkinginrails.com/2010/04/more-on-using-enums-for-constant-data-in-rails/#comments</comments>
		<pubDate>Tue, 20 Apr 2010 04:53:55 +0000</pubDate>
		<dc:creator>alan</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://thinkinginrails.com/?p=277</guid>
		<description><![CDATA[So I got around to rollowing tip #3 on using Enums in AR, and found it worked&#8230;. mostly.  The problem comes in where the value isn&#8217;t already set.  I started with this in my model: # game.rb # at the top of the file, define the list of genders GENDERS = %w&#40; boy girl coed [...]]]></description>
			<content:encoded><![CDATA[<p>So I got around to rollowing <a href="http://zargony.com/2008/04/28/five-tips-for-developing-rails-applications">tip #3</a> on using Enums in AR, and found it worked&#8230;. <em>mostly</em>.  The problem comes in where the value isn&#8217;t already set.  I started with this in my model:</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># game.rb</span>
  <span style="color:#008000; font-style:italic;"># at the top of the file, define the list of genders</span>
  GENDERS = <span style="color:#006600; font-weight:bold;">%</span>w<span style="color:#006600; font-weight:bold;">&#40;</span> boy girl coed <span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#008000; font-style:italic;"># and validations for it</span>
  validates_inclusion_of <span style="color:#ff3333; font-weight:bold;">:gender</span>,   :<span style="color:#9966CC; font-weight:bold;">in</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#6666ff; font-weight:bold;">Game::GENDERS</span>, <span style="color:#ff3333; font-weight:bold;">:on</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:create</span>, <span style="color:#ff3333; font-weight:bold;">:message</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;extension %s is not included in the list&quot;</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># finally define the gender as a symbol for lookups</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> gender
     read_attribute<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:gender</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">to_sym</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> gender=<span style="color:#006600; font-weight:bold;">&#40;</span>value<span style="color:#006600; font-weight:bold;">&#41;</span>
    write_attribute<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:gender</span>, value.<span style="color:#5A0A0A; font-weight:bold;">to_s</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>This works fine until you have a nil value for gender.  OK, next step, just check if the value is nil before you read it and return nil if it is.  Only thing is that if you were to add something like</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">gender</span>.<span style="color:#0000FF; font-weight:bold;">nil</span>? <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">nil</span></pre></div></div>

<p>But then you get an ugly &#8220;stack level too deep&#8221; error, because when you call &#8216;self.gender&#8217; it&#8217;s calling the gender method, which checks to see if self.gender is nil, which calls the gender method, which&#8230; well, you get the picture.</p>
<p>Took a bit of looking, and I&#8217;m not sure if this is the &#8220;correct&#8221; solution, but it does work properly.  I just modified the gender method as such:</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#008000; font-style:italic;">#game.rb</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> gender
    attributes = attributes_before_type_cast
    <span style="color:#9966CC; font-weight:bold;">if</span> attributes<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;gender&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
      read_attribute<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:gender</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">to_sym</span>
    <span style="color:#9966CC; font-weight:bold;">else</span>
      <span style="color:#0000FF; font-weight:bold;">nil</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>This uses the <a href="http://apidock.com/rails/ActiveRecord/Base/attributes_before_type_cast">attributes_before_type_cast</a> grabs all attributes into a hash (before they are mangled by whatever ActiveRecord does), checks to see if the &#8216;gender&#8217; attribute is filled in and either returns it or nil.  Depending on if you&#8217;re learning or not, you may want to just check out the <a href="http://github.com/zargony/activerecord_symbolize">activerecord_symbolize</a> plugin though <img src='http://thinkinginrails.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>All working, and ready to commit to the main branch.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkinginrails.com/2010/04/more-on-using-enums-for-constant-data-in-rails/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Using Enums For Constant Data in Rails and ActiveRecord</title>
		<link>http://thinkinginrails.com/2010/04/using-enums-for-constants/</link>
		<comments>http://thinkinginrails.com/2010/04/using-enums-for-constants/#comments</comments>
		<pubDate>Sat, 17 Apr 2010 06:54:13 +0000</pubDate>
		<dc:creator>alan</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://thinkinginrails.com/?p=261</guid>
		<description><![CDATA[I&#8217;ve been wondering what to write up for todays entry, in an effort to keep up the &#8220;post a day&#8221; discipline.   I have about eight drafts sitting in the wordpress queue that are either incomplete thoughts or completely uninteresting posts.  So I figured I&#8217;d take a look at what my next challenge is in my [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been wondering what to write up for todays entry, in an effort to keep up the &#8220;post a day&#8221; discipline.   I have about eight drafts sitting in the wordpress queue that are either incomplete thoughts or completely uninteresting posts.  So I figured I&#8217;d take a look at what <em>my</em> next challenge is in my own project.  After all, that&#8217;s what this site is for in some ways&#8230; a muse to get my off my butt and back into Rails code.</p>
<p>The last request that came in was for the ability to take a game object with a non-boolean, but discreet bit of data to specify if it is a boys only, girls only, or coed game.  A constant you might say.</p>
<p>Back in the old perl world I&#8217;d probably look at doing something like adding an integer field to the database and then just remember that 1 = boys, 2 = girls and 0 = coed.  Or something.  Or was it 3 = coed?  You see the problem here though.  Having to remember the settings, and make sure that all the different files output the same values for the same settings&#8230; ugh.  Even putting an output filter of some sort (or in rails parlance, a helper), is a bit of an ugly situation because that doesn&#8217;t help you with your database layer either.  I might also have used the &#8220;Constant&#8221; or &#8220;ReadOnly&#8221;modules to do the same, or even gone with the more complex solution is to create a foreign key into another table called &#8220;gamegendertype&#8221; or something that just has the 1 = boys, 2 = girls, 3 = coded, but that&#8217;s unneeded complexity, database lookups/joins, etc (though it doesmake it easier to add another data type).</p>
<p>So I dug into it to find out what the canonical &#8220;rails way&#8221; was to do it.  And that search led to <a href="http://en.wikipedia.org/wiki/Enumerated_type">enums</a>.  Enums allow you to specify your own discreet data types that can be searched on as if they were integers or the like, but are words like &#8220;Diamonds&#8221; &#8220;Hearts&#8221; &#8220;Clubs&#8221; and &#8220;Spades&#8221; for a solitaire game.</p>
<p>Rails doesn&#8217;t seem to have a built in way to do it, but the way that the various links I found had you do it were to store the string value in the backend database, but turn that into a :symbol for when it&#8217;s accessed to and from the front end.  A link is worth a thousand words though <img src='http://thinkinginrails.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<ul>
<li><a href="http://stackoverflow.com/questions/265725/what-is-the-best-way-to-handle-constants-in-ruby-when-using-rails">Using constants in RoR</a>, or how to <a href="http://stackoverflow.com/questions/693928/how-replacecreate-an-enum-field-on-rails-2-0-migrations">use them with migrations</a>, from StackOverflow</li>
<li><a href="http://www.snowgiraffe.com/tech/311/enumeration-columns-with-rails/">Enumeration columns</a> in rails</li>
<li>An (older) <a href="http://scripts.top4download.com/enum-column-plugin-for-rails/wefvo.html">Enum plugin</a></li>
<li><a href="http://zargony.com/2008/04/28/five-tips-for-developing-rails-applications">ActiveRecord enums</a> (#3 in the list, via the StackOverflow link)</li>
</ul>
<p>For my project I&#8217;d rather not use a plugin (trying to learn by doing and all) so I&#8217;ll probably go with the virtual attribute method (last link).  Keep an eye on the commit log on my <a href="http://github.com/arcterex">github account</a> to see where it goes <img src='http://thinkinginrails.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://thinkinginrails.com/2010/04/using-enums-for-constants/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Refactoring With Helpers</title>
		<link>http://thinkinginrails.com/2010/04/refactoring-with-helpers/</link>
		<comments>http://thinkinginrails.com/2010/04/refactoring-with-helpers/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 06:26:02 +0000</pubDate>
		<dc:creator>alan</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://thinkinginrails.com/?p=248</guid>
		<description><![CDATA[Bit of a follow up to my last post, with mucho thanks to the guys at the FV.rb who helped out, @pennyminder and @dkubb. I originally figured I needed to do some dynamic methods like you can do in Perl to auto-create methods, but it turns out the better way to do it nicely (or [...]]]></description>
			<content:encoded><![CDATA[<p>Bit of a follow up to my last post, with mucho thanks to the guys at the <a href="http://fvrb.org">FV.rb</a> who helped out, <a href="http://twitter.com/pennyminder">@pennyminder</a> and <a href="http://twitter.com/dkubb">@dkubb</a>.</p>
<p>I originally figured I needed to do some dynamic methods like you can do in Perl to auto-create methods, but it turns out the better way to do it nicely (or more nicely) was refactor my previous code is two areas.</p>
<p>First is to move the view logic (ie: each user having a URL attached to them) out of the controller and into a helper and to reverse it, so instead of having  &#8220;<em>&lt;rolename&gt;</em>?&#8221; method for each user type (ie: user.referee? user.assignor?) having a nice little method that just resolves the role path for the user.</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">  <span style="color:#008000; font-style:italic;"># application_helper.rb</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> user_role_path<span style="color:#006600; font-weight:bold;">&#40;</span>user<span style="color:#006600; font-weight:bold;">&#41;</span>
    role_path = <span style="color:#006600; font-weight:bold;">&#123;</span>
      <span style="color:#996600;">'clubadmin'</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">'/some/admin/path'</span>,
      <span style="color:#996600;">'referee'</span>   =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; bids_path<span style="color:#006600; font-weight:bold;">&#40;</span>user<span style="color:#006600; font-weight:bold;">&#41;</span>,
      <span style="color:#996600;">'assignor'</span>  =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; assignor_path<span style="color:#006600; font-weight:bold;">&#40;</span>user<span style="color:#006600; font-weight:bold;">&#41;</span>,
    <span style="color:#006600; font-weight:bold;">&#125;</span>
    role_path<span style="color:#006600; font-weight:bold;">&#91;</span>user.<span style="color:#9900CC;">role</span>.<span style="color:#9900CC;">name</span>.<span style="color:#9900CC;">downcase</span><span style="color:#006600; font-weight:bold;">&#93;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>I don&#8217;t like having to have the hash in here, but since that is view specific, it seems to work nicely.  Anyway, this gives me the ability to call this <strong>view specific</strong> code in my view and by using the following I can output the correct path based on the user.</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># _header.html.erb</span>
<span style="color:#006600; font-weight:bold;">&amp;</span>lt;<span style="color:#006600; font-weight:bold;">%</span>= <span style="color:#5A0A0A; font-weight:bold;">link_to</span> <span style="color:#996600;">&quot;My Page&quot;</span>, user_role_path<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#5A0A0A; font-weight:bold;">session</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:user</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">%&amp;</span>gt;</pre></div></div>

<p>Also whereas the application helpers get access to all the &#8220;view&#8221; stuff, ie: it knows how to resolve something like bids_path(user), the controllers don&#8217;t have the RESTful functions, but can if you pull in the helper code.  IE:</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># users_controller.rb</span>
  <span style="color:#008000; font-style:italic;"># pull in the helper functions from application_helper.rb</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> ApplicationHelper
  <span style="color:#006600; font-weight:bold;">&#91;</span>...<span style="color:#006600; font-weight:bold;">&#93;</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> login
    <span style="color:#008000; font-style:italic;"># [...] authenticate</span>
    <span style="color:#008000; font-style:italic;"># and now redirect....</span>
    <span style="color:#5A0A0A; font-weight:bold;">redirect_to</span> user_role_path<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#5A0A0A; font-weight:bold;">session</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:user</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Not sure how pragmatic this is, but it eliminated a big ugly if/elsif/elsif/end block.</p>
<p>The second revelation was that I was perhaps going in the wrong direction with wanting to have the &#8220;user.<em>&lt;rolename&gt;?</em> functions, where instead I could more simply have a function to see if the user is a role.  IE:</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">  <span style="color:#9966CC; font-weight:bold;">def</span> has_role?<span style="color:#006600; font-weight:bold;">&#40;</span>role<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">role</span>.<span style="color:#9966CC; font-weight:bold;">include</span>?<span style="color:#006600; font-weight:bold;">&#40;</span>role<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p><strong>Way</strong> better than a big long if/elsif/elsif/elsif/elsif/end block or case statement, and way more extendable.</p>
<p>Feel free to check out the <a href="http://github.com/arcterex/Referee-Management/commit/9a487940f4d3d4a29e80a37d688a63f567f6f303">commit on github</a> for all the gory details.  As always any suggestions are welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkinginrails.com/2010/04/refactoring-with-helpers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Better Way To Do Dynamic Methods</title>
		<link>http://thinkinginrails.com/2010/04/better-way-to-do-dynamic-methods/</link>
		<comments>http://thinkinginrails.com/2010/04/better-way-to-do-dynamic-methods/#comments</comments>
		<pubDate>Wed, 14 Apr 2010 05:49:50 +0000</pubDate>
		<dc:creator>alan</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Help]]></category>

		<guid isPermaLink="false">http://thinkinginrails.com/?p=242</guid>
		<description><![CDATA[Not sure how best to describe this, so I figure a few lines of code can say a hundred words at least: # app/models/user.rb # This lets me call @user.home_page from within views or controllers to create a URL def home_page if self.referee? return &#34;/bids&#34; # sends user to site.com/bids end if self.assignor? return &#34;/assignors&#34; [...]]]></description>
			<content:encoded><![CDATA[<p>Not sure how best to describe this, so I figure a few lines of code can say a hundred words at least:</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># app/models/user.rb</span>
  <span style="color:#008000; font-style:italic;"># This lets me call @user.home_page from within views or controllers to create a URL</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> home_page
    <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">referee</span>?
      <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#996600;">&quot;/bids&quot;</span> <span style="color:#008000; font-style:italic;"># sends user to site.com/bids</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">assignor</span>?
      <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#996600;">&quot;/assignors&quot;</span> <span style="color:#008000; font-style:italic;"># sends user to site.com/assignors</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#008000; font-style:italic;"># [... etc ...]</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># dynamically determine the role name as a method</span>
  <span style="color:#008000; font-style:italic;"># can this be done to to_sym or something better,</span>
  <span style="color:#008000; font-style:italic;"># or a missing_method call to make it dynamic?</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> referee?
    <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">role</span>.<span style="color:#9900CC;">name</span>.<span style="color:#9900CC;">downcase</span> == <span style="color:#996600;">&quot;referee&quot;</span>
      <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">true</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#0000FF; font-weight:bold;">false</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> assignor?
    <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">role</span>.<span style="color:#9900CC;">name</span>.<span style="color:#9900CC;">downcase</span> == <span style="color:#996600;">&quot;assignor&quot;</span>
      <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">true</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#0000FF; font-weight:bold;">false</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>What I really want to do is call &#8220;bids_path&#8221; or &#8220;assignors_path&#8221;, but those don&#8217;t seem to be available from within the model file.  I&#8217;m sure there must be a better way to do this, from two different aspects:</p>
<ul>
<li> The first part of the code, returning the actual path, or at least the dynamic resource path instead of having it hard coded.  This is possible in the view, but I&#8217;d have to fill it up with checks for the user type and then calling either bids_path for referees or assignors_path for assignors
</li>
<li> The second part, where I create the two methods to make the above determination.  I could just trust that the @user.role.name will return The Right Thing, but I&#8217;m not sure how to auto-magically create the methods to do this for anything that the user.role.name contains.
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thinkinginrails.com/2010/04/better-way-to-do-dynamic-methods/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Querying Multiple Tables With ActiveRecord</title>
		<link>http://thinkinginrails.com/2010/04/querying-multiple-tables-with-activerecord/</link>
		<comments>http://thinkinginrails.com/2010/04/querying-multiple-tables-with-activerecord/#comments</comments>
		<pubDate>Sat, 10 Apr 2010 21:42:58 +0000</pubDate>
		<dc:creator>alan</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://thinkinginrails.com/?p=200</guid>
		<description><![CDATA[The other day at work I was doing some data mining for our business intelligence folks. They needed to get some stats from the last year of billing transactions, and the task came to me. I had to hack up a perl script to query the archived data to find a certain type of transaction. [...]]]></description>
			<content:encoded><![CDATA[<p>The other day at work I was doing some data mining for our business intelligence folks.  They needed to get some stats from the last year of billing transactions, and the task came to me.  I had to hack up a perl script to query the archived data to find a certain type of transaction.  Easy enough, the only minor issue was that since the data set was both huge and old, the table were broken up by month.</p>
<p>My perl script looked something like this (cleaned up for brevity):</p>

<div class="wp_syntax"><div class="code"><pre class="perl" style="font-family:monospace;"><span style="color: #0000ff;">@months</span> <span style="color: #339933;">=</span> <span style="color: #000066;">qw</span><span style="color: #009900;">&#40;</span> <span style="color: #cc66cc;">200901</span> <span style="color: #cc66cc;">200902</span> <span style="color: #cc66cc;">200903</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;"># up to 201004</span>
<span style="color: #0000ff;">$sql</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">&quot;select * from BillingMONTH where resultCode=40&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">foreach</span> <span style="color: #b1b100;">my</span> <span style="color: #0000ff;">$month</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">@months</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #0000ff;">$sql_full</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">$sql</span><span style="color: #339933;">;</span>
<span style="color: #0000ff;">$sql_full</span> <span style="color: #339933;">=~</span> <span style="color: #009966; font-style: italic;">s/MONTH/$month/</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;"># change the table name for each record</span>
<span style="color: #0000ff;">$sth</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">$dbh</span><span style="color: #339933;">-</span><span style="color: #0000ff;">&amp;gt</span><span style="color: #339933;">;</span>prepare<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">$sql_full</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">or</span> <span style="color: #000066;">die</span><span style="color: #339933;">;</span>
<span style="color: #0000ff;">$sth</span><span style="color: #339933;">-</span><span style="color: #0000ff;">&amp;gt</span><span style="color: #339933;">;</span>execute<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#91;</span> <span style="color: #339933;">...</span> <span style="color: #009900;">&#93;</span> <span style="color: #666666; font-style: italic;"># retrieve the data, save/process it</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I started wondering if these sorts of quick and dirty, but non-trivial scripts were easily doable in Ruby using Active Record.</p>
<p>I set up a similar situation on my system, a mysql database with 3 tables and a couple of rows of garbage data in them.  I knew that I could get a database connection set up very fast by making a throwaway rails app, setting up the models in it, and then using script/console as my interface, but I&#8217;ve honestly never use activerecord in a <em>scripting</em> environment.</p>
<p>After some messing around I came up with this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;">#!/usr/bin/ruby</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'rubygems'</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'active_record'</span>
&nbsp;
<span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">establish_connection</span><span style="color:#006600; font-weight:bold;">&#40;</span>
   <span style="color:#ff3333; font-weight:bold;">:adapter</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">&quot;mysql&quot;</span>,
   <span style="color:#ff3333; font-weight:bold;">:username</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">&quot;root&quot;</span>,
   <span style="color:#ff3333; font-weight:bold;">:password</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">&quot;password&quot;</span>,
   <span style="color:#ff3333; font-weight:bold;">:database</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">&quot;test&quot;</span>
<span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#CC00FF; font-weight:bold;">Test</span> <span style="color:#006600; font-weight:bold;">&amp;</span>lt; <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span> 
<span style="color:#9966CC; font-weight:bold;">end</span> 
&nbsp;
<span style="color:#006600; font-weight:bold;">%</span>w<span style="color:#006600; font-weight:bold;">&#40;</span> Archive201001 Archive201002 Archive201003 <span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>tablename<span style="color:#006600; font-weight:bold;">|</span>
   res = <span style="color:#CC00FF; font-weight:bold;">Test</span>.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#ff3333; font-weight:bold;">:all</span>, <span style="color:#ff3333; font-weight:bold;">:from</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; tablename, <span style="color:#ff3333; font-weight:bold;">:conditions</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">&quot;name like 'test%'&quot;</span> <span style="color:#006600; font-weight:bold;">&#41;</span>;
   <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Total results from #{tablename}: #{res.size.to_s}&quot;</span>
   <span style="color:#008000; font-style:italic;"># [...] other awesome processing on the res object</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Running it gives me:</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">alan@phoenix:~/code/ruby$ ./testdb.rb
Total results from Archive201001: 3
Total results from Archive201002: 6
Total results from Archive201003: 3</pre></div></div>

<p>Whohoo!  The one thing I couldn&#8217;t figure out is how to get rid of having to create a sub-class of the ActiveRecord::Base class.  I technically can do it with:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">connection</span>.<span style="color:#9900CC;">execute</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;select * from #{tablename}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>But I don&#8217;t know how to get this into the &#8220;object oriented&#8221; version to use the :conditions and <img src='http://thinkinginrails.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder and such.  However, the main point of can I replace perl and DBI for quick and dirty database scripting has most definitively been answered.</p>
<p>Next step: seeing how to do the same thing in <a href="http://datamapper.org/">Data Mapper</a> (to keep <a href="http://twitter.com/dkubb">@dkubb</a> happy) <img src='http://thinkinginrails.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://thinkinginrails.com/2010/04/querying-multiple-tables-with-activerecord/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Referee Site Code Online</title>
		<link>http://thinkinginrails.com/2010/04/referee-site-code-online/</link>
		<comments>http://thinkinginrails.com/2010/04/referee-site-code-online/#comments</comments>
		<pubDate>Sat, 10 Apr 2010 05:49:20 +0000</pubDate>
		<dc:creator>alan</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[github]]></category>

		<guid isPermaLink="false">http://thinkinginrails.com/?p=203</guid>
		<description><![CDATA[Got approval to put the oft-mentioned referee site code online, so you can find it here in my github account. I don&#8217;t see it being all that useful to anyone but me, but if you feel like commenting on the code, contributing any changes or suggestions, code or design, please do!]]></description>
			<content:encoded><![CDATA[<p>Got approval to put the oft-mentioned referee site code online, so you <a href="http://github.com/arcterex/Referee-Management">can find it here</a> in my github account.  I don&#8217;t see it being all that useful to anyone but me, but if you feel like commenting on the code, contributing any changes or suggestions, code or design, <em>please do!</em></p>
]]></content:encoded>
			<wfw:commentRss>http://thinkinginrails.com/2010/04/referee-site-code-online/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>At Home With Nested Routes and Resources</title>
		<link>http://thinkinginrails.com/2010/04/at-home-with-nested-routes-and-resources/</link>
		<comments>http://thinkinginrails.com/2010/04/at-home-with-nested-routes-and-resources/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 00:16:13 +0000</pubDate>
		<dc:creator>alan</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Resources]]></category>

		<guid isPermaLink="false">http://thinkinginrails.com/?p=152</guid>
		<description><![CDATA[When I first heard about nested routes, as with most things in Rails, I completely ignored them, discounting them as something I&#8217;d get to learning when I needed to, but right now they were yet another one of those things that I didn&#8217;t quite grok as I didn&#8217;t have the other base knowledge of the [...]]]></description>
			<content:encoded><![CDATA[<p>When I first heard about nested routes, as with most things in Rails, I completely ignored them, discounting them as something I&#8217;d get to learning when I needed to, but right now they were yet another one of those things that I didn&#8217;t quite grok as I didn&#8217;t have the other base knowledge of the Rails system to know why I needed them.  To be fair, I&#8217;m not that much closer now, and started to realize the the other day I didn&#8217;t really quite understand REST and having a RESTful site.</p>
<p>But when I started looking at how my site was structured, and how things were really encapsulated in each other, such as clubs &#8220;having&#8221; fields, and fields &#8220;having&#8221; games, I started to understand the need.  Actually it was more doing the scaffolding of the site and seeing that I had to set field in a dropdown each time I created a game, or the club each time I created a field.  It didn&#8217;t make sense and it seemed like a stupid way to do it.</p>
<p>Back in the old days in perl, I&#8217;d pass the ID of the main object when I created a sub-object.  So if I had a club editing page with a &#8216;create new field&#8217; button on it, that button would pass a hidden &#8220;club_id=$id&#8221; when it was pressed.</p>
<p>Rails comes with a nicer way of doing it.  It allows you to nest related resources.  Probably the best place to start is with Ryan Bates excellent <a href="http://railscasts.com/episodes/139-nested-resources">Nested Resources screencast</a>, or Adam&#8217;s <a href="http://adamblog.heroku.com/past/2007/12/20/nested_resources_in_rails_2/">Nested Resources in Rails 2 page</a>.</p>
<p>For this I set up the following in my routes.rb as such:</p>
<div id="_mcePaste">

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">map.<span style="color:#9900CC;">resources</span> <span style="color:#ff3333; font-weight:bold;">:clubs</span>, <span style="color:#ff3333; font-weight:bold;">:has_many</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:areas</span>, <span style="color:#ff3333; font-weight:bold;">:shallow</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span></pre></div></div>

</div>
<p>And then running &#8220;rake routes&#8221; will show you what the routes will actually be:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">     club_areas GET    <span style="color:#006600; font-weight:bold;">/</span>clubs<span style="color:#006600; font-weight:bold;">/</span>:club_id<span style="color:#006600; font-weight:bold;">/</span>areas<span style="color:#006600; font-weight:bold;">&#40;</span>.:<span style="color:#CC0066; font-weight:bold;">format</span><span style="color:#006600; font-weight:bold;">&#41;</span>            <span style="color:#006600; font-weight:bold;">&#123;</span>:action<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;index&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;areas&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
                POST   <span style="color:#006600; font-weight:bold;">/</span>clubs<span style="color:#006600; font-weight:bold;">/</span>:club_id<span style="color:#006600; font-weight:bold;">/</span>areas<span style="color:#006600; font-weight:bold;">&#40;</span>.:<span style="color:#CC0066; font-weight:bold;">format</span><span style="color:#006600; font-weight:bold;">&#41;</span>            <span style="color:#006600; font-weight:bold;">&#123;</span>:action<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;create&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;areas&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
  new_club_area GET    <span style="color:#006600; font-weight:bold;">/</span>clubs<span style="color:#006600; font-weight:bold;">/</span>:club_id<span style="color:#006600; font-weight:bold;">/</span>areas<span style="color:#006600; font-weight:bold;">/</span>new<span style="color:#006600; font-weight:bold;">&#40;</span>.:<span style="color:#CC0066; font-weight:bold;">format</span><span style="color:#006600; font-weight:bold;">&#41;</span>        <span style="color:#006600; font-weight:bold;">&#123;</span>:action<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;new&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;areas&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
          clubs GET    <span style="color:#006600; font-weight:bold;">/</span>clubs<span style="color:#006600; font-weight:bold;">&#40;</span>.:<span style="color:#CC0066; font-weight:bold;">format</span><span style="color:#006600; font-weight:bold;">&#41;</span>                           <span style="color:#006600; font-weight:bold;">&#123;</span>:action<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;index&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;clubs&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
                POST   <span style="color:#006600; font-weight:bold;">/</span>clubs<span style="color:#006600; font-weight:bold;">&#40;</span>.:<span style="color:#CC0066; font-weight:bold;">format</span><span style="color:#006600; font-weight:bold;">&#41;</span>                           <span style="color:#006600; font-weight:bold;">&#123;</span>:action<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;create&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;clubs&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
       new_club GET    <span style="color:#006600; font-weight:bold;">/</span>clubs<span style="color:#006600; font-weight:bold;">/</span>new<span style="color:#006600; font-weight:bold;">&#40;</span>.:<span style="color:#CC0066; font-weight:bold;">format</span><span style="color:#006600; font-weight:bold;">&#41;</span>                       <span style="color:#006600; font-weight:bold;">&#123;</span>:action<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;new&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;clubs&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
      edit_club GET    <span style="color:#006600; font-weight:bold;">/</span>clubs<span style="color:#006600; font-weight:bold;">/</span>:id<span style="color:#006600; font-weight:bold;">/</span>edit<span style="color:#006600; font-weight:bold;">&#40;</span>.:<span style="color:#CC0066; font-weight:bold;">format</span><span style="color:#006600; font-weight:bold;">&#41;</span>                  <span style="color:#006600; font-weight:bold;">&#123;</span>:action<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;edit&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;clubs&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
           club GET    <span style="color:#006600; font-weight:bold;">/</span>clubs<span style="color:#006600; font-weight:bold;">/</span>:id<span style="color:#006600; font-weight:bold;">&#40;</span>.:<span style="color:#CC0066; font-weight:bold;">format</span><span style="color:#006600; font-weight:bold;">&#41;</span>                       <span style="color:#006600; font-weight:bold;">&#123;</span>:action<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;show&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;clubs&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
                PUT    <span style="color:#006600; font-weight:bold;">/</span>clubs<span style="color:#006600; font-weight:bold;">/</span>:id<span style="color:#006600; font-weight:bold;">&#40;</span>.:<span style="color:#CC0066; font-weight:bold;">format</span><span style="color:#006600; font-weight:bold;">&#41;</span>                       <span style="color:#006600; font-weight:bold;">&#123;</span>:action<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;update&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;clubs&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
                DELETE <span style="color:#006600; font-weight:bold;">/</span>clubs<span style="color:#006600; font-weight:bold;">/</span>:id<span style="color:#006600; font-weight:bold;">&#40;</span>.:<span style="color:#CC0066; font-weight:bold;">format</span><span style="color:#006600; font-weight:bold;">&#41;</span>                       <span style="color:#006600; font-weight:bold;">&#123;</span>:action<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;destroy&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;clubs&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">The biggest, <em>biggest</em> thing to notice here is the &#8220;:id&#8221; and &#8220;:club_id&#8221; in some of the routes.  This tripped me up a few times.</span></p>
<p><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">Nested routes let you automagically pass &#8220;club_id&#8221; (in this case) to paths.  So in your controller or views you can now use the variable from the first column.  So you can do a </span></p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">redirect_to clubs_path
<span style="color:#008000; font-style:italic;"># instead of:</span>
redirect_to <span style="color:#ff3333; font-weight:bold;">:controller</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;clubs&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;index&quot;</span></pre></div></div>

<p>for example, and it would go to the /clubs/index path and do the right thing.  It also lets you do things like:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">redirect_to new_club_area<span style="color:#006600; font-weight:bold;">&#40;</span>@club<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#008000; font-style:italic;"># sends you to /clubs/1/areas/new</span></pre></div></div>

<p>Note that you have to pass the club before this will work.  This took me <em>forever</em> to figure out, cause sometimes it worked and sometimes it didn&#8217;t.  What I found was looking for either :id or :[object]_id in the routes path would tell you both if you have to pass the route the object or not, but also if you&#8217;re processing the path in the controller, that :club_id will be passed auto-magically to it.  So for the &#8220;/clubs/:club_id/areas/new&#8221; route above, you&#8217;d process it in your areas_controller, and in the &#8216;new&#8217; def, you&#8217;d automatically get club_id for free.  IE:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># in app/controllers/area_controller.rb, possibly via new_club_area_path(@club)</span>
<span style="color:#9966CC; font-weight:bold;">def</span> new
   <span style="color:#0066ff; font-weight:bold;">@club</span> = Club.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:club_id</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
   <span style="color:#0066ff; font-weight:bold;">@area</span> = <span style="color:#0066ff; font-weight:bold;">@club</span>.<span style="color:#9900CC;">areas</span>.<span style="color:#9900CC;">new</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>You know that club_id is being passed because the rake_route for that path has &#8220;club_id&#8221; in it: &#8220;/clubs/:club_id/areas/new&#8221;.</p>
<p>Next up, finishing converting as much of the rest of my code from the controller/action syntax for redirecting and rendering to a more &#8220;restful&#8221; setup.</p>
<p><strong>Update:</strong> There is a cool sounding <a href="http://szeryf.wordpress.com/2010/03/31/introducing-rails-routes-textmate-bundle/">TextMate bundle</a> to help you with some of the brain games needed to understand nested resources.  Hat tip to <a href="http://5by5.tv/rubyshow/112">The Ruby Show</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkinginrails.com/2010/04/at-home-with-nested-routes-and-resources/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

