<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Code Worrier]]></title>
  <link href="http://code-worrier.com/atom.xml" rel="self"/>
  <link href="http://code-worrier.com/"/>
  <updated>2013-04-03T11:04:48-04:00</updated>
  <id>http://code-worrier.com/</id>
  <author>
    <name><![CDATA[Michael Hoffman]]></name>
    <email><![CDATA[m@hof.fm]]></email>
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[On Text Encoding]]></title>
    <link href="http://code-worrier.com/blog/on-text-encoding/"/>
    <updated>2013-03-22T15:10:00-04:00</updated>
    <id>http://code-worrier.com/blog/on-text-encoding</id>
    <content type="html"><![CDATA[<p>I spent a long week grappling with text encoding.
Please enjoy the fruit of my labors:</p>

<!-- more -->




<blockquote class="twitter-tweet" data-partner="tweetdeck"><p>A programmer walks into a coffee shop.Programmer: &#8220;Do you serve cortados here?&#8221;Barista: &#8220;No—wrong cafÃ©. You want the Latin one.&#8221;</p>&mdash; Michael Hoffman (@Hoffm) <a href="https://twitter.com/Hoffm/status/315178182514974720">March 22, 2013</a></blockquote>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Git Bisect: Your Friend in Times of Need]]></title>
    <link href="http://code-worrier.com/blog/git-bisect-basics/"/>
    <updated>2013-03-17T11:38:00-04:00</updated>
    <id>http://code-worrier.com/blog/git-bisect-basics</id>
    <content type="html"><![CDATA[<p>Git bisect is like CPR or a fire extinguisher:
You shouldn&#8217;t need it very often, but when you, it might just save a life.</p>

<p>In case you are not familiar with its splendor, git bisect is a tool for pinpointing the commit that caused a change.
Usually, the change you&#8217;re interested in is the introduction of a bug.
Bisect is handy when, for instance, you discover a regression and you don&#8217;t know what caused it or exactly how long it&#8217;s been around.
Bisect isolates the offending commit with logarithmic efficiency.
It accomplishes this by performing a binary search of the commits on your branch, dividing and conquering until only one commit remains.</p>

<!-- more -->


<p>The basic version of the process is simple.
You provide git with a good commit (one you know is after the change) and a bad commit (one you know is before the change).
Git then asks you a series of yes-or-no questions of the form: How about this other commit here—is it good?
Approximately log-base-2 of the number of questions in your good-bad interval later, you have your culprit.</p>

<p>Here are the commands for navigating through this process:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="nv">$ </span>git bisect start
</span><span class='line'>    <span class="c"># &quot;Let&#39;s do this thing.&quot;</span>
</span><span class='line'><span class="nv">$ </span>git bisect bad
</span><span class='line'>    <span class="c"># &quot;Hey, git, the current commit bad.&quot;</span>
</span><span class='line'><span class="nv">$ </span>git bisect bad <span class="o">[</span>commit <span class="nb">hash </span>or tag name<span class="o">]</span>
</span><span class='line'>    <span class="c"># &quot;This commit hash refers to a bad commit.&quot;</span>
</span><span class='line'>    <span class="c"># (Only one of the previous two commands is required.)</span>
</span><span class='line'><span class="nv">$ </span>git bisect good <span class="o">[</span>commit or <span class="nb">hash</span><span class="o">]</span>
</span><span class='line'>    <span class="c"># &quot;Here&#39;s an earlier point at which I know things were good.&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>At this point, Git will proceed to checkout commits for you.
Your job is to give the thumbs up or thumbs down, Roman-emperor style.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="nv">$ </span>git bisect good
</span><span class='line'>    <span class="c"># &quot;This commit is before the change; look later.&quot;</span>
</span><span class='line'><span class="nv">$ </span>git bisect bad
</span><span class='line'>    <span class="c"># &quot;This commit is after the change; look earlier.&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>At each step you&#8217;ll need to do whatever it is you need to do to check which side of the change the commit is on.
If you&#8217;re working on a Rails app, this might involve running <code>rake db:migrate</code> and <code>bundle install</code>, and then checking whether a particular test passes or a particular behavior of your application is present.</p>

<p>When git zeroes in on its target, it will spit out a message telling you what it found, e.g.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>341c8a0f26e67cf8735552cf8f2b945b80ccb84b is the first bad commit
</span><span class='line'>commit 341c8a0f26e67cf8735552cf8f2b945b80ccb84b
</span><span class='line'>Author: hoffm &lt;m@hof.fm&gt;
</span><span class='line'>Date:   Thu Mar 17 11:19:10 2013 -0500
</span><span class='line'>
</span><span class='line'>    Draft of git bisect post.
</span></code></pre></td></tr></table></div></figure>


<p>At this point, you&#8217;ll probably want to get out of bisect mode and back onto your working branch.
To do this, run</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="nv">$ </span>git bisect reset
</span></code></pre></td></tr></table></div></figure>


<p>That&#8217;s all you really need to know to start using git bisect.</p>

<p>In researching this post, though, I came across some additional commands that are worth learning.
First, if during the bisect process, git lands you on a particularly awkward commit—e.g. one for which the needed environment is hard to replicate from your present position—you can run <code>git bisect skip</code> and git will offer you a different commit to test.</p>

<p>Second—and way cooler—you can automate your yes/no decisions by feeding a custom script to <code>git bisect run</code>.
Git will run the script at every decision point, and will take an exit code of 0 to mean good, and anything else (except 125) to mean bad (details <a href="https://www.kernel.org/pub/software/scm/git/docs/git-bisect.html#_bisect_run">here</a>).
Test frameworks like RSpec <a href="https://www.relishapp.com/rspec/rspec-core/v/2-13/docs/command-line/exit-status">exit with 0</a> only when all tests pass (or none are run), so if you&#8217;re trying to identify the commit that caused a test failure, this is your tool.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to checkout the last git branch you were on]]></title>
    <link href="http://code-worrier.com/blog/git-checkout-dash/"/>
    <updated>2013-03-07T11:10:00-05:00</updated>
    <id>http://code-worrier.com/blog/git-checkout-dash</id>
    <content type="html"><![CDATA[<p>Checking out the last branch you were on is as simple as <code>git checkout -</code>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>11:13:14-hoffm~/src/food52 <span class="o">(</span>develop<span class="o">)</span><span class="nv">$ </span>git checkout master
</span><span class='line'>Switched to branch <span class="s1">&#39;master&#39;</span>
</span><span class='line'>11:13:21-hoffm~/src/food52 <span class="o">(</span>master<span class="o">)</span><span class="nv">$ </span>git checkout -
</span><span class='line'>Switched to branch <span class="s1">&#39;develop&#39;</span>
</span><span class='line'>11:13:23-hoffm~/src/food52 <span class="o">(</span>develop<span class="o">)</span><span class="nv">$ </span>git checkout -
</span><span class='line'>Switched to branch <span class="s1">&#39;master&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p><a href="http://i.imgur.com/yUNhh.gif">Boom</a>!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[3 Surprises from My First Open Source Contribution]]></title>
    <link href="http://code-worrier.com/blog/open-source-surprises/"/>
    <updated>2013-02-27T18:51:00-05:00</updated>
    <id>http://code-worrier.com/blog/open-source-surprises</id>
    <content type="html"><![CDATA[<p>I recently submitted <a href="https://github.com/rails/rails/pull/9347">my first (tiny!) patch</a> to an open source project.
It&#8217;s something I&#8217;d wanted to do for a long time, but couldn&#8217;t figure out how to initiate.
Here are some things that surprised me about the process.</p>

<h3>1. Most of the work is not coding.</h3>

<p>This, as I understand it, is the lifecycle of a garden-variety open source contribution:</p>

<ul>
<li>Find a problem.</li>
<li>Muster your courage.</li>
<li>Describe the problem to the project owners in excruciating detail.</li>
<li>Convince them it&#8217;s a problem worth solving.</li>
<li>Fork the app and get it up and running locally.</li>
<li>Solve the problem (write production code and tests).</li>
<li>Document the solution (docs, commit messages, changelogs).</li>
<li>Propose, explain, and defend your solution (pull request).</li>
<li>Iterate on your solution and its documentation.</li>
</ul>


<!-- more -->


<p>Perhaps the most difficult part of the whole open source contribution process—and, for me, certainly the longest phase—is identifying a patch that you want to write.
If you ask smart, experienced folks how to get started, they&#8217;ll often tell you to look at the open source projects that you use the most and to find something to contribute there.
I think there&#8217;s a lot of value in this advice (and, ultimately, I acted on it), but there s quite a gulf between knowing a piece of software well and finding something you want to change about it, and that others want you to change.</p>

<p>Moreover, the projects you use the most are likely to be high-profile software that a lot of other people use a lot, and that means the barriers to contribution may be relatively high.
Ultimately, my way in was finding a bug in Rails, which, after all, is the piece of open source software I use more than any other.
The only reason I ended up contributing when I did was dumb luck (or at least the law of large numbers): I found a bug.</p>

<p>Even after you figure out what problem you want to solve, writing the code to solve that problem is still only a small fraction of the work that lies ahead.
The process is probably a little different with features, but in the case of a bug fix, there&#8217;s loads to do before you even report the bug.
You need to make sure that the bug is reproducible on the current master branch of the application.
Then you need to determine exactly in which contexts the bug occurs, and to check whether the issue is caused by some problem with—or a corner case intimately related to—the configuration of a particular application that makes use of the open source project.</p>

<p>Much of the rest of the work, as the list above illustrates, is about communication.
Basically, it&#8217;s an exercise in technical writing and in empathy for your readers:
What will the owners of the project want to know about the change I propose?
What will future developers need to know about the change I made?</p>

<p>The importance of communication is, of course, not limited to open source projects.
It&#8217;s a commonplace (but for good reason) that precise, empathic writing is a among the developer&#8217;s most essential skills.
This is never more true than in the context of an open source project with a large number of contributors.
Yes, you will need to actually fix your bug (or build your feature), but chances are, by the time you submit your proposal, you&#8217;ll have done enough investigating and writing that you&#8217;ll already have a good idea how to do it.
Examples used in writing turn into test assertions, which in turn guide production code.
Actually writing the code can feel like an afterthought, especially in the case of a small bug fix like the one I submitted.</p>

<p>In addition to preparatory investigation, communication, and writing the patch, the final piece of the puzzle is getting your code where it needs to be so that others can review it: source control.
I was surprised to find that, for me, source control was one of the most daunting aspects of the whole process.</p>

<h3>2. Source control might be the scariest part.</h3>

<p>I&#8217;m quite comfortable using git, but I&#8217;d never issued a pull request from a forked repo before, so I had some things to learn.
I followed the <a href="http://guides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-code">Rails contributions instructions</a> closely in submitting my original request, and everything went fine.
(<a href="http://steveklabnik.com/">Steve Klabnik</a> has a good project-agnostic guide <a href="http://thechangelog.com/you-yes-you-should-contribute-to-open-source/">here</a>.)
However, when I had to iterate on my work, I was less careful and I ran into trouble.
Somewhere in the process of pulling in changes that others had made in the interim, resolving conflicts, rebasing and pushing to my feature brach, I ended up <a href="https://github.com/rails/rails/pull/9311">garbling</a> my original pull request.
I panicked a bit as I imagined the reactions of all of the Rails core members whom I&#8217;d just spammed.
I closed the sullied request and opened a fresh one.</p>

<p>In retrospect, and as a kind soul pointed out to me, I could simply have fixed the existing request.
But the point is that source control on a large open source project is a high stakes game (or feels that way at any rate), and if this is your first rodeo, you should learn from my mistake and be methodical.
If things go awry, there&#8217;s always <code>git push -f</code>.</p>

<p>The good news is that, having done this once, I&#8217;ll have an easier time with my next patch.
I imagine that the workflow is pretty similar across most projects, so hopefully I won&#8217;t find myself up git&#8217;s creek again any time soon.</p>

<h3>3. It feels like awesome.</h3>

<p>There were lots of reasons I wanted to contribute to open source: to give something back to people from whose work I&#8217;ve benefitted greatly, for the pure challenge of it, and, frankly, to build my resume.
What I did not anticipate was that getting a patch accepted makes you feel like a million bucks.
The Rails community was super supportive of me the entire way, overseeing my fix when they could have written their own patch with less effort.
I truly felt that I was being accepted into a community.</p>

<p>The thought of having even the tiniest effect on a ubiquitous piece of software is thrilling.
Your code will run on so many servers, your name emblazoned on so many replications of the changelog.
This thrill may be a narcissistic one, but I feel it&#8217;s alright to revel in it.
What&#8217;s wrong with feeling satisfied that you&#8217;ve applied your skills to improve a product that hundreds (or thousands, or millions) of people use to build cool stuff?</p>

<p>Contributing to open source is a great high; I can&#8217;t wait to get my next fix.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[404 and 500 Error Pages in Rails]]></title>
    <link href="http://code-worrier.com/blog/error-pages-in-rails/"/>
    <updated>2013-02-09T13:43:00-05:00</updated>
    <id>http://code-worrier.com/blog/error-pages-in-rails</id>
    <content type="html"><![CDATA[<p>There are many approaches to responding to failed requests in Rails.
Here I offer the way I currently favor setting things up.
I&#8217;m hoping that this might start a conversation about best practices;
I&#8217;m sure I could do better!</p>

<p>The default way Rails handles requests to which your application does not have a contentful response is to serve up static HTML documents stored in the public directory.
In particular, 500 (server error) and 404 (not found) responses result in the application&#8217;s rendering <code>500.html</code> and <code>404.html</code>, respectively.</p>

<!-- more -->


<p>This default approach is solid—it can be relied upon to display the correct pages in the correct conditions— but it does not allow customization of those pages.
These error pages can&#8217;t execute ruby code, and so they can&#8217;t use your layouts, can&#8217;t interact with your data, and can&#8217;t vary based on conditions such as the time, the user, or the nature of the request.
Such customizations can imporve user experience and reduce bounce rates when things go wrong.</p>

<p>For these reasons, it&#8217;s tempting to rescue all kinds of exceptions and render full-blown erb templates in response to them.
I think this strategy is reasonable in the case of 404 errors, and here&#8217;s how I do it:</p>

<figure class='code'><figcaption><span>app/controllers/application_controller.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">ApplicationController</span> <span class="o">&lt;</span> <span class="no">ActionController</span><span class="o">::</span><span class="no">Base</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># custom 404</span>
</span><span class='line'>  <span class="k">unless</span> <span class="no">Rails</span><span class="o">.</span><span class="n">application</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">consider_all_requests_local</span>
</span><span class='line'>    <span class="n">rescue_from</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">RecordNotFound</span><span class="p">,</span>
</span><span class='line'>                <span class="no">ActionController</span><span class="o">::</span><span class="no">RoutingError</span><span class="p">,</span>
</span><span class='line'>                <span class="no">ActionController</span><span class="o">::</span><span class="no">UnknownController</span><span class="p">,</span>
</span><span class='line'>                <span class="no">ActionController</span><span class="o">::</span><span class="no">UnknownAction</span><span class="p">,</span>
</span><span class='line'>                <span class="no">ActionController</span><span class="o">::</span><span class="no">MethodNotAllowed</span> <span class="k">do</span> <span class="o">|</span><span class="n">exception</span><span class="o">|</span>
</span><span class='line'>
</span><span class='line'>      <span class="c1"># Put loggers here, if desired.</span>
</span><span class='line'>
</span><span class='line'>      <span class="n">redirect_to</span> <span class="n">four_oh_four_path</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>You can define <code>four_oh_four_path</code> and the corresponding action and template however you&#8217;d like.
A similar but lighter-weight approach would be to render a template in your <code>app/view/shared/</code> directory instead of redirecting to an action.
In any case, we wrap this rescue block in the <code>consider_all_requests_local</code> condition, because we&#8217;d still like to get an informative stack trace in development mode.</p>

<p>It&#8217;s tempting to treat 500s analogously, but I think that would be a mistake.
If your application is returning a 500 response, chances are something has gone wrong, and the behavior it&#8217;s exhibiting is not what you expected.
Given this, who&#8217;s to say whether or not your fancy custom 500 page will load?
What if the bug is in the very code that catches and responds to errors?</p>

<p>For these reasons, it is much safer to take the default approach to 500 errors.
Don&#8217;t like your static 500 page?
My suggestion is: make sure that people rarely get to see it.</p>

<p>To get some inspiration for such pages, you could the <code>/500</code> path your favorite websites.
<a href="https://github.com/500" target="_blank">Here</a>
<a href="https://twitter.com/500" target="_blank">are</a>
<a href="https://path.com/500" target="_blank">some</a>
<a href="http://www.heroku.com/500" target="_blank">examples</a>.
And
<a href="http://food52.com/500" target="_blank">here is the page</a>
I recently made for Food52.
(Thanks to
<a href="http://ryanahamilton.com/" target="_blank">Ryan</a>
for finding the image and helping make the page responsive!)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Try out Routes in the Rails Console]]></title>
    <link href="http://code-worrier.com/blog/test-routes-in-rails-console/"/>
    <updated>2013-02-04T20:23:00-05:00</updated>
    <id>http://code-worrier.com/blog/test-routes-in-rails-console</id>
    <content type="html"><![CDATA[<p>How do you quickly check what path a certain route helper maps to?</p>

<p>One method I use a lot is to grep <code>rake routes</code>.
So, let&#8217;s say I&#8217;m looking for a route that has to do with comment approval.
In that case, I might run <code>rake routes | grep approve</code>.
And there&#8217;s my answer:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">approve_comment</span> <span class="no">POST</span>  <span class="sr">/comments/</span><span class="ss">:id</span><span class="o">/</span><span class="n">approve</span><span class="p">(</span><span class="o">.</span><span class="ss">:format</span><span class="p">)</span>  <span class="p">{</span><span class="ss">:action</span><span class="o">=&gt;</span><span class="s2">&quot;approve&quot;</span><span class="p">,</span> <span class="ss">:controller</span><span class="o">=&gt;</span><span class="s2">&quot;comments&quot;</span><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>There&#8217;s one problem with this, though: It&#8217;s
  <a href="http://i.minus.com/iBKc6u9W2Zreb.gif" target="_blank">slooooow</a>.</p>

<!-- more -->


<p>It&#8217;s slow because running <code>rake routes</code> loads up your whole Rails environment.
If your workflow is anything like mine, though, chances are you&#8217;ve already have your environement loaded in another tab: the one where you have a Rails console running.
So in cases where you have some idea what the name of the route is, testing it  out in the console can save you time.
And, luckily, it couldn&#8217;t be simpler.</p>

<p>In the Rails console, the variable <code>app</code> holds a session object on which you can call path and url helpers as instance methods.
So away we go:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="o">&gt;&gt;</span> <span class="n">app</span><span class="o">.</span><span class="n">approve_comment_path</span><span class="p">(</span><span class="no">Comment</span><span class="o">.</span><span class="n">last</span><span class="o">.</span><span class="n">id</span><span class="p">)</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="s2">&quot;/comments/138138/approve&quot;</span>
</span><span class='line'><span class="o">&gt;&gt;</span> <span class="n">app</span><span class="o">.</span><span class="n">user_path</span><span class="p">(</span><span class="no">User</span><span class="o">.</span><span class="n">find_by_login</span><span class="p">(</span><span class="s2">&quot;Michael Hoffman&quot;</span><span class="p">))</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="s2">&quot;/users/784-michael-hoffman&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>That&#8217;s all there is to it.</p>

<p><em>(See <a href="code-worrier.com/blog/custom-slugs-in-rails/">this post</a> for my way of generating custom slugs like the one in that user path.)</em></p>

<p><em>(Searching around a bit, I think I originally got this tip from <a href="http://37signals.com/svn/posts/3176-three-quick-rails-console-tips" target="_bank">this wonderful post</a>. Read it to learn about other useful things you can accomplish with <code>app</code>.)</em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Custom Slugs in Rails without Gems]]></title>
    <link href="http://code-worrier.com/blog/custom-slugs-in-rails/"/>
    <updated>2013-02-01T16:48:00-05:00</updated>
    <id>http://code-worrier.com/blog/custom-slugs-in-rails</id>
    <content type="html"><![CDATA[<p>There are some
 <a href="https://github.com/norman/friendly_id" target="_blank">nice</a>
 <a href="https://github.com/Sutto/slugged" target="_blank">gems</a>
out there to help you create and manage human-readable slugs in Rails.
However, our requirements at Food52 were simple enough—and different enough from the standard case—that I thought I&#8217;d have a go at building a slugging system from scratch.</p>

<h2>The Problem</h2>

<p>As an example of the desired behavior, given that we want to use the attribute <code>name</code> to generate slugs for users, and given that my user id is 784 and my name is &#8220;Michael Hoffman&#8221;, the slug for my user page should be:</p>

<blockquote><p><code>"784-michael-hoffman"</code></p></blockquote>

<p>(We leave the id in because we like it there!
It makes debugging easier and it allows us to use Active Record <code>find</code> to look up objects from params.)</p>

<p>Furthermore, we want our slugs to adapt gracefully to changing circumstances.
So, if my name changes, the slug should do&#8230;something smart.</p>

<p>Getting a little more abstract, our requirements are as follows:</p>

<!-- more -->


<ol>
<li>It should be possible to opt models in to custom slugging.</li>
<li>Custom slugs should have the form: <code>[:id]-[parameterized-string]</code>.</li>
<li>The string to be parameterized should be configurable per model.</li>
<li>Relevant changes in records&#8217; attributes should be reflected in the slug.</li>
<li>Records should have only one slug apiece, even as attribute values change.</li>
</ol>


<p>That&#8217;s the problem.
In this post, I explain my solution.
Even if your custom slug needs are slightly different, I hope the general strategy might be useful.</p>

<h2>A Naive Attempt</h2>

<p>Before we begin, we need some background on how Rails handles slugs by default.
Active Record has an instance method <code>#to_param</code>, which Action Pack uses to create URLs.
By default, <code>#to_param</code> returns the id of the object, converted to a string.
(See the source,
 <a href="http://apidock.com/rails/ActiveRecord/Integration/to_param" target="_blank">here</a>
.)
Thus, the default path to my user page (given standard resourceful routing) would be <code>"/users/784"</code>.
However, it is possible to customize slugs by overriding this method on a model-by-model basis.</p>

<p>So, the naive way to get the result we want would be to add a method like this one to the User model:</p>

<figure class='code'><figcaption><span>app/model/user.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># [...]</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">to_param</span>
</span><span class='line'>    <span class="o">[</span><span class="nb">id</span><span class="p">,</span> <span class="nb">name</span><span class="o">.</span><span class="n">parameterize</span><span class="o">].</span><span class="n">join</span><span class="p">(</span><span class="s2">&quot;-&quot;</span><span class="p">)</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>This approach meets the first four requirements, but there are two problems with it.
First, we&#8217;re going to have to repeat this method (modulo the string to be parameterized) in all the models for which we want human-readable slugs.</p>

<p>Second, it fails to meet the fifth requirement.
Specifically, as users&#8217; names change, we will end up with many different addresses that point to the same content.
For instance, if I change my name to, say, &#8220;Michael Danger Hoffman&#8221;, then Action-Pack-generated links to my profile will use <code>784-michael-danger-hoffman</code>, but anyone who&#8217;d previously copied the link, or bookmarked it, will be able to reach the same page by visiting the old slug.
Not only is that confusing to humans, it&#8217;s also confusing to search bots.
Confusing search bots makes them <a href="http://www.geekologie.com/2011/09/22/stupid-robots.gif" target="_blank">sad</a>!</p>

<h2>A Better Solution</h2>

<p>Let&#8217;s build on the naive solution to create a slugging system that can be applied succinctly across many models.
(We&#8217;ll deal with the duplicate content problem in a another pass.)</p>

<p>Given a model, there are only two things we need to know about it with regard to slugging:</p>

<ul>
<li>Should it use custom slugs?</li>
<li>If so, what string should it use to create them?</li>
</ul>


<p>Ideally, we want a system that would allow us to opt models in to custom sluging, and simultaneously to specify how to calculate the strings those models should use to create slugs.</p>

<p>We can do this by adding a class method to <code>ActiveRecord::Base</code> that redefines <code>#to_param</code>.</p>

<figure class='code'><figcaption><span>lib/app_utilities.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">module</span> <span class="nn">ActiveRecordExtensions</span>
</span><span class='line'>  <span class="kp">extend</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">Concern</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">module</span> <span class="nn">ClassMethods</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1"># Override &#39;to_param&#39;.</span>
</span><span class='line'>    <span class="k">def</span> <span class="nf">custom_slugs_with</span><span class="p">(</span><span class="n">seed</span><span class="p">)</span>
</span><span class='line'>      <span class="nb">self</span><span class="o">.</span><span class="n">redefine_method</span><span class="p">(</span><span class="ss">:to_param</span><span class="p">)</span> <span class="k">do</span>
</span><span class='line'>        <span class="o">[</span><span class="nb">id</span><span class="p">,</span> <span class="nb">self</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">seed</span><span class="p">)</span><span class="o">.</span><span class="n">parameterize</span><span class="o">].</span><span class="n">join</span><span class="p">(</span><span class="s2">&quot;-&quot;</span><span class="p">)</span>
</span><span class='line'>      <span class="k">end</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># Include above methods in all models.</span>
</span><span class='line'>  <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="ss">:include</span><span class="p">,</span> <span class="no">ActiveRecordExtensions</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&#8217;re going to want to make <code>::custom_slugs_with</code> available in all models, so let&#8217;s require this file in an initializer:</p>

<figure class='code'><figcaption><span>config/initializers/active_record_extensions.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="nb">require</span> <span class="s2">&quot;app_util&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Requiring this file will execute the include call, including <code>ActiveRecordExtensions</code> in <code>ActiveRecord::Base</code> (andmaking the module&#8217;s methods available to Active Record&#8217;s descendants).
The <code>::custom_slugs_with</code> method takes as an argument the name of an instance method that specifies the string to be used in the slug.
So, for instance, adding this line to the User model:</p>

<figure class='code'><figcaption><span>app/model/user.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
</span><span class='line'>  <span class="n">custom_slugs_with</span><span class="p">(</span><span class="ss">:name</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># [...]</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>will serve the same purpose as the <code>to_param</code> method in our original, naive solution.</p>

<p>When we want to retrieve the object from its slug, as will often be the case in controller actions, we can use a simple Active Record find. E.g.</p>

<figure class='code'><figcaption><span>app/controllers/users_controller.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">UsersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">#[...]</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">show</span>
</span><span class='line'>    <span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</span><span class="p">)</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>Find is smart enough to parse strings like these and extract the correct id.</p>

<p>Lastly, if we wanted to use an explicit method to generate the string (instead of relying on the attribute, <code>name</code>), we could define that method in the User model and pass its symbolized name into the <code>::custom_slugs_with</code>.</p>

<h2>Keeping Slugs Consistent</h2>

<p>We still have a lingering problem.
The attributes from which these custom slugs are generated might change.
Moreover, we might be installing this system in an application that already has a different slugging system.
Both of these eventualities will lead us into to the uncomfortable situation I mentioned above: having multiple URLs that refer to the same content.
To get around this problem, let&#8217;s treat the record&#8217;s current slug—the one we get when we call <code>#to_param</code> on it—as canonical.
Then, when we get a request for an out-of-date or incorrect slug, we can redirect the canonical one.</p>

<p>We&#8217;ll do this in basically the same way in every controller, so let&#8217;s add our new code to the application controller.
The first method checks if the slug is canonical.
The second redirects to the canonical slug, as retrieved by Action Pack.</p>

<figure class='code'><figcaption><span>app/controllers/application_controller.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">ApplicationController</span> <span class="o">&lt;</span> <span class="no">ActionController</span><span class="o">::</span><span class="no">Base</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">#[...]</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">##</span>
</span><span class='line'>  <span class="c1"># Check if the current slug is not the cannonical one.</span>
</span><span class='line'>  <span class="k">def</span> <span class="nf">bad_slug?</span><span class="p">(</span><span class="n">object</span><span class="p">)</span>
</span><span class='line'>    <span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</span> <span class="o">!=</span> <span class="n">object</span><span class="o">.</span><span class="n">to_param</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">##</span>
</span><span class='line'>  <span class="c1"># 301 redirect to canonical slug.</span>
</span><span class='line'>  <span class="k">def</span> <span class="nf">redirect_to_good_slug</span><span class="p">(</span><span class="n">object</span><span class="p">)</span>
</span><span class='line'>      <span class="n">redirect_to</span> <span class="n">params</span><span class="o">.</span><span class="n">merge</span><span class="p">({</span>
</span><span class='line'>                    <span class="ss">:controller</span> <span class="o">=&gt;</span> <span class="n">controller_name</span><span class="p">,</span>
</span><span class='line'>                    <span class="ss">:action</span> <span class="o">=&gt;</span> <span class="n">params</span><span class="o">[</span><span class="ss">:action</span><span class="o">]</span><span class="p">,</span>
</span><span class='line'>                    <span class="ss">:id</span> <span class="o">=&gt;</span> <span class="n">object</span><span class="o">.</span><span class="n">to_param</span><span class="p">,</span>
</span><span class='line'>                    <span class="ss">:status</span> <span class="o">=&gt;</span> <span class="ss">:moved_permanently</span>
</span><span class='line'>                  <span class="p">})</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we can call these methods from controller actions that we want to redirect non-canonical slugs:</p>

<figure class='code'><figcaption><span>app/controllers/users_controller.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">UsersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">#[...]</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">show</span>
</span><span class='line'>    <span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</span><span class="p">)</span>
</span><span class='line'>    <span class="n">redirect_to_good_slug</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span> <span class="ow">and</span> <span class="k">return</span> <span class="k">if</span> <span class="n">bad_slug?</span><span class="p">(</span><span class="vi">@user</span><span class="p">)</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>This gets the job done.
Requests for <code>"/users/784-something-totally-weird"</code> will redirect to <code>"/users/784-Michael-Hoffman"</code> as desired.
Changing my name will change the target of this redirection.</p>

<p>I must admit, though, that I find this solution less than ideal.
It requires repeating the redirect-if-bad-slug code in many actions.
However, I have not yet found a better approach.
If you have one, I&#8217;d love to hear it!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Put Your Git Branch in Your Bash Prompt]]></title>
    <link href="http://code-worrier.com/blog/git-branch-in-bash-prompt/"/>
    <updated>2013-01-24T21:54:00-05:00</updated>
    <id>http://code-worrier.com/blog/git-branch-in-bash-prompt</id>
    <content type="html"><![CDATA[<p>Lots of folks were interested in getting <a href="http://code-worrier.com/blog/autocomplete-git/">git autocomplete</a> going in bash, so I thought I&#8217;d offer another useful git/bash tip.
This one was suggested by <a href="http://twitter.com/S_2K">Stephan</a> in the comments of that earlier post.</p>

<p>If you&#8217;re using git properly and collaborating on a project, chances are you find yourself changing branches often.
This can be quite disorienting.
You deploy from the master branch, then get back to that bug fix you were about to work except for—whoops!—now you commited that fix to master and have to <a href="http://d22zlbw5ff7yk5.cloudfront.net/images/cm-23141-050624c7335479.gif">back away slowly</a>.
Confusions like this one can easily be avoided by putting you branch name front-and-center: at the end of your bash prompt.
Here&#8217;s how.</p>

<!-- more -->


<p>Get the <code>git-promt.sh</code> script <a href="https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh">here</a>.
Put it somewhere like <code>~/.git-prompt.sh</code>.
If you want to be all CLI about it, you could just run:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>curl https://raw.github.com/git/git/master/contrib/completion/git-prompt.sh -o ~/.git-prompt.sh
</span></code></pre></td></tr></table></div></figure>


<p>Now modify your your bash profile (it&#8217;s at <code>~/.bash-profile</code>, in case you&#8217;re new to this stuff).
Before the part of the file that declares what your prompt will look like (<code>PS1=[...]</code>), load in the script you just downloaded, like so:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="c"># Load in the git branch prompt script.</span>
</span><span class='line'><span class="nb">source</span> ~/.git-prompt.sh
</span></code></pre></td></tr></table></div></figure>


<p>Now add <code>\$(__git_ps1)</code> to your prompt declaration.
You can put it wherever you like, but I think it&#8217;s best suited for the very end, right before the final dollar sign (<code>\$</code>)
If you want to get all fancy, you can make it a pretty color.
My declaration looks like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="nv">PS1</span><span class="o">=</span><span class="s2">&quot;\[$GREEN\]\t\[$RED\]-\[$BLUE\]\u\[$YELLOW\]\[$YELLOW\]\w\[\033[m\]\[$MAGENTA\]\$(__git_ps1)\[$WHITE\]\$ &quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>(See <a href="https://wiki.archlinux.org/index.php/Color_Bash_Prompt">here</a> for color definitions.)</p>

<p>This declaration results in a prompt looks like this when I&#8217;m in the directory <code>~/src/food52</code> and on the branch <code>develop</code>:</p>

<p><img src="http://f.cl.ly/items/0b3e1Q2R1I3b2T2a1q03/Screen%20Shot%202013-01-25%20at%2010.31.45%20AM.png" alt="" /></p>

<p>That&#8217;s it. Never git lost again!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How do you prevent ActionMailer from spamming people in development?]]></title>
    <link href="http://code-worrier.com/blog/rails-intercept-emails-in-dev/"/>
    <updated>2012-10-18T19:09:00-04:00</updated>
    <id>http://code-worrier.com/blog/rails-intercept-emails-in-dev</id>
    <content type="html"><![CDATA[<p>I&#8217;ve been working on a Rails app that contains lots of mailers with hard-coded recipients.
For instance, here&#8217;s a mailer that we use to notify folks when someone asks an urgent question on our hotline:</p>

<figure class='code'><figcaption><span>hotline_mailer.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">HotlineMailer</span> <span class="o">&lt;</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">default</span> <span class="ss">:from</span> <span class="o">=&gt;</span> <span class="s2">&quot;notifications@mywebapp.com&quot;</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">notify_urgent_question</span><span class="p">(</span><span class="n">question</span><span class="p">)</span>
</span><span class='line'>    <span class="vi">@question</span> <span class="o">=</span> <span class="n">question</span>
</span><span class='line'>    <span class="nb">send</span><span class="p">(</span> <span class="ss">:to</span> <span class="o">=&gt;</span> <span class="s2">&quot;urgent@mywebapp.com&quot;</span><span class="p">,</span>
</span><span class='line'>          <span class="ss">:subject</span> <span class="o">=&gt;</span> <span class="s2">&quot;Urgent: </span><span class="si">#{</span><span class="n">question</span><span class="o">.</span><span class="n">title</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># Other mailer methods...</span>
</span><span class='line'>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>The email address &#8220;urgent@mywebapp.com&#8221; generates emails to many people.
We handle membership in Google apps.</p>

<p>Left to its own devices, this mailer will trigger an email to that list of people every time you hit the controller action that calls for it to be delivered.</p>

<p>That&#8217;s bad news if you&#8217;re just testing out the action in your development environment.
You have a group of people who are getting annoying emails for no reason, and you may not even be getting the emails yourself!</p>

<!-- more -->


<p>We might consider using a constant in place of the email address, and initializing this constant differently in different environments.
However, this approach has two shortcomings:</p>

<ol>
<li>If we have more than one person working on the project, it&#8217;s hard to choose which email address to use as the default for development.</li>
<li>We&#8217;ll all have to remember to make a new constant every time we have a new email address that needs to be masked.</li>
</ol>


<p>Luckily, ActionMailer makes a better solution possible. Here&#8217;s what you need to do:</p>

<figure class='code'><figcaption><span>lib/development_mail_interceptor.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">DevelopmentMailInterceptor</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">delivering_email</span><span class="p">(</span><span class="n">message</span><span class="p">)</span>
</span><span class='line'>    <span class="n">message</span><span class="o">.</span><span class="n">to</span> <span class="o">=</span> <span class="n">defined?</span><span class="p">(</span><span class="no">PERSONAL_EMAIL</span><span class="p">)</span> <span class="p">?</span> <span class="no">PERSONAL_EMAIL</span> <span class="p">:</span> <span class="s2">&quot;default@mywebapp.com&quot;</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span>config/initializers/mailer_config.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="nb">require</span> <span class="s1">&#39;development_mail_interceptor&#39;</span>
</span><span class='line'><span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span><span class="o">.</span><span class="n">register_interceptor</span><span class="p">(</span><span class="no">DevelopmentMailInterceptor</span><span class="p">)</span> <span class="k">if</span>  <span class="no">Rails</span><span class="o">.</span><span class="n">env</span><span class="o">.</span><span class="n">development?</span>
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span>config/initializers/personal_email.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="no">PERSONAL_EMAIL</span> <span class="o">=</span> <span class="s2">&quot;personal@mywebapp.com&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Lastly, you want to git ignore <code>config/initializers/personal_email.rb</code>, and tell your collaborators to create their own local version of the file.
(You want to git ignore it so that it can be customized per dev box.)</p>

<p>What does this all do?
When you call <code>#deliver</code> on an message, if the environment is development, the <code>to</code> option on the mailer is overridden with your personal address.
(In this example, it&#8217;s &#8220;personal@mywebapp.com&#8221;).
That&#8217;s it!
We set up the default in the interceptor in case one of our collaborators doesn&#8217;t get the message about creating <code>personal_email.rb</code>.
In that case, that person&#8217;s dev mailer emails will be sent to the default you set in the interceptor class.
(In this example it&#8217;s &#8220;default@mywebapp.com&#8221;)</p>

<p>When I first struck upon this solution, I was worried that the interceptor would prevent me from seeing who would actually receive a given email if the code were running in production.
I needn&#8217;t have worried.
The interceptor only affects the behavior of the <code>#deliver</code> method; the message object remains intact.
So, if you call</p>

<blockquote><p><code>HotlineMailer.notify_urgent_question(question)</code></p></blockquote>

<p>you&#8217;ll find that object returned has the attribute <code>&lt;To: urgent@mywebapp.com&gt;</code>.
That&#8217;s the address this email would go to if the interceptor did not interfere.
However, if you call</p>

<blockquote><p><code>HotlineMailer.notify_urgent_question(question).deliver</code>,</p></blockquote>

<p>the object returned has the attribute <code>&lt;To: personal@mywebapp.com&gt;</code> and sends the email to that address.</p>

<p>I think this is an effective solution, but it could be better.
Forcing developers to manually create files in order to properly use your repo is not ideal.
If you have an idea to improve this system, I&#8217;d love to hear about it in the comments.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A tiny benchmarking utility]]></title>
    <link href="http://code-worrier.com/blog/tiny-benchmarking/"/>
    <updated>2012-09-30T14:54:00-04:00</updated>
    <id>http://code-worrier.com/blog/tiny-benchmarking</id>
    <content type="html"><![CDATA[<p>While working on a longer (forthcoming) post, I wrote a little benchmarking utility that I want to share.
Here it is:</p>

<figure class='code'><figcaption><span>tiny_timer.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">module</span> <span class="nn">TinyTimer</span>
</span><span class='line'>  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">benchmark</span><span class="p">(</span><span class="n">samples</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">times</span> <span class="o">=</span> <span class="o">[]</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">samples</span><span class="o">.</span><span class="n">times</span> <span class="k">do</span>
</span><span class='line'>      <span class="n">start</span> <span class="o">=</span> <span class="no">Time</span><span class="o">.</span><span class="n">now</span>
</span><span class='line'>      <span class="k">yield</span>
</span><span class='line'>      <span class="n">times</span> <span class="o">&lt;&lt;</span> <span class="p">(</span><span class="no">Time</span><span class="o">.</span><span class="n">now</span> <span class="o">-</span> <span class="n">start</span><span class="p">)</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">times</span><span class="o">.</span><span class="n">sum</span> <span class="o">/</span> <span class="n">samples</span><span class="o">.</span><span class="n">to_f</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>




<!-- more -->


<p>As you can see, this method runs a specified number of trials of a block of code and returns the average time in seconds it took to execute the block.
Usage examples:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="o">&gt;&gt;</span> <span class="nb">require</span> <span class="s1">&#39;tiny_timer&#39;</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="o">[</span><span class="s2">&quot;TinyTimer&quot;</span><span class="o">]</span>
</span><span class='line'><span class="o">&gt;&gt;</span> <span class="no">TinyTimer</span><span class="o">.</span><span class="n">benchmark</span><span class="p">{</span> <span class="p">(</span><span class="mi">0</span><span class="o">.</span><span class="n">.</span><span class="mi">100000</span><span class="p">)</span><span class="o">.</span><span class="n">map</span><span class="p">{</span><span class="nb">rand</span><span class="p">(</span><span class="mi">10</span><span class="p">)}</span><span class="o">.</span><span class="n">sort</span> <span class="p">}</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="mi">0</span><span class="o">.</span><span class="mo">0670641</span>
</span><span class='line'><span class="o">&gt;&gt;</span> <span class="no">TinyTimer</span><span class="o">.</span><span class="n">benchmark</span><span class="p">(</span><span class="mi">100</span><span class="p">){</span> <span class="mi">2</span><span class="o">**</span><span class="mi">1000000</span> <span class="p">}</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="mi">0</span><span class="o">.</span><span class="mo">00</span><span class="mi">841815</span>
</span></code></pre></td></tr></table></div></figure>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Invoke a Rake Task from Another Task]]></title>
    <link href="http://code-worrier.com/blog/embedded-rake-tasks/"/>
    <updated>2012-09-25T17:02:00-04:00</updated>
    <id>http://code-worrier.com/blog/embedded-rake-tasks</id>
    <content type="html"><![CDATA[<p>You can invoke a rake task from another rake task.
Here&#8217;s how:</p>

<figure class='code'><figcaption><span>examples.rake</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">namespace</span> <span class="ss">:examples</span> <span class="k">do</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">desc</span> <span class="s2">&quot;Inner task.&quot;</span>
</span><span class='line'>  <span class="n">task</span> <span class="ss">:inner_task</span> <span class="o">=&gt;</span> <span class="ss">:environment</span> <span class="k">do</span>
</span><span class='line'>    <span class="c1"># Some code that accomplishes a task.</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">desc</span> <span class="s2">&quot;Outer task.&quot;</span>
</span><span class='line'>  <span class="n">task</span> <span class="ss">:outer_task</span> <span class="k">do</span>
</span><span class='line'>    <span class="c1"># Some code.</span>
</span><span class='line'>    <span class="no">Rake</span><span class="o">::</span><span class="no">Task</span><span class="o">[</span><span class="s1">&#39;examples:inner_task&#39;</span><span class="o">].</span><span class="n">execute</span> <span class="c1">#Execute innter task.</span>
</span><span class='line'>    <span class="c1"># Some other code.</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>




<!-- more -->


<p>Now when you execute <code>rake examples:outer_task</code>, you will execute the inner task in whatever context you placed it.
Using this contruction allows you to break down unweildy tasks into smaller ones, which perhaps you&#8217;ll want to reuse in different contexts elsewhere.</p>

<p>Here&#8217;s a toy examples that actually works:</p>

<figure class='code'><figcaption><span>toys.rake</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">namespace</span> <span class="ss">:toys</span> <span class="k">do</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">desc</span> <span class="s2">&quot;Inner task: Square the value.&quot;</span>
</span><span class='line'>  <span class="n">task</span> <span class="ss">:square</span> <span class="k">do</span>
</span><span class='line'>    <span class="vi">@value</span> <span class="o">*=</span> <span class="vi">@value</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">desc</span> <span class="s2">&quot;Outer task: Initialize the value and square thrice.&quot;</span>
</span><span class='line'>  <span class="n">task</span> <span class="ss">:square_three_times</span> <span class="k">do</span>
</span><span class='line'>    <span class="vi">@value</span> <span class="o">=</span> <span class="mi">2</span>
</span><span class='line'>    <span class="mi">3</span><span class="o">.</span><span class="n">times</span><span class="p">{</span><span class="no">Rake</span><span class="o">::</span><span class="no">Task</span><span class="o">[</span><span class="s1">&#39;toys:square&#39;</span><span class="o">].</span><span class="n">execute</span><span class="p">}</span>
</span><span class='line'>    <span class="nb">puts</span> <span class="s2">&quot;The value is </span><span class="si">#{</span><span class="vi">@value</span><span class="si">}</span><span class="s2">.&quot;</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>Running this in the shell, we get:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="nv">$ </span>rake toys:square_three_times --trace
</span><span class='line'>** Invoke toys:square_three_times <span class="o">(</span>first_time<span class="o">)</span>
</span><span class='line'>** Execute toys:square_three_times
</span><span class='line'>** Execute toys:square
</span><span class='line'>** Execute toys:square
</span><span class='line'>** Execute toys:square
</span><span class='line'>The value is 256.
</span></code></pre></td></tr></table></div></figure>


<p>And yes, I know you&#8217;re thinking it now: rake tasks can call themselves quite happily.</p>

<p>You can also invoke rake tasks from within ActiveRecord migrations.
This can come in handy when you want to initialize a bunch of data immeidately after altering the database schema.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Quick Tip: Autocomplete Git Commands and Branch Names in Bash]]></title>
    <link href="http://code-worrier.com/blog/autocomplete-git/"/>
    <updated>2012-09-09T21:44:00-04:00</updated>
    <id>http://code-worrier.com/blog/autocomplete-git</id>
    <content type="html"><![CDATA[<p>In bash in Mac OS X, you can use [TAB] to autocomplete file paths.
Wouldn&#8217;t if be nice if you could do the same with git commands and branch names?</p>

<p>You can.
Here&#8217;s how.</p>

<!-- more -->


<p>First get the <code>git-completion.bash</code> script (view it <a href="https://github.com/git/git/blob/master/contrib/completion/git-completion.bash">here</a>) and put it in your home directory:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>curl https://raw.github.com/git/git/master/contrib/completion/git-completion.bash -o ~/.git-completion.bash
</span></code></pre></td></tr></table></div></figure>


<p>Next, add the following lines to your <code>.bash_profile</code>.
This tells bash to execute the git autocomplete script if it exists.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="k">if</span> <span class="o">[</span> -f ~/.git-completion.bash <span class="o">]</span>; <span class="k">then</span>
</span><span class='line'>  . ~/.git-completion.bash
</span><span class='line'><span class="k">fi</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now open a new shell, <code>cd</code> into a git repo, and start typing a git command.
You should find that [TAB] now autocompletes git commands and git branch names.</p>

<p>For example, if you type <code>git</code> then add a space and hit [TAB], you&#8217;ll get a readout like this, which lists all available git commands:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>add                 filter-branch       reflog
</span><span class='line'>am                  format-patch        relink
</span><span class='line'>annotate            fsck                remote
</span><span class='line'>apply               gc                  repack
</span><span class='line'>archive             get-tar-commit-id   replace
</span><span class='line'>bisect              grep                request-pull
</span><span class='line'>blame               gui                 reset
</span><span class='line'>branch              <span class="nb">help                </span>revert
</span><span class='line'>bundle              imap-send           rm
</span><span class='line'>checkout            init                send-email
</span><span class='line'>cherry              instaweb            shortlog
</span><span class='line'>cherry-pick         log                 show
</span><span class='line'>citool              merge               show-branch
</span><span class='line'>clean               mergetool           stage
</span><span class='line'>clone               mv                  stash
</span><span class='line'>commit              name-rev            status
</span><span class='line'>config              notes               submodule
</span><span class='line'>describe            p4                  svn
</span><span class='line'>diff                pull                tag
</span><span class='line'>difftool            push                whatchanged
</span><span class='line'>fetch               rebase
</span></code></pre></td></tr></table></div></figure>


<p>Now to learn what some of these more exotic git commands do!
What&#8217;s your favorite git command?</p>

<p>(I learned this way of installing <code>git-completion.bash</code> <a href="http://apple.stackexchange.com/questions/55875/how-can-i-get-git-to-autocomplete-e-g-branches-at-the-command-line/55886#55886">here</a>.)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[What does Ruby's 'next' keyword return?]]></title>
    <link href="http://code-worrier.com/blog/map-and-next/"/>
    <updated>2012-09-04T19:55:00-04:00</updated>
    <id>http://code-worrier.com/blog/map-and-next</id>
    <content type="html"><![CDATA[<p>Pop quiz, hotshot:
<strong>What does the following Ruby expression return?</strong></p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="o">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="o">].</span><span class="n">map</span><span class="p">{</span> <span class="o">|</span><span class="n">n</span><span class="o">|</span> <span class="k">next</span> <span class="k">if</span> <span class="n">n</span><span class="o">.</span><span class="n">even?</span> <span class="p">;</span> <span class="mi">2</span><span class="o">*</span><span class="n">n</span> <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>




<!-- more -->


<p>It turns out I&#8217;m not much of a hotshot, because this how I reasoned through this question while at work today:</p>

<ol>
<li><code>Array#map</code> evaluates the block for each member of the array and returns a new array of the returned values, in order.</li>
<li>When <code>n == 1</code> or <code>n == 3</code>, the block evaluates to <code>2*n</code>.</li>
<li>However, when <code>n == 2</code> we hit the <code>next</code> keyword and nothing gets evaluated.</li>
<li>Therefore this expression returns <code>[2,6]</code>.</li>
</ol>


<p>Reinforcing this line of reasoning, a very similar expression,</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="o">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="o">].</span><span class="n">each</span><span class="p">{</span> <span class="o">|</span><span class="n">n</span><span class="o">|</span> <span class="k">next</span> <span class="k">if</span> <span class="n">n</span><span class="o">.</span><span class="n">even?</span> <span class="p">;</span> <span class="nb">puts</span> <span class="mi">2</span><span class="o">*</span><span class="n">n</span> <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>gives the analog of this result:
it prints &#8220;2&#8221; and then &#8220;6&#8221; and then return.
The iteration that hits <code>next</code> just gets skipped.
Analogously, the version with <code>map</code> should return <code>[2,6]</code></p>

<p><strong>Wrong!</strong></p>

<p>In fact, the answer to the quiz is&#8230;</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="o">[</span><span class="mi">2</span><span class="p">,</span> <span class="kp">nil</span><span class="p">,</span> <span class="mi">6</span><span class="o">]</span>
</span></code></pre></td></tr></table></div></figure>


<p>The error in the reasoning above is contained in premise (3).
It turns out that <strong>when <code>next</code> is evaluated, it returns <code>nil</code></strong>.</p>

<p>Similarly,</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="o">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="o">].</span><span class="n">map</span><span class="p">{</span> <span class="o">|</span><span class="n">n</span><span class="o">|</span> <span class="mi">2</span><span class="o">*</span><span class="n">n</span> <span class="k">if</span> <span class="n">n</span><span class="o">.</span><span class="n">odd?</span> <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>returns the same array, <code>[2, nil, 6]</code>, because <code>... if false</code> returns nil no matter what (syntactically valid) expression <code>...</code> is.</p>

<p>So, if you&#8217;re using <code>map</code>, and you want to skip some elements, you can&#8217;t just use <code>next</code> or <code>if</code>.
You also need to deal with the <code>nil</code>s when you&#8217;re done, like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="o">].</span><span class="n">map</span><span class="p">{</span> <span class="o">|</span><span class="n">n</span><span class="o">|</span> <span class="k">next</span> <span class="k">if</span> <span class="n">n</span><span class="o">.</span><span class="n">even?</span> <span class="p">;</span> <span class="mi">2</span><span class="o">*</span><span class="n">n</span> <span class="p">}</span><span class="o">.</span><span class="n">compact</span>
</span></code></pre></td></tr></table></div></figure>


<p>Alternatively—although it&#8217;s probably more expensive—you could select the elements you want before proceeding with the operations you want to perform on them:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="o">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="o">].</span><span class="n">reject</span><span class="p">{</span> <span class="o">|</span><span class="n">n</span><span class="o">|</span> <span class="n">n</span><span class="o">.</span><span class="n">even?</span> <span class="p">}</span><span class="o">.</span><span class="n">map</span><span class="p">{</span> <span class="o">|</span><span class="n">n</span><span class="o">|</span> <span class="mi">2</span><span class="o">*</span><span class="n">n</span> <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Let me know in the comments if you can think of a generalizable implementation that&#8217;s more elegant than either of these.
In the meantime, may you never make the same mistake I made!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Quick Tip: More Legible Output with 'Kernel#y']]></title>
    <link href="http://code-worrier.com/blog/more-legible-output-with-y/"/>
    <updated>2012-08-30T14:24:00-04:00</updated>
    <id>http://code-worrier.com/blog/more-legible-output-with-y</id>
    <content type="html"><![CDATA[<p>Ever tried to get a sense of an ActiveRecord object by squinting though output like this?</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>&gt;&gt; User.find_by_login("Michael Hoffman").recipes.last
</span><span class='line'>=&gt; #&lt;Recipe id: 18891, title: "Pasta with Lemon-Parmesan Butte
</span><span class='line'>r", created_at: "2012-08-29 00:03:55", updated_at: "2012-08-29
</span><span class='line'>16:20:58", description: "I was walking by a little pizzeria in
</span><span class='line'>the East Vill...", recipe_category_id: 36, serving_size: "4 as
</span><span class='line'>a pasta course, 2 as a main", user_id: 784, editors_pick: fals
</span><span class='line'>e, editors_comments: "", label: "pasta_with_lemonparmesan_butt
</span><span class='line'>er", flag_inappropriate: false, wine_id: nil, recipe_style: "a
</span><span class='line'>b", varietal_id: nil, rating_average: 0, makes_serves: "Serves
</span><span class='line'>", flag_inappropriate_comments: nil, sommelier_comments: nil, 
</span><span class='line'>comments_count: 1, is_winner: false, interest: 1, is_finalist:
</span><span class='line'>nil, new_categories_added: nil, admin_categorization_note: nil
</span><span class='line'>&gt;</span></code></pre></td></tr></table></div></figure>


<p>Yuck.</p>

<!-- more -->


<p>Luckily, there&#8217;s a super simple way to get some nicer formatting.
The <code>Kernel</code> module has a private instance method <code>#y</code> which will print out an active record object (or anything else) as YAML.
Check it out:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>&gt;&gt; y User.find_by_login("Michael Hoffman").recipes.last
</span><span class='line'>--- !ruby/ActiveRecord:Recipe 
</span><span class='line'>attributes: 
</span><span class='line'>  sommelier_comments: 
</span><span class='line'>  recipe_style: ab
</span><span class='line'>  updated_at: 2012-08-29 16:20:58
</span><span class='line'>  admin_categorization_note: 
</span><span class='line'>  is_finalist: 
</span><span class='line'>  is_winner: "0"
</span><span class='line'>  editors_comments: ""
</span><span class='line'>  serving_size: 4 as a pasta course, 2 as a main
</span><span class='line'>  title: Pasta with Lemon-Parmesan Butter
</span><span class='line'>  interest: "1"
</span><span class='line'>  editors_pick: "0"
</span><span class='line'>  recipe_category_id: "36"
</span><span class='line'>  rating_average: "0"
</span><span class='line'>  id: "18891"
</span><span class='line'>  new_categories_added: 
</span><span class='line'>  flag_inappropriate_comments: 
</span><span class='line'>  wine_id: 
</span><span class='line'>  description: "I was walking by a little pizzeria in the East 
</span><span class='line'>    Village - one I've never been to and may never go to - and
</span><span class='line'>    I slowed my gait to glance at the menu. My eyes happened t
</span><span class='line'>    o land on a pasta dish. I don't remember exactly what it w
</span><span class='line'>    as called, but it involved lemon and parmesan, and not muc
</span><span class='line'>    h else. Lemon! So obvious. Why had I never thought of that
</span><span class='line'>    ? The next night I made this for dinner."
</span><span class='line'>  comments_count: "1"
</span><span class='line'>  makes_serves: Serves
</span><span class='line'>  varietal_id: 
</span><span class='line'>  user_id: "784"
</span><span class='line'>  label: pasta_with_lemonparmesan_butter
</span><span class='line'>  flag_inappropriate: "0"
</span><span class='line'>  created_at: 2012-08-29 00:03:55
</span><span class='line'>=&gt; nil</span></code></pre></td></tr></table></div></figure>


<p>Notice that, in addition to producing more legible formatting, <code>#y</code> does not truncate values, so we get to see the whole description of the recipe.
Another great use case for this method is visualizing nested hashes and arrays.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>&gt;&gt; a = {:animals =&gt; {:mammals =&gt; [:dog, :cat, :narwhal], :fish =&gt; [:tuna, :shark] }, :fruits =&gt; [:plum, :peach, :banana]}
</span><span class='line'>=&gt; {:fruits=&gt;[:plum, :peach, :banana], :animals=&gt;{:mammals=&gt;[:dog, :cat, :narwhal], :fish=&gt;[:tuna, :shark]}}
</span><span class='line'>&gt;&gt; y a
</span><span class='line'>--- 
</span><span class='line'>:fruits: 
</span><span class='line'>- :plum
</span><span class='line'>- :peach
</span><span class='line'>- :banana
</span><span class='line'>:animals: 
</span><span class='line'>  :mammals: 
</span><span class='line'>  - :dog
</span><span class='line'>  - :cat
</span><span class='line'>  - :narwhal
</span><span class='line'>  :fish: 
</span><span class='line'>  - :tuna
</span><span class='line'>  - :shark
</span><span class='line'>=&gt; nil</span></code></pre></td></tr></table></div></figure>


<p>Nice, huh?</p>

<p>One caveat:
<a href="http://stackoverflow.com/questions/11571801/rails-console-y-helper-returns-nameerror-rather-than-yaml-formatting-output/11572045#11572045">Apparently</a> this method relies on the <a href="http://stackoverflow.com/a/11572045">Syck YAML parser</a>.
For this reason, it won&#8217;t immediately work out of the box with Ruby 1.9.3, which uses the <a href="https://github.com/tenderlove/psych/">Psych parser</a> by default.
If you&#8217;re using 1.9.3 and you want to play around with <code>Kernel#y</code>, run <code>YAML::ENGINE.yamler = 'syck'</code> to change parsers.</p>

<p>And a question: I&#8217;d like to know how to get <code>#y</code> to print out ActiveRecord attributes in the same order as they are normally displayed.</p>

<p>(By the way, I highly recommend trying out <a href="http://food52.com/recipes/18891_pasta_with_lemonparmesan_butter">the recipe</a> mentioned above.)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Why RTFM is Some Bullshit]]></title>
    <link href="http://code-worrier.com/blog/why-rtfm-is-some-bullshit/"/>
    <updated>2012-08-29T10:48:00-04:00</updated>
    <id>http://code-worrier.com/blog/why-rtfm-is-some-bullshit</id>
    <content type="html"><![CDATA[<p>Learning to code is hard.</p>

<p>I&#8217;m not talking about the sense in which we&#8217;re all still learning.
I mean when you first start out, the first few months.
During this period, every tiny bit of progress you make comes at the expense of an excruciating, time-consuming trial.</p>

<p>Personally, I had the great fortune of being around patient, empathic experts who helped me through the worst of it.
(Thanks <a href="https://twitter.com/binarycleric">Jon</a>, <a href="https://twitter.com/jackiekircher">Jackie</a>, <a href="https://twitter.com/laurenvoswinkel">Lauren</a>, et al!)
But not everyone is so lucky, and sooner or later a new programmer is bound to encounter <a href="http://en.wikipedia.org/wiki/RTFM">RTFM</a> and its new-fangled cousins, GIYF and LMGTFY.</p>

<!-- more -->


<p>Ever ask an elementary question about coding or about getting your development environment set up, and encounter one of the following responses?</p>

<ol>
<li>Contempt without assistance.</li>
<li>A link to a page you don&#8217;t understand, with no explanation.</li>
<li>Overly brief assistance, with or without contempt.</li>
</ol>


<p>Whether or not they say it explicitly, the authors of these responses are expressing the RTFM sentiment.
And RTFM is bullshit.</p>

<p>I&#8217;m not the first person to say this, of course.
But as a programmer who is still very much in touch with what it&#8217;s like to know nothing, I hope I am in a position fortify the empathy of my more seasoned colleagues.</p>

<p>No one feels Meno&#8217;s Paradox as viscerally as the Googling noob.</p>

<blockquote><p>And how will you inquire into a thing when you are wholly ignorant of what it is?
Even if you happen to bump right into it, how will you know it is the thing you didn&#8217;t know?</p></blockquote>

<p>Answering technical questions via internet searches is a <em>skill</em> that takes <em>practice</em> to hone and which requires <em>background knowledge</em>.
Teaching yourself to code on the internet is a boostrapping process:
The more you learn, the better you get at learning it, and before you&#8217;ve learned very much, learning is really hard.</p>

<p>If you get stuck and you seek help on the internet, you need to know at least the following in order to have any hope of success:</p>

<ul>
<li>The nature of the problem your having.</li>
<li>The vocabulary that is commonly used to express this problem.</li>
<li>How to understand potential solutions to your problem.</li>
<li>How to implement potential solutions to see if they work.</li>
<li>What would constitute a solution&#8217;s working.</li>
</ul>


<p>People who ask stupid technical questions might be stupid people.
Or, more likely, they might just be missing one or more of the pieces of knowledge they need to ask a smart quetsion and understand the answer.
It&#8217;s not their fault they don&#8217;t know these things.
They are beginners.
Learning to figure stuff our using documentation and Google is a skill they&#8217;re developing along with all the others.</p>

<p>So, if someone asks a stupid question, consider taking the time answer it, fully and cheerfully.
Or don&#8217;t answer at all.
Just remember: RTFM is some lazy, rude bullshit.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[All your undefined vars are evaluate to nil.]]></title>
    <link href="http://code-worrier.com/blog/all-your-vars/"/>
    <updated>2012-08-27T18:14:00-04:00</updated>
    <id>http://code-worrier.com/blog/all-your-vars</id>
    <content type="html"><![CDATA[<p><em>(NB: I learned much of what I discuss here from this <a href="http://stackoverflow.com/a/4023224/882025">post</a>.)</em></p>

<p>What does a brand new, never-before-mentioned variable evaluate to in Ruby?
Perhaps it seems that the correct answer is: it depends what kind of variable.
Undefined instance variables, for example, evaluate to <code>nil</code>, whereas undefined local variables can&#8217;t be evaluated at all.</p>

<!-- more -->


<p>A little experimentation in irb seems to confirm this hypothesis.
Uninitialize local variables raise a <code>NameError</code>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>&gt;&gt; local_variables
</span><span class='line'>=&gt; []
</span><span class='line'>&gt;&gt; local_var
</span><span class='line'>NameError: undefined local variable or method `local_var' for main:Object</span></code></pre></td></tr></table></div></figure>


<p>whereas instance variables evaluate to <code>nil</code>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>&gt;&gt; instance_variables
</span><span class='line'>=&gt; []
</span><span class='line'>&gt;&gt; @instance_var
</span><span class='line'>=&gt; nil</span></code></pre></td></tr></table></div></figure>


<p>(Global variables behave the same way in this respect as instance varables.)</p>

<p>So, again, it seems as if the correct answer to our question is, &#8220;It depends.&#8221;
But that&#8217;s wrong.
In fact, the question has a single, simple correct answer:
<em>All types of uninitialized variables evaluate to nil.</em></p>

<p>Here&#8217;s proof:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>&gt;&gt; local_var = "something or other" if false
</span><span class='line'>=&gt; nil
</span><span class='line'>&gt;&gt; local_var
</span><span class='line'>=&gt; nil</span></code></pre></td></tr></table></div></figure>


<p>The initialization of <code>local_var</code> is never evaluated, because the condition <code>false</code> is, of course, not met.
Yet, it seems that the mere fact that the parser has parsed <code>local_var</code> suffices to avoid the <code>NameError</code> when evaluating the variable.
Why?</p>

<p>The answer is that the <code>NameError</code> was merely an error of ambiguity:
In our first example, the parser could not decide whether <code>local_var</code> was a local variable, or the name of a method—shorthand for <code>self.local_var</code>.
The error message we got didn&#8217;t do a great job of explaining this, but it did hint at it with the phrase &#8220;variable or method&#8221;.
Once the parser has encountered <code>local_var</code> in an unambiguously variable-like context—namely, <code>local_var = "something or other"</code>— it has no problem evaluating the name as the name of a variable.
And, as I&#8217;ve claimed, all uninitialized variable evaluate to <code>nil</code>.</p>

<p>So, what appeared to be a difference between local varables and other types of variables is actually just a coincidence of Ruby syntax.
Ruby gives us the flexibility to leave the receiver to which we pass a method implicit:
if we don&#8217;t explicitly identify a reciever, the message is passed to the current object.
However, this flexibilty comes at the price of ambiguity;
absent additional context, methods invoked on implcitly defined receivers look to the world (and, more importantly, the parser!) just like local variables.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Quick Tip: Recursive Arrays in Ruby]]></title>
    <link href="http://code-worrier.com/blog/recursive-arrays/"/>
    <updated>2012-08-16T22:30:00-04:00</updated>
    <id>http://code-worrier.com/blog/recursive-arrays</id>
    <content type="html"><![CDATA[<p>They&#8217;re real!</p>

<p>In Ruby, an array can contain itself:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="o">&gt;&gt;</span> <span class="n">a</span> <span class="o">=</span> <span class="o">[]</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="o">[]</span>
</span><span class='line'><span class="o">&gt;&gt;</span> <span class="n">a</span> <span class="o">&lt;&lt;</span> <span class="n">a</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="o">[[.</span><span class="n">.</span><span class="o">.]]</span>
</span><span class='line'><span class="o">&gt;&gt;</span> <span class="n">a</span><span class="o">.</span><span class="n">first</span><span class="o">.</span><span class="n">equal?</span> <span class="n">a</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="kp">true</span>
</span></code></pre></td></tr></table></div></figure>


<!-- more -->


<p>But <a href="http://stackoverflow.com/questions/10606734/what-are-recursive-arrays-good-for">why would you want to go and do that?</a>?</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Quick Tip: Helper methods in the Rails console?]]></title>
    <link href="http://code-worrier.com/blog/helper-methods-in-console/"/>
    <updated>2012-08-14T11:53:00-04:00</updated>
    <id>http://code-worrier.com/blog/helper-methods-in-console</id>
    <content type="html"><![CDATA[<p>So you want to mess around with a helper method in the console?
It&#8217;s super simple, as I just learned <a href="http://stackoverflow.com/questions/151030/how-do-i-call-controller-view-methods-from-the-console-in-rails">here</a> from <a href="http://caiochassot.com/">kch</a>.
Basically, Rails gets a bit <a href="http://nextlol.com/images/37181-yo-dawg-hotdawg.jpg">yo dawg</a> and provides a helper for your helpers—called &#8220;helper&#8221;.</p>

<p>Here&#8217;s an example. Suppose you have a helper module like the following:</p>

<!-- more -->




<figure class='code'><figcaption><span>cars_helper.rb  </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">module</span> <span class="nn">CarsHelper</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">put_a_car_in</span><span class="p">(</span><span class="n">location</span><span class="p">)</span>
</span><span class='line'>    <span class="k">if</span> <span class="n">location</span> <span class="o">==</span> <span class="s2">&quot;your car&quot;</span>
</span><span class='line'>      <span class="nb">puts</span> <span class="s2">&quot;So you can drive while you drive!&quot;</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>Fire up a Rails console, and to create the helper-helper, all you have to do in include the module:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>&gt;&gt; include CarsHelper
</span><span class='line'>=&gt; Object
</span><span class='line'>
</span><span class='line'>&gt;&gt; helper.put_a_car_in("your car")
</span><span class='line'>So you can drive while you drive!</span></code></pre></td></tr></table></div></figure>


<p>I hope this has been helpful. (Sorry, can&#8217;t help myself.)</p>

<p>Ok, I&#8217;m done.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Passing Symbols, a Kata Lesson]]></title>
    <link href="http://code-worrier.com/blog/passing-symbols/"/>
    <updated>2012-08-12T22:02:00-04:00</updated>
    <id>http://code-worrier.com/blog/passing-symbols</id>
    <content type="html"><![CDATA[<p>In <a href="http://code-worrier.com/blog/kata/">my post</a> about the <a href="https://github.com/wbailey/kata">kata gem</a>, I promised to share something I learned from the <a href="https://github.com/wbailey/code_katas/blob/master/calculator.rb">calculator kata</a>.
Here goes.</p>

<p>The calculator kata asks you to construct a <code>Calculator</code> class the instances of which are initialized with comma-delimited strings of integers.
Next you are asked, one by one, to create a series of instance methods—<code>#sum</code>, <code>#prod</code>, <code>#div</code>, <code>#diff</code>—for the class that perform arithmetic operations on the stored integers.</p>

<p>Starting with <code>#sum</code> only, I wrote the class, obviously enough, like this:</p>

<!-- more -->




<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'>  <span class="k">class</span> <span class="nc">Calculator</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">def</span> <span class="nf">initialize</span> <span class="n">expr</span>
</span><span class='line'>      <span class="vi">@expr</span> <span class="o">=</span> <span class="n">expr</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">def</span> <span class="nf">sum</span>
</span><span class='line'>      <span class="vi">@expr</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sr">/\,/</span><span class="p">)</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:to_i</span><span class="p">)</span><span class="o">.</span><span class="n">inject</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:+</span><span class="p">)</span> <span class="o">||</span> <span class="mi">0</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>After adding in another instance method, it made sense to move to conversion from string to array into the initialization method:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'>  <span class="k">class</span> <span class="nc">Calculator</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">def</span> <span class="nf">initialize</span> <span class="n">expr</span>
</span><span class='line'>      <span class="vi">@expr_array</span> <span class="o">=</span> <span class="n">expr</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sr">/\,/</span><span class="p">)</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:to_i</span><span class="p">)</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">def</span> <span class="nf">sum</span>
</span><span class='line'>      <span class="vi">@expr_array</span><span class="o">.</span><span class="n">inject</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:+</span><span class="p">)</span> <span class="o">||</span> <span class="mi">0</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">def</span> <span class="nf">prod</span>
</span><span class='line'>      <span class="vi">@expr_array</span><span class="o">.</span><span class="n">inject</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:*</span><span class="p">)</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>I went on to add analogous subtraction and division methods, and then I started to get an itch:
Could I avoid writing &#8220;inject&#8221; four times?
More importantly, could I find a way that to write this class that reflected the underlying similarity in function shared by these four methods?</p>

<p>On a kata-fuelled lark, I decided to write the code I <em>wished</em> would work, even though I had no reason to think it would.
I passed the arithmetic operation symbols into the methods as arguments, and then into the inject blocks:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'>  <span class="k">class</span> <span class="nc">Calculator</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">def</span> <span class="nf">initialize</span> <span class="n">expr</span>
</span><span class='line'>      <span class="vi">@expr_array</span> <span class="o">=</span> <span class="n">expr</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sr">/\,/</span><span class="p">)</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:to_i</span><span class="p">)</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">def</span> <span class="nf">sum</span>
</span><span class='line'>      <span class="n">inject_op</span><span class="p">(</span><span class="ss">:+</span><span class="p">)</span> <span class="o">||</span> <span class="mi">0</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">def</span> <span class="nf">prod</span>
</span><span class='line'>      <span class="n">inject_op</span><span class="p">(</span><span class="ss">:*</span><span class="p">)</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1"># etc.</span>
</span><span class='line'>
</span><span class='line'>    <span class="kp">private</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">def</span> <span class="nf">inject_op</span> <span class="n">op</span>
</span><span class='line'>      <span class="vi">@expr_array</span><span class="o">.</span><span class="n">inject</span><span class="p">(</span><span class="o">&amp;</span> <span class="n">op</span><span class="p">)</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>To my surprise <em>this actually does work</em>!!</p>

<p>My initial reaction was: Go Ruby!
And then: Thank you, kata.</p>

<p>But, finally, in the spirit of the aphorism that &#8220;magic is code you don&#8217;t understand yet,&#8221; I thought: How do these <code>&amp;</code> blocks work, anyway?
More on that in a later post.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Code Kata and the Kata Gem]]></title>
    <link href="http://code-worrier.com/blog/kata/"/>
    <updated>2012-08-12T18:01:00-04:00</updated>
    <id>http://code-worrier.com/blog/kata</id>
    <content type="html"><![CDATA[<p>A <a href="http://codekata.pragprog.com/">code kata</a> is a small programming challenge on which a developer can practice her craft.
Kata have solutions in the sense that they set our requirements that a program can meet or fail to meet.
However, it is the process of thinking through the kata—and perhaps implementing it multiple times in different ways—that is intended to provoke learning.</p>

<p>Of course, you can&#8217;t learn anything form a kata unless you <em>do</em> the kata.
Enter the <a href="https://github.com/wbailey/kata">kata gem</a> by <a href="http://exposinggotchas.blogspot.com/">Wes Bailey</a>.</p>

<!-- more -->


<p>I learned about the gem from a lightning talk Bailey delivered at the inaugural <a href="http://steelcityrubyconf.org/">Steel City Ruby Conference</a> in Pittsburgh.
(Incidentally, SCRC was my first programming conference, and it was fantastic.
My experience there inspired this blog.)</p>

<p>The kata gem reduces the friction between you and actually sitting down to do kata.
It accomplishes this by presenting the kata requirements in bite-sized pieces on the command line.
The process of working through a kata via the gem resembles the work flow of test-driven development.
(To be clear, working with the gem in no way precludes <em>actual</em> TDD.)
This is no accident;
Bailey&#8217;s <a href="https://github.com/wbailey/kata/wiki/Authoring-a-Kata">DSL</a> for authoring kata is modeled after the <a href="http://rspec.info/">Rspec</a> testing framework.</p>

<p>Here are the first two steps of the calculator kata, which asks the coder to create a <code>Calculator</code> class, instances of which are initialized with strings of numbers:</p>

<pre><code>Create a calculator that is initialized with a string expression
- detail: The expression is of the form digits separated by commas: "1,2"
- detail: The expression is accessed by a method named expr
- detail: The expression can be reset for evaluation at any time without re-initializing
- example: Calculator.new "1,2"

Add Method
  Create an add method that sums the string expression
  - detail: The method will return the sum of the digits
  - detail: The expression can contain 0, 1 or 2 numbers
  - detail: Then empty string will return 0
  - example: "" computes to 0
  - example: "1" computes to 1
  - example: "1,2" computes to 3
</code></pre>

<p>&#8230;and so on. Yes, things start off simply, but simple problems allow for focus on technique and experimentation.
In my <a href="http://code-worrier.com/blog/passing-symbols">next post</a>, I&#8217;ll relate something I learned by experimenting with the calculator kata.</p>
]]></content>
  </entry>
  
</feed>
