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

  <title><![CDATA[Strong Opinions Weakly Typed]]></title>
  <link href="https://www.strongopinionsweaklytyped.com/atom.xml" rel="self"/>
  <link href="https://www.strongopinionsweaklytyped.com/"/>
  <updated>2018-12-07T07:54:10-05:00</updated>
  <id>https://www.strongopinionsweaklytyped.com/</id>
  <author>
    <name><![CDATA[Andrew Warner]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Faster and Simpler With the Command Line: Deep-comparing Two 5GB JSON Files 3X Faster by Ditching the Code]]></title>
    <link href="https://www.strongopinionsweaklytyped.com/blog/2018/12/07/faster-and-simpler-with-the-command-line-deep-comparing-two-5gb-json-files-3x-faster-by-ditching-the-code/"/>
    <updated>2018-12-07T07:42:27-05:00</updated>
    <id>https://www.strongopinionsweaklytyped.com/blog/2018/12/07/faster-and-simpler-with-the-command-line-deep-comparing-two-5gb-json-files-3x-faster-by-ditching-the-code</id>
    <content type="html"><![CDATA[<p><em>This post also appeared on <a href="https://genius.engineering/faster-and-simpler-with-the-command-line-deep-comparing-two-5gb-json-files-3x-faster-by-ditching-the-code/">the Genius Engineering blog</a>.</em></p>

<p>As part of our <a href="https://genius.com/a/genius-gets-smart-with-apple-music">recently announced deal with Apple Music</a>, you can now view Genius lyrics for your favorite music within the Apple Music app.</p>

<p>We deliver our lyrics to Apple via a nightly export of newline-delimited JSON objects. With millions of songs in our catalog, these dumps can easily get as big as 5 GB. It’s not quite “big data”, but it’s also not something you can easily open in vim.</p>

<p>Our first iteration of the code that generated these nightly exports was slow and failure-prone. So, we recently did a ground up rewrite focused on speed and reliability, which yielded significant improvements on both axes—stay tuned for a future blog post on that subject. But other than spot-checking with small data sets, how could we make sure that the new export process wasn’t introducing regressions? We decided to run both export processes concurrently and compare the generated exports from each method to make sure the new version was a comprehensive replacement.</p>

<!-- more -->


<p>What’s the best way to compare these two 5GB files? A good first check is whether the new and old exports have the same number of lines; we can do this on the command line by dividing <code>wc -l</code> (line count) of the old export by <code>wc -l</code> of the new export using <code>bc</code>. If you haven’t seen <code>bc</code> before, don&rsquo;t worry: I hadn&rsquo;t either! It’s a tool to do simple arithmetic in the console.</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>
</pre></td><td class='code'><pre><code class=''><span class='line'>$ echo "scale=3; $(wc -l &lt; old_export.json) / $(wc -l &lt; new_export.json)" | bc
</span><span class='line'>.999</span></code></pre></td></tr></table></div></figure>


<p>Ok great! The old export has 99.9% of the line count of the new export, meaning the new version actually has <em>more</em> lines than the old export, so off to a good start.</p>

<p>Next, we can use <code>diff</code> to get the percentage of lines that are different between the new and old export. We&rsquo;ll use the <code>--side-by-side</code> and <code>--suppress-common-lines</code> flags so that we can pipe the output from <code>diff</code> directly to <code>wc</code> to get a count of total lines that differ between the two exports.</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>
</pre></td><td class='code'><pre><code class=''><span class='line'>$ echo "scale=3; $(diff --side-by-side --suppress-common-lines old_export.json new_export.json | wc -l) / $(wc -l &lt; new_export.json)" | bc
</span><span class='line'>1.000</span></code></pre></td></tr></table></div></figure>


<p>OOPS! Our diff is showing 100% of the lines differing.. either we seriously screwed up with this new export or our diff methodology is flawed.</p>

<p>Let&rsquo;s take a look at how these objects are structured (payload slightly modified for simplicity):</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>
</pre></td><td class='code'><pre><code class=''><span class='line'>$ head -n2 old_export.json
</span><span class='line'>{"genius_id":1,"title":"Killa Cam","artist":"Cam’ron","featured_artists":["Opera Steve"],"producers":["The Heatmakerz"],"url":"https://genius.com/Camron-killa-cam-lyrics","lyrics":"..."}
</span><span class='line'>{"genius_id":3,"title":"Can I Live","artist":"JAY-Z","featured_artists":[],"producers":["Irv Gotti"], "url":"https://genius.com/Jay-z-can-i-live-lyrics","lyrics":"..."}</span></code></pre></td></tr></table></div></figure>


<p>Fairly standard newline-delimited JSON. Let&rsquo;s look at the new export:</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>
</pre></td><td class='code'><pre><code class=''><span class='line'>$ head -n2 new_export.json
</span><span class='line'>{"url": "https://genius.com/Lil-wayne-fly-out-lyrics", "title": "Fly Out", "artist": "Lil Wayne", "lyrics": "...", "genius_id": 23, "producers": ["Marques Houston", "T-Mix"], "featured_artists": []}
</span><span class='line'>{"url": "https://genius.com/Wu-tang-clan-cream-lyrics", "title": "C.R.E.A.M.", "artist": "Wu-Tang Clan", "lyrics": "...", "genius_id": 28, "producers": ["RZA"],"featured_artists": []}</span></code></pre></td></tr></table></div></figure>


<p>Yikes, it appears that not only does the new export methodology not order songs in the same way, it doesn&rsquo;t have the same order of keys within each JSON object. This means that even if the actual JSON content of the files was 100% the same, it would look 100% different with our naive <code>diff</code> strategy.</p>

<h3>Enter <code>jq</code></h3>

<p>My first thought was to write a ruby script to parse and compare the two exports, but after spending a little time coding something up I had a program that was starting to get fairly complicated, didn&rsquo;t work correctly, <em>and</em> was too slow—my first cut took well over an hour. Then I thought: is this one of those situations where a simple series of shell commands can replace a complex purpose-built script?</p>

<p>Enter <code>jq</code>, <a href="https://stedolan.github.io/jq/">a powerful command-line tool for processing JSON objects</a>. Note: <code>jq</code> is not related to jQuery, but its name does make googling for examples a little tricky! Up until this point I had mostly used <code>jq</code> for pretty-printing JSON, a feature it is quite good at. For example, you can do:</p>

<figure class='code'><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=''><span class='line'>$ curl -s https://api.cdnjs.com/libraries/jquery | jq</span></code></pre></td></tr></table></div></figure>


<p>And see a nice pretty-printed version of the CDNJS response for jQuery.</p>

<p><code>jq</code> also allows you to dig out specific fields from some JSON, e.g. going back to our exports, to get the list of ids from each export:</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>
</pre></td><td class='code'><pre><code class=''><span class='line'>$ head -n2 old_export.json | jq '.genius_id'
</span><span class='line'>1
</span><span class='line'>3
</span><span class='line'>$ head -n2 new_export.json | jq '.genius_id'
</span><span class='line'>23
</span><span class='line'>28</span></code></pre></td></tr></table></div></figure>


<p>That&rsquo;s pretty much all I had used <code>jq</code> for before looking through these exports. But it turns out that <code>jq</code> is incredibly powerful as a tool for processing JSON (check out <a href="https://github.com/stedolan/jq/wiki/Cookbook">the <code>jq</code> cookbook</a> to see some of the neat things that are possible). You can run entire programs, or “filters” as <code>jq</code> calls them (“filter” because it takes an input and produces an output), to iterate over, modify, and transform JSON objects.</p>

<p>How can we use it to solve the problem at hand, diffing these two large JSON files?</p>

<p>Well first we need to sort these files so that tools like <code>diff</code> can easily compare them. But we can&rsquo;t just use <code>sort</code>; we need to sort them by the value of the <code>genius_id</code>s in their payload.</p>

<p>It turns out this is quite easy with <code>jq</code>. To sort the exports by <code>genius_id</code> we can run:</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>
</pre></td><td class='code'><pre><code class=''><span class='line'>$ cat old_export.json | jq -csMS 'sort_by(.genius_id)[]' &gt; sorted_old_export.json
</span><span class='line'>$ cat new_export.json | jq -csMS 'sort_by(.genius_id)[]' &gt; sorted_new_export.json</span></code></pre></td></tr></table></div></figure>


<p>Running through these options:</p>

<ul>
<li><code>-c / --compact-output</code> makes sure the JSON objects remain compact and not pretty printed</li>
<li><code>-s / --slurp</code> reads each object into an in-memory array instead of processing one object at a time, which we need in order to sort the file</li>
<li><code>-M / --monochrome-output</code> prevents the JSON from being colorized in the terminal</li>
<li><code>-S / --sort-keys</code> makes sure that each JSON object&rsquo;s keys are sorted, ensuring that the order of keys within each object payload is consistent between exports when we compare them</li>
</ul>


<p>And, of course, the <code>jq</code> expression to sort the file itself is quite terse! It&rsquo;s just <code>sort_by(.genius_id)</code>, which sorts the slurped in array by id, and then there&rsquo;s a little <code>[]</code> on the end which basically splays the sorted array back out into newline-delimited JSON.</p>

<p>This takes a little while, but once it&rsquo;s done we&rsquo;ve got two sorted files ready to be compared!</p>

<p>But wait.. not so fast. There are still a few keys in our export, specifically <code>featured_artists</code> and <code>producers</code> that are arrays of string values, and it&rsquo;s not guaranteed that each export will generate those in the same order.</p>

<p>Not to worry: <code>jq</code> has a solution to that problem too! We want to sort each of those keys in the output as well, which we can do by complicating our expression just a little more:</p>

<figure class='code'><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=''><span class='line'>$ cat old_export.json | jq -csMS 'map(.featured_artists |= sort | .producers |= sort) | sort_by(.genius_id)[]' &gt; sorted_old_export.json</span></code></pre></td></tr></table></div></figure>


<p>So now the expression is a little more tricky. Let&rsquo;s break it down.</p>

<ul>
<li><code>map</code> does what you expect and maps over each object, much as <code>sort_by</code> operates on each object.</li>
<li>Within that <code>map</code> operation we&rsquo;re first calling <code>.featured_artists |= sort</code>, which uses the <a href="https://stedolan.github.io/jq/manual/#Update-assignment:|="><code>|=</code> update operator</a> to do an in-place alphabetic sort on the <code>featured_artists</code> array. This is a bit confusing, but all it&rsquo;s doing is running the value of <code>featured_artists</code> through a <code>sort</code> &ldquo;filter&rdquo;, sorting it, then assigning that sorted value back to the <code>featured_artists</code> key of the object, and passing on the the entire object that <code>featured_artists</code> key is in. It would be equivalent to <code>map(.featured_artists = (.featured_artists | sort))</code>. If you don&rsquo;t know what that <code>|</code> does, don&rsquo;t worry.. read on!</li>
<li>Next up we use <a href="https://stedolan.github.io/jq/manual/#Pipe:|"><code>|</code> operator</a> to pipe the previous step to our next step which just sorts the <code>producers</code> array exactly as we did the <code>featured_artists</code> array. The pipe operator works exactly like the unix-style pipe on the command line, so we&rsquo;re essentially sorting the <code>featured_artists</code> array, returning the full object it resides in, and then running that same operation for <code>producers</code> on the result.</li>
<li>And then we just feed that object with its sorted arrays into our sort operator from before using another pipe.</li>
</ul>


<p>And voila! We&rsquo;ve got two normalized 5 GB JSON blobs, all that&rsquo;s left is to feed them back into our <code>diff</code> operation just like before to see how similar they are:</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>
</pre></td><td class='code'><pre><code class=''><span class='line'>$ echo "scale=3; $(diff --side-by-side --suppress-common-lines sorted_old_export.json sorted_new_export.json | wc -l) / $(wc -l &lt; sorted_new_export.json)" | bc
</span><span class='line'>.002</span></code></pre></td></tr></table></div></figure>


<p>So after all that normalizing we find that only 0.2% of the lines differ between the exports! That&rsquo;s an incredible start for a complete rewrite of fairly complicated export process. Plus this whole thing takes about 10 minutes to generate each normalized file on my macbook pro and then less than a minute to compare them, already much faster than my naive ruby script.</p>

<p>The final step was looking through specific differing examples to figure out why the logic produced slightly different export outputs, but getting into the details of that is application logic and not what this post is about.</p>

<p>Hopefully now you&rsquo;ll reach for <code>jq</code> the next time you want to manipulate JSON files on the command line.. or at least if you want to pretty print an API response.</p>

<h2>Additional discussion</h2>

<p>One thing that bugged me about this solution was the explicit sorting of each key. What if we later added more arrays, or if we had deeply nested objects! Since we were just comparing two specific export results with an unchanging schema over the course of a couple of weeks, this didn&rsquo;t really matter, but it was bugging me so I poked around looking for a more generic way of normalizing JSON objects.</p>

<p>If you check out the <a href="https://github.com/stedolan/jq/wiki/FAQ#general-questions"><code>jq</code> FAQ</a> you&rsquo;ll find that there was a function called <code>walk</code> introduced as a built-in after 1.5, which allows you deeply iterate through JSON objects and modify them. It wasn&rsquo;t in the version I was using but it was simple enough to copy it into my program, which it turns out made the code much simpler:</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>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="err">#</span> <span class="nx">from</span> <span class="nx">https</span><span class="o">:</span><span class="c1">//github.com/stedolan/jq/wiki/FAQ#general-questions</span>
</span><span class='line'>
</span><span class='line'><span class="nx">def</span> <span class="nx">walk</span><span class="p">(</span><span class="nx">f</span><span class="p">)</span><span class="o">:</span>
</span><span class='line'>  <span class="p">.</span> <span class="nx">as</span> <span class="nx">$in</span>
</span><span class='line'>    <span class="o">|</span> <span class="k">if</span> <span class="nx">type</span> <span class="o">==</span> <span class="s2">&quot;object&quot;</span> <span class="nx">then</span>
</span><span class='line'>    <span class="nx">reduce</span> <span class="nx">keys_unsorted</span><span class="p">[]</span> <span class="nx">as</span> <span class="nx">$key</span>
</span><span class='line'>    <span class="p">(</span> <span class="p">{};</span> <span class="p">.</span> <span class="o">+</span> <span class="p">{</span> <span class="p">(</span><span class="nx">$key</span><span class="p">)</span><span class="o">:</span>  <span class="p">(</span><span class="nx">$in</span><span class="p">[</span><span class="nx">$key</span><span class="p">]</span> <span class="o">|</span> <span class="nx">walk</span><span class="p">(</span><span class="nx">f</span><span class="p">))</span> <span class="p">}</span> <span class="p">)</span> <span class="o">|</span> <span class="nx">f</span>
</span><span class='line'>    <span class="nx">elif</span> <span class="nx">type</span> <span class="o">==</span> <span class="s2">&quot;array&quot;</span> <span class="nx">then</span> <span class="nx">map</span><span class="p">(</span> <span class="nx">walk</span><span class="p">(</span><span class="nx">f</span><span class="p">)</span> <span class="p">)</span> <span class="o">|</span> <span class="nx">f</span>
</span><span class='line'>    <span class="k">else</span> <span class="nx">f</span>
</span><span class='line'>    <span class="nx">end</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="err">#</span> <span class="nx">actual</span> <span class="nx">custom</span> <span class="nx">jq</span> <span class="nx">program</span>
</span><span class='line'><span class="nx">walk</span><span class="p">(</span> <span class="k">if</span> <span class="nx">type</span> <span class="o">==</span> <span class="s2">&quot;array&quot;</span> <span class="nx">then</span> <span class="nx">sort</span> <span class="k">else</span> <span class="p">.</span> <span class="nx">end</span> <span class="p">)</span> <span class="o">|</span> <span class="nx">sort_by</span><span class="p">(.</span><span class="nx">genius_id</span><span class="p">)[]</span>
</span></code></pre></td></tr></table></div></figure>


<p>It turned out that this also made it significantly slower to normalize each file, so I ended up just using the more verbose and brittle version, but the <code>walk</code> version is a lot cleaner!</p>

<p>Also, you might be curious how you can run the above file.. you can also run <code>jq</code> program files using the <code>-f</code> option, 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>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">$</span> <span class="nx">cat</span> <span class="nx">my_file</span><span class="p">.</span><span class="nx">json</span> <span class="o">|</span> <span class="nx">jq</span> <span class="o">-</span><span class="nx">csMS</span> <span class="o">-</span><span class="nx">f</span> <span class="nx">normalize</span><span class="p">.</span><span class="nx">jq</span>
</span></code></pre></td></tr></table></div></figure>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Beware the Siren Song of Comments]]></title>
    <link href="https://www.strongopinionsweaklytyped.com/blog/2014/08/27/beware-the-siren-song-of-comments/"/>
    <updated>2014-08-27T08:37:08-04:00</updated>
    <id>https://www.strongopinionsweaklytyped.com/blog/2014/08/27/beware-the-siren-song-of-comments</id>
    <content type="html"><![CDATA[<div id='rg_embed_link_521365' class='rg_embed_link'>

<p>
Developers love comments! Everyone who writes a comment thinks that they&#8217;re making a <a href="http://en.wikipedia.org/wiki/Pareto_efficiency">pareto improvement</a> to the codebase, when in fact it&#8217;s quite the opposite. Comments are especially dangerous because there are many situations where it <i>seems</i> like a comment will help, but beware the siren&#8217;s call.

I hate reading articles that make abstract arguments, so enough bloviating, let&#8217;s check out some examples. Here are some concrete uses of comments that I&#8217;ve seen a lot, and how they can be easily avoided.
</p>

<!-- more -->

Read <a href="http://tech.genius.com/Andrew-warner-beware-the-siren-song-of-comments-annotated">“Beware the Siren Song of Comments” by Andrew Warner</a> on News Genius

</div>




<script src='//tech.genius.com/songs/521365/embed.js?u=143768'></script>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Choosing a New Theme]]></title>
    <link href="https://www.strongopinionsweaklytyped.com/blog/2014/08/13/choosing-a-new-theme/"/>
    <updated>2014-08-13T23:25:46-04:00</updated>
    <id>https://www.strongopinionsweaklytyped.com/blog/2014/08/13/choosing-a-new-theme</id>
    <content type="html"><![CDATA[<p>About a week ago I finally decided that I wanted to start blogging again. I love talking about programming, but I often find it
difficult to motivate myself to write a blog post about it. I sat down to write a post, and sure enough, I couldn&rsquo;t think of anything
to blog about. So instead I procrastinated by thinking about all of the things I wanted to do to make my blog better.</p>

<!-- more -->


<p>The most obvious problem was that I was still using the default <a href="https://github.com/imathis/octopress">Octopress</a> theme.
It has a lot of nice qualities: it&rsquo;s easy to navigate around, easy to read, and it&rsquo;s responsive! Unfortunately,
using the default theme meant that my site also looked exactly like
<a href="https://github.com/imathis/octopress/wiki/Octopress-Sites">everyone else&rsquo;s</a>.</p>

<p>Now Octopress is also great because it&rsquo;s extremely easy for anyone to make a theme. In fact, a
<a href="https://github.com/imathis/octopress/wiki/3rd-Party-Octopress-Themes">bunch of people</a> have already done exactly that. Looking at the
list of themes, though, I realized that it was difficult to tell which ones were &ldquo;the good ones.&rdquo; Normally when I have a huge list of
products that I want to comb through, I&rsquo;m on a website where I can easily sort by some metadata about the product. (e.g. Amazon)
My preferred sort is always by popularity: I basically trust the wisdom of the crowd. On Amazon, for example, I&rsquo;m much more interested
in the product with the most reviews than I am in the product with the best average review. Unfortunately, GitHub tables have no such
convenient sorting options!</p>

<p>Luckily, I&rsquo;m a programmer, and, wanting to procrastinate more, I decided that I wanted to write a quick script to sort projects by
number of stars. As it turns out, it&rsquo;s pretty simple to use <a href="http://nokogiri.org/">Nokogiri</a> and <a href="https://github.com/octokit/octokit.rb">Octokit</a> to get the information I want:</p>

<div><script src='https://gist.github.com/60afe3ffdd0872719247.js'></script>
<noscript><pre><code>require 'nokogiri'
require 'octokit'
require 'open-uri'

github = Octokit::Client.new(:access_token =&gt; ENV['GH_TOKEN'])

doc = Nokogiri::HTML.fragment(open('https://github.com/imathis/octopress/wiki/3rd-Party-Octopress-Themes').read)

doc.search('table tr td:first a:first').map do |a|
  a['href'] =~ %r{https?://github.com/([^/]+)/([^?/]+)(\?|$|/)} &amp;&amp; [$1, $2]
end.compact.map do |owner, repo_name|
  begin
    github.repository(:owner =&gt; owner, :name =&gt; repo_name)
  rescue Octokit::NotFound
  end
end.compact.sort_by { |repo| -repo.stargazers_count }.each do |repo|
  puts &quot;#{repo.html_url} - #{repo.stargazers_count}&quot;
end</code></pre></noscript></div>


<p>This script simply:</p>

<ul>
<li>scrapes the <a href="https://github.com/imathis/octopress/wiki/3rd-Party-Octopress-Themes">themes page</a></li>
<li>parses it with Nokogiri</li>
<li>finds the table with the themes</li>
<li>selects the link from the first column of each row, which is the link to the theme repository on GitHub</li>
<li>extracts the owner and repo name using a &ldquo;simple&rdquo; regular expression</li>
<li>maps owner/repo to number of stars</li>
<li>prints a sorted list of repo links and stars</li>
</ul>


<p>and voila, we have an Amazon-like sort by popular-type situation. (check out the results in the <a href="https://gist.github.com/a-warner/60afe3ffdd0872719247">gist comments</a>)</p>

<p>After checking out the popular themes, I decided, contrary to my usual shopping strategy, that I wasn&rsquo;t in love with any of them.
I was looking for something simple, single-column, and easy to read. I ended up settling on
<a href="https://github.com/mjhea0/whiterspace">whiterspace</a>, which, even though it only had 45 stars, was exactly what I was looking for.</p>

<p>So, while I didn&rsquo;t end up choosing the most popular theme, it was still useful to be able to look at a mapping of themes to popularity.
In the end, whiterspace got one more star, and I got a cleaner, more distinct-looking blog. Oh, and in doing all of this work, I ended up with a
somewhat interesting topic to blog about (I hope!), accomplishing my original goal in a somewhat roundabout way. Win win win!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Git-getpull: Quickly Find the Pull Request That Merged Your Commit to Master]]></title>
    <link href="https://www.strongopinionsweaklytyped.com/blog/2014/03/06/git-getpull-quickly-find-the-pull-request-that-merged-your-commit-to-master/"/>
    <updated>2014-03-06T14:40:00-05:00</updated>
    <id>https://www.strongopinionsweaklytyped.com/blog/2014/03/06/git-getpull-quickly-find-the-pull-request-that-merged-your-commit-to-master</id>
    <content type="html"><![CDATA[<div id='rg_embed_link_270809' class='rg_embed_link'>
  <span style="display: none;"
    Read <a href="http://news.rapgenius.com/Andrew-warner-git-getpull-quickly-find-the-pull-request-that-merged-your-commit-to-master-annotated">&#8220;Git-getpull: Quickly find the pull request that merged your commit to master&#8221; by Andrew Warner</a> on News Genius
  </span>

  <p>
  Ideally <code><a href="http://genius.com/2457353" target="_blank">git blame</a></code> would give you all the context you need to determine why some code was written. But the reality is that no team is perfectly disciplined, and sometimes you&#8217;re going to run across commits with cryptic or ambiguous messages (&#8220;bugfix,&#8221; anyone?).
  </p>
</div>




<!-- more -->




<script src='//news.rapgenius.com/songs/270809/embed.js'></script>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The 3 Ways to Get the Size of an Active Record Relation]]></title>
    <link href="https://www.strongopinionsweaklytyped.com/blog/2013/04/21/the-3-ways-to-get-the-size-of-an-active-record-relation/"/>
    <updated>2013-04-21T18:14:00-04:00</updated>
    <id>https://www.strongopinionsweaklytyped.com/blog/2013/04/21/the-3-ways-to-get-the-size-of-an-active-record-relation</id>
    <content type="html"><![CDATA[<p>If you&rsquo;re reading this and your first thought is, &ldquo;there are 3 ways to get the size of a relation?&rdquo;, then
you&rsquo;ve come to the right place! Basically, given a relation like <code>Post.all</code> or <code>User.first.posts</code>, when you
want to know the size, you&rsquo;ve got 3 choices: <code>size</code>, <code>length</code>, and <code>count</code>.  At first glance, it seems like these
might do the same thing, right?  Not so!  There are some key differences between them.</p>

<!-- more -->


<p>TL;DR - use <code>size</code>, it usually &ldquo;Does the Right Thing&rdquo;</p>

<p>First off, some background: both <code>Post.all</code> and <code>User.first.posts</code> are instances of <code>ActiveRecord::Relation</code>,
a very sneaky and
powerful class which manages lazy loading of records from the database. (full disclosure, <code>User.first.posts</code> is
actually an instance of <code>ActiveRecord::Associations::CollectionProxy</code>, but the difference between the two isn&rsquo;t
really relevant to this article).  It makes a best effort to filter, and
order records until the last possible minute when you actually ask for something concrete.  It&rsquo;s that lazy loading
which allows you to write code like <code>Post.where(featured: true).order(created_at: :desc).paginate(page: 1)</code>, which
will generate only one query for the first page of posts.  If you want to get the size of a Relation, there are
3 different ways to ask for it:</p>

<h3>length</h3>

<p>The simplest of the three methods, <code>length</code> is simply delegated to <code>to_a</code> on the collection; in other words, calling
length is equivalent to calling <code>Post.all.to_a.length</code>.  It will query for ALL records, initialize ruby objects for
all of them, and then get the size of the array.  Probably not what you want if you just want to display the count
of the Posts on your blog!</p>

<h3>count</h3>

<p>Does a sql <code>count(*)</code> query for the count of the records in the database.  You probably want to use this method
if you only ever need the count of the records in the association for whatever you&rsquo;re doing.  In the example above,
just displaying a count on the page is a perfect use case for <code>count</code>.</p>

<h3>size</h3>

<p>Size makes a best effort attempt to &ldquo;Do The Right Thing&rdquo; based on the current state of the collection.  Here is the
actual source for size:</p>

<p>From <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation.rb#L205">ActiveRecord::Relation</a>:</p>

<figure class='code'><figcaption><span>lib/active_record/relation.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>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'>  <span class="c1"># Returns size of the records.</span>
</span><span class='line'>  <span class="k">def</span> <span class="nf">size</span>
</span><span class='line'>    <span class="n">loaded?</span> <span class="p">?</span> <span class="vi">@records</span><span class="o">.</span><span class="n">length</span> <span class="p">:</span> <span class="n">count</span>
</span><span class='line'>  <span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>Great comment by the way, I never would have known what <code>size</code> did without it.</p>

<p>Basically, size is a heuristic switch between <code>length</code> and <code>count</code>.  If the collection is loaded, it just
gets the length of the loaded array, otherwise it will hit the database with a query.  As pointed out in a
<a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/collection_proxy.rb#L677">much more informative comment which is for some reason in the CollectionProxy object instead</a>,
you&rsquo;ll end up with an extra query if you call <code>size</code> and then actually need the elements of the collection later.</p>

<p>In a lot of cases the differences are completely irrelevant, but, for my money, <code>size</code> is the best of the 3 options.
It does the best job of not leaking details about what&rsquo;s going on under the hood in terms of lazy loading in Active
Record.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Use the Rails Router for Routing!]]></title>
    <link href="https://www.strongopinionsweaklytyped.com/blog/2013/04/21/use-the-rails-router-for-routing/"/>
    <updated>2013-04-21T17:41:00-04:00</updated>
    <id>https://www.strongopinionsweaklytyped.com/blog/2013/04/21/use-the-rails-router-for-routing</id>
    <content type="html"><![CDATA[<p>This is a quick one, and the title says most of it.  Basically, you should never have code like this in
your app:</p>

<figure class='code'><figcaption><span>some_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>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">SomeController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
</span><span class='line'>  <span class="k">def</span> <span class="nf">some_action</span>
</span><span class='line'>    <span class="k">if</span> <span class="n">something_about_the_url?</span>
</span><span class='line'>      <span class="n">do_something</span>
</span><span class='line'>      <span class="n">render</span> <span class="ss">:template</span> <span class="o">=&gt;</span> <span class="ss">:foo</span>
</span><span class='line'>    <span class="k">else</span>
</span><span class='line'>      <span class="n">do_something_else</span>
</span><span class='line'>      <span class="n">render</span> <span class="ss">:template</span> <span class="o">=&gt;</span> <span class="ss">:baz</span>
</span><span class='line'>    <span class="k">end</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>


<!-- more -->


<p>The whole point of the router is to handle stuff about the url!  Instead, move whatever the logic inside
<code>something_about_the_url?</code> does upstream to the router layer.  For example, say you want to display a different
home page for www.mysite.com and blog.mysite.com.  This can be accomplished very easily using the router:</p>

<figure class='code'><figcaption><span>routes.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="n">constraints</span> <span class="ss">subdomain</span><span class="p">:</span> <span class="s1">&#39;blog&#39;</span> <span class="k">do</span>
</span><span class='line'>  <span class="n">root</span> <span class="ss">to</span><span class="p">:</span> <span class="s1">&#39;blog#home&#39;</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="n">root</span> <span class="ss">to</span><span class="p">:</span> <span class="s1">&#39;static#home&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note that, in this specific case, you must have the subdomain route above the <code>root</code> route, otherwise the router
will match the route to <code>static#home</code> before it gets to the subdomain constraint.  Remember that the router
checks routes in order.  All set!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Simple Active Record Query Debugging in the Rails Console]]></title>
    <link href="https://www.strongopinionsweaklytyped.com/blog/2013/03/17/simple-active-record-query-debugging-in-the-rails-console/"/>
    <updated>2013-03-17T18:22:00-04:00</updated>
    <id>https://www.strongopinionsweaklytyped.com/blog/2013/03/17/simple-active-record-query-debugging-in-the-rails-console</id>
    <content type="html"><![CDATA[<p>Stop me if this sounds familiar.  You&rsquo;re tooling around in the Rails console, testing out some new code you&rsquo;re working on (or debugging some slow/broken code), and you see a ton of repeat queries.</p>

<p>I have this experience frequently; usually I can figure out what&rsquo;s going on, but sometimes it can be quite tricky to track down the source of extra queries.  Whenever I want to figure out where a method is getting called from, one easy and lazy solution is to add a debugger statement in that code.  But where the heck do I add a debugger for sql statements?</p>

<!-- more -->


<p>It turns out that Active Record has a fairly unified choke-point for query execution on a per-model basis - <code>#find_by_sql</code>.  So, now that we know the method, what&rsquo;s the best way to add the debugger statement?  Well, we <em>could</em> just open up the gem code, but then we have to restart our console, and we run the risk of forgetting to remove the statement or otherwise screwing up the gem code in some way that&rsquo;s difficult to track down.  We could monkey patch the method, but even that sounds onerous, especially if we want the method to be usable again without hitting that debugger statement later in our session.</p>

<p>Enter a relatively short addition to your <code>.irbrc</code> or <code>.pryrc</code>!  Simply add the following 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>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">def</span> <span class="nf">add_debugger</span><span class="p">(</span><span class="n">clazz</span><span class="p">,</span> <span class="nb">method</span><span class="p">)</span>
</span><span class='line'>  <span class="n">debugger_method</span> <span class="o">=</span> <span class="nb">binding</span><span class="o">.</span><span class="n">respond_to?</span><span class="p">(</span><span class="ss">:pry</span><span class="p">)</span> <span class="p">?</span> <span class="s1">&#39;binding.pry&#39;</span> <span class="p">:</span> <span class="s1">&#39;debugger&#39;</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">unless</span> <span class="n">clazz</span><span class="o">.</span><span class="n">method_defined?</span> <span class="s2">&quot;</span><span class="si">#{</span><span class="nb">method</span><span class="si">}</span><span class="s2">_with_debugger&quot;</span>
</span><span class='line'>    <span class="n">clazz</span><span class="o">.</span><span class="n">class_eval</span> <span class="o">&lt;&lt;-</span><span class="no">CODE</span><span class="p">,</span> <span class="bp">__FILE__</span><span class="p">,</span> <span class="bp">__LINE__</span> <span class="o">+</span> <span class="mi">1</span>
</span><span class='line'><span class="sh">      def #{method}_with_debugger(*args, &amp;block)</span>
</span><span class='line'><span class="sh">        #{debugger_method}</span>
</span><span class='line'><span class="sh">        #{method}_without_debugger(*args, &amp;block)</span>
</span><span class='line'><span class="sh">      end</span>
</span><span class='line'><span class="sh">      alias_method_chain :#{method}, :debugger</span>
</span><span class='line'><span class="no">    CODE</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>Note that my debugger preference is <code>pry</code>, if it&rsquo;s available.  You can of course adjust the above code per your preference.  Now we can simply 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='ruby'><span class='line'><span class="n">add_debugger</span> <span class="no">MyModel</span><span class="o">.</span><span class="n">singleton_class</span><span class="p">,</span> <span class="ss">:find_by_sql</span>
</span></code></pre></td></tr></table></div></figure>


<p>Running through our problem code again, you should find yourself in the debugger for any queries on <code>MyModel</code>.  Once in the debugger, simply inspect <code>caller</code> to figure out what pesky bit of code is generating all of the extra queries.</p>

<p>This is great, but it would incomplete if we had to restart the server in order to remove the debugger statement!  The following snippet should do the trick:</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='ruby'><span class='line'><span class="k">def</span> <span class="nf">remove_debugger</span><span class="p">(</span><span class="n">clazz</span><span class="p">,</span> <span class="nb">method</span><span class="p">)</span>
</span><span class='line'>  <span class="k">return</span> <span class="k">unless</span> <span class="n">clazz</span><span class="o">.</span><span class="n">method_defined?</span> <span class="s2">&quot;</span><span class="si">#{</span><span class="nb">method</span><span class="si">}</span><span class="s2">_with_debugger&quot;</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">clazz</span><span class="o">.</span><span class="n">class_eval</span> <span class="k">do</span>
</span><span class='line'>    <span class="n">alias_method</span> <span class="nb">method</span><span class="p">,</span> <span class="s2">&quot;</span><span class="si">#{</span><span class="nb">method</span><span class="si">}</span><span class="s2">_without_debugger&quot;</span>
</span><span class='line'>    <span class="n">undef_method</span> <span class="s2">&quot;</span><span class="si">#{</span><span class="nb">method</span><span class="si">}</span><span class="s2">_with_debugger&quot;</span>
</span><span class='line'>    <span class="n">undef_method</span> <span class="s2">&quot;</span><span class="si">#{</span><span class="nb">method</span><span class="si">}</span><span class="s2">_without_debugger&quot;</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>Just run <code>remove_debugger MyModel.singleton_class, :find_by_sql</code>, and you&rsquo;re back to regular development.</p>

<p>Now that you&rsquo;ve got this method, adding debugging statements to your own code or 3rd party code is a breeze!</p>

<p>Check out my <a href="https://github.com/a-warner/dotfiles/blob/master/.railsrc">.railsrc</a> for more little one-off development helper methods.</p>

<p>Is there an easier way to do this with pry?  Is there a gem that just does this and makes my silly code obsolete?  Let me know in the comments!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[My First Blog Post]]></title>
    <link href="https://www.strongopinionsweaklytyped.com/blog/2013/03/17/my-first-blog-post/"/>
    <updated>2013-03-17T18:07:00-04:00</updated>
    <id>https://www.strongopinionsweaklytyped.com/blog/2013/03/17/my-first-blog-post</id>
    <content type="html"><![CDATA[<p>This is my first blog post! I setup up my blog using <a href="http://octopress.org/">Octopress</a>, which was incredibly easy.  They&rsquo;ve got some great guides on their site, but just to give you a sense of exactly how easy it is, I simply:</p>

<ul>
<li>Created a repository on github named a-warner.github.com - the standard naming conventions that <a href="http://pages.github.com/">Github Pages</a> expects if I want a-warner.github.com to resolve to this blog</li>
<li>Cloned Octopress via <code>git clone git://github.com/imathis/octopress.git a-warner.github.com</code>, ran <code>bundle</code></li>
<li>Next step was to run <code>rake setup_github_pages</code></li>
<li>Then it&rsquo;s as simple as <code>rake generate</code> and <code>rake deploy</code>!</li>
<li>Creating this blog post just involved running <code>rake new_post["My first blog post"]</code></li>
</ul>


<p>The writing process is extremely simple - just run <code>rake preview</code> until it looks right, and then <code>rake deploy</code> after committing your changes.</p>

<p>Not that I should be surprised, but using Octopress is really a breeze, and I highly recommend it to anybody looking to crank out a quick blog with minimal setup and maintenance.</p>
]]></content>
  </entry>
  
</feed>
