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

<channel>
	<title>Garbled &#187; code</title>
	<atom:link href="http://garbled.benhamill.com/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://garbled.benhamill.com</link>
	<description>garbled = Blog.new(:author =&#62; &#039;Ben Hamill&#039;)</description>
	<lastBuildDate>Fri, 03 Feb 2012 20:50:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>A Smarter has_many :through?</title>
		<link>http://garbled.benhamill.com/2011/08/a-smarter-has_many-through/</link>
		<comments>http://garbled.benhamill.com/2011/08/a-smarter-has_many-through/#comments</comments>
		<pubDate>Thu, 25 Aug 2011 19:00:05 +0000</pubDate>
		<dc:creator>benhamill</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://garbled.benhamill.com/?p=41</guid>
		<description><![CDATA[At work, I&#8217;ve been expending a lot of effort on this complicated search functionality where you can enter a search phrase that will full-text search over one model&#8217;s fields (we&#8217;re using texticle [github], which is awesome) and limit the results by which other models are involved relationally. Sort of like searching Amazon for &#8220;green converse&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p>At work, I&#8217;ve been expending a lot of effort on this complicated search functionality where you can enter a search phrase that will full-text search over one model&#8217;s fields (we&#8217;re using <a href="http://tenderlove.git.hub.com/texticle/">texticle</a> [<a href="https://github.com/tenderlove/texticle">github</a>], which is awesome) and limit the results by which other models are involved relationally. Sort of like searching Amazon for &#8220;green converse&#8221; and choosing the &#8220;shoes&#8221; category.</p>
<p>The object graph behind this is pretty complicated and it&#8217;s been a real education in SQL trying to make sure the query that gets generated is both reasonably speedy and right. Several times, I&#8217;ve gotten it &#8220;working&#8221; only to realize I was joining in some table more than once and so either returning some record twice or excluding it when I shouldn&#8217;t've or joining all rows against all rows and, thus, making everything pass all constraints. My SQL skill has leveled up several times throughout, though, which has been really awesome. This is mostly because I was hand-writing a lot of the join SQL with table aliases and whatnot.</p>
<h4>Example</h4>
<p>The other day, I realized that Rails 3 (or, anyway, the 3.1 release candidates, which is what this app is using) will let you do something that earlier versions would not: do a <code>has_many :through</code> relation on another <code>has_many :through</code>. Say you&#8217;ve got Departments composed of Employees. Employees work in groups to create Widgets and which, in turn, get Tags. You can do this number:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Widget <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">AR::Base</span>
  has_many <span style="color:#ff3333; font-weight:bold;">:tags</span>
  has_many <span style="color:#ff3333; font-weight:bold;">:employees</span>
&nbsp;
  has_many <span style="color:#ff3333; font-weight:bold;">:departments</span>, <span style="color:#ff3333; font-weight:bold;">:through</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:employees</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Tag <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">AR::Base</span>
  belongs_to <span style="color:#ff3333; font-weight:bold;">:widget</span>
&nbsp;
  has_many <span style="color:#ff3333; font-weight:bold;">:employees</span>, <span style="color:#ff3333; font-weight:bold;">:through</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:widget</span>
  has_many <span style="color:#ff3333; font-weight:bold;">:departments</span>, <span style="color:#ff3333; font-weight:bold;">:through</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:employees</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Employee <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">AR::Base</span>
  belongs_to <span style="color:#ff3333; font-weight:bold;">:widget</span>
  belongs_to <span style="color:#ff3333; font-weight:bold;">:department</span>
&nbsp;
  has_many <span style="color:#ff3333; font-weight:bold;">:tags</span>, <span style="color:#ff3333; font-weight:bold;">:through</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:widget</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Department <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">AR::Base</span>
  has_many <span style="color:#ff3333; font-weight:bold;">:employees</span>
&nbsp;
  has_many <span style="color:#ff3333; font-weight:bold;">:widgets</span>, <span style="color:#ff3333; font-weight:bold;">:through</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:employees</span>
  has_many <span style="color:#ff3333; font-weight:bold;">:tags</span>, <span style="color:#ff3333; font-weight:bold;">:through</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:widgets</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>Which enables stuff like:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;">Department.<span style="color:#9900CC;">joins</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:tags</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">where</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:tag</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#ff3333; font-weight:bold;">:id</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:tag_id</span><span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></td></tr></table></div>

<h4>The SQL</h4>
<p>So, though, since I was hand-writing my <code>JOIN</code> statements before, I&#8217;m clearly concerned with what, exactly, it&#8217;s going to execute against the database. So I pulled out good ol&#8217; <code>ActiveRecord::Base#to_sql</code> to see. Here&#8217;s what I got (edited without all the quoting and with newlines):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> departments<span style="color: #66cc66;">.*</span> <span style="color: #993333; font-weight: bold;">FROM</span> departments
<span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> employees <span style="color: #993333; font-weight: bold;">ON</span> employees<span style="color: #66cc66;">.</span>department_id <span style="color: #66cc66;">=</span> departments<span style="color: #66cc66;">.</span>id
<span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> widgets <span style="color: #993333; font-weight: bold;">ON</span> widgets<span style="color: #66cc66;">.</span>id <span style="color: #66cc66;">=</span> employees<span style="color: #66cc66;">.</span>widget_id
<span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> tags <span style="color: #993333; font-weight: bold;">ON</span> tags<span style="color: #66cc66;">.</span>widget_id <span style="color: #66cc66;">=</span> widgets<span style="color: #66cc66;">.</span>id
<span style="color: #993333; font-weight: bold;">WHERE</span> tags<span style="color: #66cc66;">.</span>id <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">3</span></pre></td></tr></table></div>

<p>Hopefully, that query is pretty straight forward and you can see how ActiveRecord has decided how to make all those joins. However, something struck me: I&#8217;m joining through with <code>widgets</code> table, but both <code>employees</code> and <code>tags</code> already have <code>widget_id</code> on them. I&#8217;d rather have seen something like:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> departments<span style="color: #66cc66;">.*</span> <span style="color: #993333; font-weight: bold;">FROM</span> departments
<span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> employees <span style="color: #993333; font-weight: bold;">ON</span> employees<span style="color: #66cc66;">.</span>department_id <span style="color: #66cc66;">=</span> departments<span style="color: #66cc66;">.</span>id
<span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> tags <span style="color: #993333; font-weight: bold;">ON</span> tags<span style="color: #66cc66;">.</span>widget_id <span style="color: #66cc66;">=</span> employees<span style="color: #66cc66;">.</span>widget_id
<span style="color: #993333; font-weight: bold;">WHERE</span> tags<span style="color: #66cc66;">.</span>id <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">3</span></pre></td></tr></table></div>

<p>The result set should be the same and it&#8217;s slightly faster. In this example, joining through the extra table wouldn&#8217;t be a big hit, probably, but if we&#8217;ve got more objects all related to Widgets and many are, like Departments, related through some other object, we might be (and in my case often are) joining many more tables, so if we can eliminate middle-man joins, it can have an appreciable effect on the query&#8217;s speed.</p>
<h4>How We Do It</h4>
<p>So it turns out you <em>can</em> make ActiveRecord generate the above SQL. You don&#8217;t want <code>has_many :through</code> for the second association. If you do like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Department <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">AR::Base</span>
  has_many <span style="color:#ff3333; font-weight:bold;">:employees</span>
&nbsp;
  has_many <span style="color:#ff3333; font-weight:bold;">:widgets</span>, <span style="color:#ff3333; font-weight:bold;">:through</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:employees</span>
  <span style="color:#008000; font-style:italic;"># has_many :tags, :through =&gt; :widgets</span>
  has_many <span style="color:#ff3333; font-weight:bold;">:tags</span>, <span style="color:#ff3333; font-weight:bold;">:foreign_key</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:widget_id</span>, <span style="color:#ff3333; font-weight:bold;">:primary_key</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:widget_id</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>You can use the same ActiveRecord query syntax from above to generate the second SQL example. It&#8217;s a lot of typing, though, so I wondered: Wouldn&#8217;t it be awesome if ActiveRecord knew you when you had this matching-middle-man-foreign-key situation in a query and generated the leaner SQL?</p>
<p>I&#8217;m not sure if there are pitfalls to this I&#8217;m not seeing (especially related to uses outside what I&#8217;m doing with it right now), but I&#8217;ve started digging around in the Rails source to see where it&#8217;s thinking about these kinds of things (led me to <code>lib/active_record/associations/join_dependency/join_association.rb:72</code> so far). I&#8217;d love some thoughts and feedback on these ideas or guidance in my code-diving efforts. I expect I may end up in the Arel source at some point&#8230; we&#8217;ll see where it takes me.</p>
]]></content:encoded>
			<wfw:commentRss>http://garbled.benhamill.com/2011/08/a-smarter-has_many-through/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Falsiness and Null Objects</title>
		<link>http://garbled.benhamill.com/2011/06/falsiness-and-null-objects/</link>
		<comments>http://garbled.benhamill.com/2011/06/falsiness-and-null-objects/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 13:00:18 +0000</pubDate>
		<dc:creator>benhamill</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[naval gazing]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://garbled.benhamill.com/?p=39</guid>
		<description><![CDATA[Recently, I went to RailsConf. I saw a bunch of talks and met some cool people. This is not a RailsConf post-mortem post (if you&#8217;re interested, though, I&#8217;ve collected some notes from myself and some others here). This post is about what, in retrospect, was probably the best talk I went to (and I went [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I went to <a href="http://railsconf.com">RailsConf</a>. I saw a bunch of talks and met some cool people. This is not a RailsConf post-mortem post (if you&#8217;re interested, though, I&#8217;ve collected some notes from myself and some others <a href="https://github.com/benhamill/railsconf_2011">here</a>). This post is about what, in retrospect, was probably the best talk I went to (and I went to several really awesome talks). I&#8217;ve been mulling over it since I got back, basically, and that seems like a good result from a talk. That talk was <a href="http://avdi.org">Avdi Grimm</a>&#8216;s Confident Code (<a href="http://avdi.org/talks/confident-code-railsconf-2011/">slides</a>, <a href="https://github.com/benhamill/railsconf_2011/blob/master/confident_code.txt">my notes</a>).</p>
<p>One thing in particular sort of caught at the edge of my thought patterns: <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">The Null Object Pattern</a>. I don&#8217;t have a CS degree and so I&#8217;m missing a lot of the formal training about design patterns that many programmers have (and, probably, forget), so I&#8217;d never heard of it. When Avdi started talking about how ActiveRecord&#8217;s <code>try</code> method is a code smell, I was like, &#8220;Yes!&#8221; I would not say that I hate it, but I have seen several times some line of code that looks like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#0066ff; font-weight:bold;">@user</span>.<span style="color:#9900CC;">try</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:posts</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">try</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:recent</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">try</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:first</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></td></tr></table></div>

<p>I mean&#8230; bleh. But I didn&#8217;t know a way that looked any better to me, really. Anyway, you can look at <a href="https://github.com/benhamill/railsconf_2011/blob/master/confident_code.txt">the notes</a> and <a href="http://avdi.org/talks/confident-code-railsconf-2011/">slides</a> to learn about what Avdi says about the Null Object Pattern. I thought it was awesome and so when I went home, I decided to take it for a test drive.</p>
<h4>The Test Course</h4>
<p>So in a project at work, we have Users and they may or may not have one Subscription. Hopefully, you can picture this complex object graph. Subscriptions may or may not be &#8220;current&#8221; based on various business rules mostly to do with whether you paid us or not. So, naturally, we have a <code>Subscrption#current?</code> method. But we&#8217;re using the User as a sort of presenter for Subscriptions. So you don&#8217;t want to call <code>@user.subscription.current?</code>. That&#8217;s a code smell. So on User we had this method:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> current?
  subscription.<span style="color:#9900CC;">try</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:current</span>?<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>There&#8217;s that rascal <code>try</code>. &#8220;This,&#8221; I thought, &#8220;is a perfect spot for that <code>Maybe</code> method from Avdi&#8217;s talk.&#8221; So I rewrote it thusly:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> current?
  Maybe<span style="color:#006600; font-weight:bold;">&#40;</span>subscription<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">current</span>?
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>W00t, right? Wrong. The accompanying <code>NullObject</code> class looks like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> NullObject
  <span style="color:#9966CC; font-weight:bold;">def</span> method_missing<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">*</span>args, <span style="color:#006600; font-weight:bold;">&amp;</span>block<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0000FF; font-weight:bold;">self</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">nil</span>?
    <span style="color:#0000FF; font-weight:bold;">true</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>That method missing treatment, so handy in avoiding the chain of <code>try</code>s in my first example, is the gotcha. It means that if I have a User without a Subscription for whatever reason, calling <code>User#current?</code> returns an instance of <code>NullObject</code>, which will pass, say, the boolean clause of an <code>if</code> statement.</p>
<p>So, not sure as to whether I&#8217;d misunderstood something, was making some dumb mistake or what, I emailed Avdi. He said, basically, &#8220;Awesome question. I will answer it in a blog post.&#8221; And, lo, <a href="http://avdi.org/devblog/2011/05/30/null-objects-and-falsiness/">he did</a>. Go read <a href="http://avdi.org/devblog/2011/05/30/null-objects-and-falsiness/">that post</a> to see <a href="http://avdi.org/devblog/2011/05/30/null-objects-and-falsiness/">what he said</a>. The comments also have some good ideas.</p>
<h4>Noodles</h4>
<p>If you read my comment, I said I was going to noodle on stuff and post again. I had more thoughts than it seemed like would fit in a blog comment. Hence this post. So my initial thought was disappointment. It turned out the Null Object Pattern wasn&#8217;t as powerful (in Ruby) as I&#8217;d hoped, since if you might have something (calling <code>Maybe</code>) the chances that you&#8217;ll have some conditional asking a boolean business-rule question about it is not low.</p>
<p>So I thought about how to get around that. You could, for instance, make a more complex <code>method_missing</code> definition that grepped the message name for <code>/\?$/</code> and returned false. That&#8217;s fail, though. It falls down the moment you have something like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">if</span> Maybe<span style="color:#006600; font-weight:bold;">&#40;</span>@posts<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">empty</span>?
  <span style="color:#008000; font-style:italic;"># Intuitively, you'd expect NullObject#empty? to have put you in here.</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>But then I realized that Avdi was making a higher-level point: since it is not possible to make your own objects look falsey in Ruby, you have to have another solution. Trying to define various question-mark methods on <code>NullObject</code> is trying to untie the knot, but I should be looking for a way to cut it. So it got me thinking: Why the hell to I have Users without Subscriptions, anyway? Shouldn&#8217;t <code>User#current?</code> express that business logic clearly, rather than just express the logic that enforces it? Yes. Yes, it should.</p>
<p>We have some Users who are also admins, who have special rights. It&#8217;s also conceivable that we could give away a free account for whatever reason. So, really, we want something like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> current?
  <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">free_account</span>? <span style="color:#006600; font-weight:bold;">||</span> subscription.<span style="color:#9900CC;">current</span>?
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>But, this thought it incomplete. It expresses the business logic cleanly: The User is current if they&#8217;re flagged as free or if their Subscription is up to date. However, if the weird case of a User who is neither free nor has an associated Subscription crops up, we still have to hunt down the &#8220;Undefined method &#8216;current?&#8217; for nil&#8221; error. It sort of has be reaching for <code>Maybe</code> again.</p>
<p>Or maybe (heh, you see what I did there) I want to steal another trick from Avdi&#8217;s presentation and have <code>User#subscription</code> return <code>:no_subscription_defined_for_user</code> so that the error message makes some more sense. I don&#8217;t like redefining <code>ActiveRecord</code>&#8216;s default accessor methods, though, to transparently return the symbol if the real object is missing.</p>
<p>If you&#8217;ve got any thoughts, I&#8217;d love to hear them.</p>
]]></content:encoded>
			<wfw:commentRss>http://garbled.benhamill.com/2011/06/falsiness-and-null-objects/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Release: twitter_atm 1.0</title>
		<link>http://garbled.benhamill.com/2011/01/release-twitter_atm-1-0/</link>
		<comments>http://garbled.benhamill.com/2011/01/release-twitter_atm-1-0/#comments</comments>
		<pubDate>Fri, 14 Jan 2011 15:00:19 +0000</pubDate>
		<dc:creator>benhamill</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[otherinbox]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://garbled.benhamill.com/?p=38</guid>
		<description><![CDATA[Holy crap. Did I really start this blog in December 2008? That would make it more than 2 years old. Wow. Well, good on me, I guess. That feels sort of absurd. Anyway&#8230; An Itch&#8230; The other day at work, I had to get the OAuth credentials for a twitter account that our application would [...]]]></description>
			<content:encoded><![CDATA[<p>Holy crap. Did I really start this blog in December 2008? That would make it more than 2 years old. Wow. Well, good on me, I guess. That feels sort of absurd. Anyway&#8230;</p>
<h4>An Itch&#8230;</h4>
<p>The other day at <a title="OtherInbox" href="http://www.otherinbox.com" target="_blank">work</a>, I had to get the OAuth credentials for a twitter account that our application would use to send programmatic tweets to. For those of you not familiar with OAuth, a brief description: The usual way you OAuth with Twitter is that you have a web page where a user clicks something indicating they&#8217;d like to OAuth you to their account. You then send your consumer key and secret off to Twitter to get a request token and, using that, you send the user off to a url over on twitter.com.</p>
<p>Once there, they sign in (or are already signed in) and click &#8220;Allow&#8221;. Twitter then hits your callback url with some more tokens, which you use to make a final reply and then they respond with the access token and secret you&#8217;ll need to do whatever it is you&#8217;re doing with the user&#8217;s account. If the user changes username or password, you&#8217;re still authorized and if they want to revoke your access, they can without changing their username or password<em>. </em>Great! (If you&#8217;re thinking, &#8220;What?!? Not great! That made no sense!&#8221; then maybe the image in <a title="OAuth Documentation on dev.twitter.com" href="http://dev.twitter.com/pages/auth#intro" target="_blank">this article</a> will help).</p>
<p>However, when your program is a desktop client or when you&#8217;ve only got one account you&#8217;ll ever be tweeting from (or maybe a small handful), it&#8217;s not really practical to build a web interface and a callback url to hit so that you can do the whole dance and get the tokens. So Twitter has an alternate path that replaces the redirects in the middle of the dance. Instead of redirecting users over to twitter.com, you show them the URL and they go there manually. When they click &#8220;Allow&#8221;, they&#8217;re given a PIN, which they then give back to you and you can then finish off the dance as if the PIN were the callback.</p>
<h4>&#8230;Scratched</h4>
<p>So at work, I hacked around in the console for a bit and eventually figured out how to work the PIN-based method, ran it for the account I wanted and then got the access token and secret for our account. But, I thought, I shouldn&#8217;t have to hunt all around to figure out how it works (the documentation is almost all focused on the callback path). Heck, if I know my consumer key and secret and I own the account, I shouldn&#8217;t need to know how it works at all. So, having figured out how it works already, I decided I&#8217;d write a little command to do it for me and publish it as a gem. Thus was born <a title="Github repo" href="https://github.com/benhamill/twitter_atm" target="_blank">twitter_atm</a>.</p>
<h4>The Tool</h4>
<p>As the README states, it&#8217;s pretty simple. You invoke <code>twitter_atm get_creds</code> with your consumer key and secret as arguments, then it interactively gives you directions on how to finish out the process and spits out the access token and secret at the end. I do want to note, about the name, it&#8217;s not about cash. It&#8217;s about inputting a PIN and getting something in return. It&#8217;s not very exciting to use, so I won&#8217;t talk about it much. I&#8217;d rather move on to&#8230;</p>
<h4>An Old God of Asgard</h4>
<p>This was the first time I&#8217;d written a program with a command line interface, so I asked around a little about gems that were good at that and Jonathan Otto (of <a title="Dealzon main site." href="http://dealzon.com" target="_blank">Dealzon</a>) pointed me at <a title="thor gem on Github" href="https://github.com/wycats/thor" target="_blank">thor</a>. In short, thor seems awesome. It&#8217;s got a nice DSL for describing the various subcommands of your application and it looks deep enough to handle something more complex than my purposes with twitter_atm.</p>
<p>As a brief example, consider <code>git pull --rebase origin master</code>. If you were writing something that would support this syntax in thor, it would look something like this (I made up the git commands inside off the top of my head, so it&#8217;s a bit naive):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Git <span style="color:#006600; font-weight:bold;">&lt;</span> Thor
  desc <span style="color:#996600;">&quot;git pull&quot;</span>, <span style="color:#996600;">&quot;Fetches and merges stuff into the current branch.&quot;</span>
  method_options <span style="color:#ff3333; font-weight:bold;">:rebase</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:boolean</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> pull<span style="color:#006600; font-weight:bold;">&#40;</span>remote, branch<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#996600;">`git fetch #{remote}`</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">if</span> options<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:rebase</span><span style="color:#006600; font-weight:bold;">&#93;</span>
      <span style="color:#996600;">`git rebase #{remote}/#{branch}`</span>
    <span style="color:#9966CC; font-weight:bold;">else</span>
      <span style="color:#996600;">`git merge #{remote}/#{branch}`</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>You can also declare different types of options, default values, etc. Have a look at the fairly extensive readme and look at <a title="/bin/twitter_atm" href="https://github.com/benhamill/twitter_atm/blob/develop/bin/twitter_atm" target="_blank">how I used it in twitter_atm</a> if that helps. I quite recommend the gem and already have another project I&#8217;d like to use it on.</p>
<h4>bundle gem twitter_atm</h4>
<p>There&#8217;s this little project&#8211;I don&#8217;t know if you&#8217;ve heard of it&#8211;called <a title="Bundler website." href="http://gembundler.com/" target="_blank">bundler</a>. It was started by a <a title="Carl Lerche on Github" href="https://github.com/carllerche" target="_blank">couple of up-and-coming young programmers</a> <a title="Yehuda Katz on Github" href="https://github.com/wycats" target="_blank">who really might go somewhere some day</a>. Bundler is great for managing gems in a big project and it does this really impressive dependency resolution thing. But there&#8217;s a lesser known command that I&#8217;ve fallen in love with: <code>bundle gem &lt;gem_name&gt;</code>. It just makes a skeleton for a gem project for you. Unlike <a title="Jeweler on Github" href="https://github.com/technicalpickles/jeweler" target="_blank">Jeweler</a>, it only gives you the bare minimum and really just gets out of your way. You manage your own version number and <a title="Yehuda on using .gemspec files &quot;correctly&quot;." href="http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/" target="_blank">write your own gemspec</a> (gasp!).</p>
<p>It has three handy rake tasks with obvious functions: <code>rake build</code>, <code>rake install</code> and <code>rake release</code>. Each of those for the most part just issue various <code>gem</code> commands. I basically like it because it builds you a little foundation and then doesn&#8217;t really manage anything else for you. One thing that&#8217;s important to note: The current version of bundler doesn&#8217;t add <code>Gemfile.lock</code> to the <code>.gitignore</code> that it generates (but future versions will), and it is important that you do so. Yehuda has a <a title="Yehuda on Gemfile and .gemspec" href="http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/" target="_blank">blog post</a> explaining why.</p>
<p>So, based on this experience, here&#8217;s what <em>I</em> took away: Thor is good to use for making a CLI, <code>bundle gem</code> is good to use for making a gem and sometimes you can make something small and cool for yourself in one sitting which gives you a good feeling and is a well invested 5 hours.</p>
]]></content:encoded>
			<wfw:commentRss>http://garbled.benhamill.com/2011/01/release-twitter_atm-1-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My First Ruby Gem</title>
		<link>http://garbled.benhamill.com/2010/05/my-first-ruby-gem/</link>
		<comments>http://garbled.benhamill.com/2010/05/my-first-ruby-gem/#comments</comments>
		<pubDate>Fri, 07 May 2010 14:00:03 +0000</pubDate>
		<dc:creator>benhamill</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[heygovote]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://garbled.benhamill.com/?p=32</guid>
		<description><![CDATA[I just released my first ruby gem, twitter_alert. It&#8217;s intended to be a component of the side project I mentioned forever ago, HeyGoVote. It grabs all the followers for a Twitter account and DMs them a message. The messages have dates on them because their intended to be schedule ahead of time. I&#8217;ll crib from [...]]]></description>
			<content:encoded><![CDATA[<p>I just released my first ruby gem, <a href="http://rubygems.org/gems/twitter_alert">twitter_alert</a>. It&#8217;s intended to be a component of the side project <a href="http://garbled.benhamill.com/2009/09/new-side-project-heygovote/">I mentioned</a> forever ago, HeyGoVote. It grabs all the followers for a Twitter account and DMs them a message. The messages have dates on them because their intended to be schedule ahead of time. I&#8217;ll crib from the readme near the end, but if you want, you can <a href="http://github.com/BenHamill/twitter_alert">go read the whole thing for yourself</a>. First, I&#8217;m going to talk a bit about my experience writing my first gem.</p>
<h4>Jeweler</h4>
<p>I used the <a href="http://github.com/technicalpickles/jeweler">jeweler</a> gem to create a gem template for this guy. It&#8217;s very simple and was a huge boon considering this was my first time. It scaffolds out the directory structure for you, sets up some handy rake tasks and generally gives you guidance on how to structure your gem. The readme for jeweler is very helpful. I won&#8217;t bother to restate what it says, but seriously, new to gems or not, you should have a look at jeweler if you haven&#8217;t already. One of the nicest things is that it&#8217;ll generate your gemspec file for you and also handle version bumping in a <a href="http://semver.org/">semantic versioning</a> compatible way. It also integrates with git and <a href="http://github.com">GitHub</a> in some interesting ways.</p>
<h4>Gemcutter</h4>
<p>Jeweler will also handle publishing your gem to &#8220;gemcutter&#8221; for you, which is nice. I say that in quotes because, of course, gemcutter.org is no longer a thing and their stuff all got officially adopted by <a href="http://rubygems.org">rubygems.org</a>, so it actually publishes to there. The jeweler documentation, though, all acts as if gemcutter were still a separate thing. This could be potentially confusing, I guess, but it ends up working right, so it&#8217;s fine. It does use the gemcutter gem to manage the publishing, so you&#8217;ll have to have that installed, and make sure you have a rubygems.org account and api key set up. The api key goes in ~/.gem/credentials as you&#8217;ll learn on your rubgems profile.</p>
<h4>twitter_alert</h4>
<p>I&#8217;ll crib from my readme example to show the most basic setup:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'twitter_alert'</span>
&nbsp;
account = <span style="color:#6666ff; font-weight:bold;">TwitterAlert::Account</span>.<span style="color:#9900CC;">new</span> <span style="color:#ff3333; font-weight:bold;">:user_name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'benhamill'</span>, <span style="color:#ff3333; font-weight:bold;">:password</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'thisisnotmyrealpassword'</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Alert
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">TiwtterAlert::Alert</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
alert = Alert.<span style="color:#9900CC;">new</span> <span style="color:#996600;">'Very important message.'</span>, <span style="color:#CC00FF; font-weight:bold;">DateTime</span>.<span style="color:#9900CC;">now</span>
&nbsp;
account.<span style="color:#9900CC;">announce</span> alert</pre></td></tr></table></div>

<p>In the wild, I don&#8217;t imagine that your Alert class will be so simple. For instance, when I plug this into HeyGoVote, it&#8217;ll be included in an ActiveRecord model so I can run a cron job that pulls out tweets that should go out today (based on the date) and sends them all.</p>
<p>I haven&#8217;t plugged this into code yet, and note the version number 0.1. The tests pass, but they may not be comprehensive and I might have botched something up in my publishing, but it looks like everything&#8217;s working to me. My next step is to start building up HeyGoVote and using twitter_alert in it, which might reveal some needed features. In the meantime, I welcome feedback. Leave a comment here, or <a href="http://github.com/BenHamill/twitter_alert">fork it</a> and issue me a pull request, if you have an idea.</p>
]]></content:encoded>
			<wfw:commentRss>http://garbled.benhamill.com/2010/05/my-first-ruby-gem/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>My Twitter Project: atreply</title>
		<link>http://garbled.benhamill.com/2009/02/my-twitter-project-atreply/</link>
		<comments>http://garbled.benhamill.com/2009/02/my-twitter-project-atreply/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 06:57:34 +0000</pubDate>
		<dc:creator>benhamill</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://garbled.benhamill.com/?p=10</guid>
		<description><![CDATA[I use Twitterfox to read and create tweets most of the time. I follow enough people that, when I open my browser for the first time for the day, more than 20 tweets have accumulated and, really, I don&#8217;t want to go back and read all 60-odd or whatever that have accumulated overnight. Twenty, I [...]]]></description>
			<content:encoded><![CDATA[<p>I use <a href="http://twitterfox.net/">Twitterfox</a> to read and create tweets most of the time. I follow enough people that, when I open my browser for the first time for the day, more than 20 tweets have accumulated and, really, I don&#8217;t want to go back and read all 60-odd or whatever that have accumulated overnight. Twenty, I should note, is just what Twitterfox picks up when it first turns on.</p>
<p>Occasionally, I&#8217;ll come in and see the last few tweets in a conversation between two people I&#8217;m following (I only see @replies by others who are to people I&#8217;m also following). If it seems interesting enough, I&#8217;ll go back and page through to see what they were talking about, reading in reverse order. Sort of like reading a chat log written by the guys that made <a href="http://www.imdb.com/title/tt0209144/">Memento</a>. It&#8217;s not horrible, but neither is it ideal.</p>
<p>So I had an idea about it and I&#8217;ve started work. Twitter tracks what tweet (technically called a &#8220;Twitter status&#8221;, apparently) any given tweet was a reply to. And, I figured, it would be relatively simple to, given a Twitter status ID, recursively follow the reply chain back and get the whole conversation. Turns out, I was right.</p>
<p>A proof of concept:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'rubygems'</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'twitter'</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Reply
 attr_accessor <span style="color:#ff3333; font-weight:bold;">:text</span>, <span style="color:#ff3333; font-weight:bold;">:author</span>, <span style="color:#ff3333; font-weight:bold;">:in_reply_to</span>, <span style="color:#ff3333; font-weight:bold;">:time</span>, <span style="color:#ff3333; font-weight:bold;">:atreply</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">def</span> initialize status_id
   status = <span style="color:#6666ff; font-weight:bold;">Twitter::Client</span>.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">status</span> <span style="color:#ff3333; font-weight:bold;">:get</span>, status_id
&nbsp;
   <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">text</span> = status.<span style="color:#9900CC;">text</span>
   <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">author</span> = <span style="color:#9966CC; font-weight:bold;">if</span> status.<span style="color:#9900CC;">user</span>.<span style="color:#9900CC;">name</span> <span style="color:#9966CC; font-weight:bold;">then</span> status.<span style="color:#9900CC;">user</span>.<span style="color:#9900CC;">name</span> <span style="color:#9966CC; font-weight:bold;">else</span> status.<span style="color:#9900CC;">user</span>.<span style="color:#9900CC;">screen_name</span> <span style="color:#9966CC; font-weight:bold;">end</span>
   <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">time</span> = status.<span style="color:#9900CC;">created_at</span>
   <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">in_reply_to</span> = status.<span style="color:#9900CC;">in_reply_to_status_id</span>
   <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">atreply</span> = Reply.<span style="color:#9900CC;">new</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">in_reply_to</span> <span style="color:#9966CC; font-weight:bold;">unless</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">in_reply_to</span>.<span style="color:#0000FF; font-weight:bold;">nil</span>?
 <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">def</span> each_reply <span style="color:#006600; font-weight:bold;">&amp;</span>amp;block
   reply_chain.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>reply<span style="color:#006600; font-weight:bold;">|</span>
     <span style="color:#9966CC; font-weight:bold;">yield</span> reply
   <span style="color:#9966CC; font-weight:bold;">end</span>
 <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">def</span> to_s
   <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">author</span> <span style="color:#006600; font-weight:bold;">+</span> <span style="color:#996600;">' - '</span> <span style="color:#006600; font-weight:bold;">+</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">time</span>.<span style="color:#9900CC;">to_s</span> <span style="color:#006600; font-weight:bold;">+</span> <span style="color:#996600;">&quot;<span style="color:#000099;">\n</span>&quot;</span> <span style="color:#006600; font-weight:bold;">+</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">text</span>
 <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
 protected
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">def</span> reply_chain
   <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#0000FF; font-weight:bold;">self</span><span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#9966CC; font-weight:bold;">unless</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">atreply</span>
&nbsp;
   <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">atreply</span>.<span style="color:#9900CC;">reply_chain</span> <span style="color:#006600; font-weight:bold;">&amp;</span>lt;<span style="color:#006600; font-weight:bold;">&amp;</span>lt; <span style="color:#0000FF; font-weight:bold;">self</span>
 <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>This has a dependency on <a href="http://github.com/joshuamiller/twitter4r/tree/master">Joshuamiller&#8217;s version of twitter4r</a>. My medium-term plan is to make a one-trick-website that will take an ID or twitter URL and give you the replies all pretty-like. Maybe make a bookmarklet for convenience&#8217;s sake. I plan on using Rails, even though that&#8217;s overkill because I figure it&#8217;ll be a good learning experience on that front. Find it on <a href="http://github.com/BenHamill/atreply/tree/master">Github</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://garbled.benhamill.com/2009/02/my-twitter-project-atreply/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

