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

  <title><![CDATA[Liam Kaufman]]></title>
  <link href="http://liamkaufman.com/atom.xml" rel="self"/>
  <link href="http://liamkaufman.com/"/>
  <updated>2014-08-05T20:19:51-04:00</updated>
  <id>http://liamkaufman.com/</id>
  <author>
    <name><![CDATA[Liam Kaufman]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Smiley Faces in Linux Source Code and Token Statistics]]></title>
    <link href="http://liamkaufman.com/blog/2014/08/05/smily-faces-in-linux-source-code/"/>
    <updated>2014-08-05T00:00:00-04:00</updated>
    <id>http://liamkaufman.com/blog/2014/08/05/smily-faces-in-linux-source-code</id>
    <content type="html"><![CDATA[<p>
  Github uses <a href="https://github.com/github/linguist">Linguist</a>, a Ruby library, to help detect which programming language is in a given file. Recently, an issue was filed that indicated that Linguist incorrectly classifies Mercury (a programming language) files as Objective-c since they both use the same extension (.m). Linguist’s primary method for language detection is a file’s extension - a method that fell short for Mercury. If Mercury were added to Linguist, then there would be two languages with the same extension - and this is where things get interesting. If two languages share the same extension, or the file does not have an extension, Linguist has 3 methods for guessing the language. First it checks if the file has a shebang (<code>#!/bin/sh</code>). If there is no shebang the second method it uses is a set of <a href="https://github.com/github/linguist/blob/master/lib/linguist/heuristics.rb">heuristics</a>. For instance, if the file includes the “:-” token it concludes that the contents are prologue code, or if “defun” is present it’s common lisp. If it still hasn’t found a match the third method it uses is a <a href="https://github.com/github/linguist/blob/master/lib/linguist/classifier.rb">Bayesian classifier</a>. Roughly speaking the classifier iterates over all of a file’s tokens, and for each token determines the probability that it is present in each programming language. Subsequently, it sums all those probabilities, sorts the results, and returns an array of language-probability pairs (e.g <code>[[‘Ruby’, 0.8], [‘Python’, 0.2]]</code>). 
</p>

<p>
  I wondered how logistic regression, support vector machines or even clustering algorithms would help in classifying a given file. As I dived into the data I realized that the descriptive statistics on tokens, and even ascii faces, would be nearly as interesting as their predictive power. Thus, this post will summarize the descriptive statistics, while in my next post I’ll cover using tokens to predict a file’s programming language.
</p>

<h2>Methods</h2>
<h3>Fetching The Code</h3>
<p>
  Using Github’s API I fetched the 10 most popular repositories for 10 languages (c, haskell, go, javascript, java, lua, objective-c, ruby, python and php). Those 10 were chosen for their popularity, differing paradigms (e.g. Haskell vs Java), differing syntax (Haskell vs go) and overlapping syntaxes (C, JavaScript and Java). After retrieving a list of 100 repositories I downloaded the zip ball for each repo.
</p>

<h3>Tokenizing The Code</h3>
<p>
  First, a list of common programming tokens (eg: <code>; , . ( )</code>, etc) was created - tokens that would be found in many of the 10 languages of interest. Using those tokens I created a tokenizer that would output an object with the keys being tokens and their values being the number of times that the token occurred in the file. Base 10 numbers, hex numbers, strings (double quotes) and ‘characters’ (single quotes) were treated as 4 different token types. This was done so the number 8 was not treated as a different token from the number 44 (they are both tokenized as “numbers”). 
</p>

<p>
  Each of the 100 repositories was traversed and non binary files were tokenized, with each file’s total token count stored in Redis’ sorted set data structure (sorted by number of occurrences). Using a sorted set made it trivial to retrieve the 1000 most common tokens from all 100 repositories. Each file was then re-tokenize, but only tokens that were present in the 1,000 most common token list were counted. A data set was created that included information on 65,804 files from 100 different repos. Along with the token data, the following data was also recorded: 1) the file’s extension, 2) it’s path within the repository, 3) it’s shebang, if present and 4) the token count for the first 250 most common tokens (I decided to limit my analysis on a smaller number of tokens for the first round of analysis). Finally, the counts for each token were converted to the ratio that that token occurred relative to the total occurrences. of all tokens (e.g. # of periods/total number of all tokens). The absolute number of tokens per file would be skewed by large files, which have more tokens. 
</p>

<h3>Counting Smiley Faces</h3>
<p>
  Two ease analysis I focused on c and JavaScript files (in c and JavaScript repositories): both languages have identical single and multi-line comment syntax. First, text from comments was separated from code. Second, the number of times an ascii face appeared in a given file’s comments was counted. The following “faces”:  <code>:( :) :-) :-D :p ;) ;-)</code> were counted.
</p>
<h3>Statistics</h3>
<p>
  All statistics were carried out using R. Welch Two Sample t-tests were used to compare groups.
</p>

<h2>Results</h2>
<h3>Tokens</h3>
<p>
  While the top 1,000 tokens, by occurrence were recorded, only the top 20 are presented in Table 1 (<a href="https://github.com/liamks/languageStatisticsData/blob/master/top1000Tokens.csv">see here for the top 1,000</a>). Not surprisingly numbers are the most prevalent token, with commas coming a very close second. Interestingly, and what sparked my interest in ascii smiley faces, is that there are slightly more right parentheses than left. While the contents of strings were ignored, the contents of comments were not. Seeing as most (all?) of the analyzed languages require parenthesis to be balanced I presumed that the imbalance might be caused by ascii smiley faces in comments.
</p>
<p>
  Interestingly, hexidecimal numbers were the 6th most common token despite rarely being used outside of c. While hex numbers are used extensively in CSS, I only classified numbers that started with &#8216;x&#8217; as being hex, which precluded the hex numbers in CSS from being included.
</p>
<style type="text/css">
  .largest {
    font-weight: bold;
    background-color: yellow  ;
  }
  .table-alternate tr:nth-child(odd){
    background-color:#ddd;
  }

  .alternate {
    background-color:#ddd;
  }

  .normal {
    background-color: #efefef;
  }

  .fixed-column{
    position: absolute;
    display: inline-block;
    width: auto;
  }
</style>
<script type="text/javascript">
  $.domReady(function(){
      var $table = $('.table-fixed');
      //Make a clone of our table
      var $firstColumnItems = $table.find('th:first-child,td:first-child');

      var firstColumnHeaderWidth = $($firstColumnItems[0]).width();

      //Match the height of the rows to that of the original table's
      $firstColumnItems.each(function (elem, i) {
          var node = this.cloneNode();
          node.textContent = $(this).text();
          
          $(node).addClass(i%2 === 0  ? 'alternate' : 'normal');
          $(node).height($(this).height());
          $(node).width(firstColumnHeaderWidth);
          $(node).addClass('fixed-column');
          $(this).before(node);
      });
  });
</script>

<div class="table table-alternate">
  <h2>Table 1. Top 20 Tokens By Occurence</h2>
  <table>
    <tr><th>Token</th><th>Occurrences</th></tr>
    <tr><td>Numbers</td><td>19,640,325</td></tr>
    <tr><td>,</td><td>19,597,223</td></tr>
    <tr><td>)</td><td>10,446,695</td></tr>
    <tr><td>(</td><td>10,425,221</td></tr>
    <tr><td>;</td><td>7,882,261</td></tr>
    <tr><td>Hex Numbers</td><td>6,261,887</td></tr>
    <tr><td>*</td><td>6,205,697</td></tr>
    <tr><td>.</td><td>5,978,092</td></tr>
    <tr><td>=</td><td>5,841,844</td></tr>
    <tr><td>Strings (Double Quotes - DQ)</td><td>4,336,520</td></tr>
    <tr><td>}</td><td>3,310,463</td></tr>
    <tr><td>{</td><td>3,305,033</td></tr>
    <tr><td>/</td><td>2,939,954</td></tr>
    <tr><td>:</td><td>2,640,872</td></tr>
    <tr><td>-&gt;</td><td>2,425,261</td></tr>
    <tr><td>#</td><td>2,423,779</td></tr>
    <tr><td>[</td><td>2,004,437</td></tr>
    <tr><td>]</td><td>2,002,711</td></tr>
    <tr><td>&lt;</td><td>1,591,276</td></tr>
    <tr><td>Strings (Single Quotes - SQ)</td><td>1,578,686</td></tr>
  </table>
  <p>
    The top 20 tokens, by occurrence in aggregate (across 65,804 files).
  </p>
</div>

<p>
  Table 2 shows the top 20 tokens and their ratios (token/all tokens in a given file) in 16 different file types. Not surprisingly JSON files lead the pack for double quoted strings, curly brackets, colons and commas. Likewise, Clojure leads by having the highest proportion of parentheses. The right arrow <code>-></code> occurred most often in Php, C and Haskell. Finally, square brackets were very prevalent in Objective-C.
</p>

<div class="table table-large table-alternate table-fixed" style="overflow:scroll;">
  <h2>Table 2. Top 20 Tokens (Scroll Right For Full Table)</h2>
  <table style="width:2200px;">
    <tr>
      <th>File Type</th>
      <th># Files</th>
      <th>Numbers</th>
      <th>,</th>
      <th>)</th>
      <th>(</th>
      <th>;</th>
      <th>Hex Numbers</th>
      <th>*</th>
      <th>.</th>
      <th>=</th>
      <th>Strings (DQ)</th>
      <th>}</th>
      <th>{</th>
      <th>/</th>
      <th>:</th>
      <th>-&gt;</th>
      <th>#</th>
      <th>[</th>
      <th>]</th>
      <th>&lt;</th>
      <th>Strings (SQ)</th>
    </tr>
    <tr>
      <td>.php</td><td>10289</td><td>0.0106</td><td>0.0280</td><td>0.0634</td><td>0.0632</td><td>0.0406</td><td>0.0000</td><td>0.0463</td><td>0.0257</td><td>0.0172</td><td>0.0054</td><td>0.0219</td><td>0.0218</td><td>0.0187</td><td>0.0077</td><td class="largest">0.0239</td><td>0.0004</td><td>0.0042</td><td>0.0042</td><td>0.0126</td><td>0.0375</td>
    </tr>
    <tr>
      <td>.json</td><td>1002</td><td>0.0183</td><td class="largest">0.1510</td><td>0.0001</td><td>0.0001</td><td>0.0000</td><td>0</td><td>0.0001</td><td>0.0011</td><td>0.0001</td><td class="largest">0.3575</td><td class="largest">0.0927</td><td class="largest">0.0930</td><td>0.0000</td><td class="largest">0.2163</td><td>0</td><td>0.0001</td><td>0.0179</td><td>0.0179</td><td>0.0001</td><td>0.0001</td>
    </tr>
    <tr>
      <td>.md</td><td>1541</td><td>0.0317</td><td>0.0238</td><td>0.0250</td><td>0.0248</td><td>0.0030</td><td>0.0001</td><td>0.0146</td><td>0.0559</td><td>0.0063</td><td>0.0108</td><td>0.0039</td><td>0.0038</td><td>0.0012</td><td>0.0251</td><td>0.0006</td><td>0.0251</td><td>0.0127</td><td>0.0127</td><td>0.0066</td><td>0.0064</td>
    </tr>
    <tr>
      <td>.hs</td><td>6133</td><td>0.0416</td><td>0.0224</td><td>0.0426</td><td>0.0424</td><td>0.0014</td><td>0.0002</td><td>0.0025</td><td>0.0253</td><td>0.0407</td><td>0.0121</td><td>0.0123</td><td>0.0123</td><td>0.0006</td><td>0.0051</td><td>0.0179</td><td>0.0229</td><td>0.0090</td><td>0.0091</td><td>0.0019</td><td>0.0060</td>
    </tr>
    <tr>
      <td>.html</td><td>1579</td><td>0.0211</td><td>0.0091</td><td>0.0117</td><td>0.0116</td><td>0.0154</td><td>0.0000</td><td>0.0007</td><td>0.0252</td><td>0.0463</td><td>0.0482</td><td>0.0295</td><td>0.0295</td><td>0.0033</td><td>0.0099</td><td>0.0003</td><td>0.0270</td><td>0.0016</td><td>0.0016</td><td>0.1150</td><td>0.0052</td>
    </tr>
    <tr>
      <td>.css</td><td>701</td><td class="largest">0.0811</td><td>0.0212</td><td>0.0083</td><td>0.0083</td><td class="largest">0.0676</td><td>0.0000</td><td>0.0219</td><td>0.0564</td><td>0.0023</td><td>0.0050</td><td>0.0392</td><td>0.0394</td><td>0.0169</td><td>0.0779</td><td>0</td><td>0.0194</td><td>0.0011</td><td>0.0011</td><td>0.0001</td><td>0.0018</td>
    </tr>
    <tr>
      <td>.js</td><td>9089</td><td>0.0290</td><td>0.0681</td><td>0.0646</td><td>0.0639</td><td>0.0436</td><td>0.0005</td><td>0.0075</td><td>0.0574</td><td>0.0239</td><td>0.0328</td><td>0.0226</td><td>0.0220</td><td>0.0043</td><td>0.0203</td><td>0.0000</td><td>0.0004</td><td>0.0086</td><td>0.0086</td><td>0.0013</td><td>0.0251</td>
    </tr>
    <tr>
      <td>.py</td><td>3081</td><td>0.0211</td><td>0.0483</td><td>0.0539</td><td>0.0537</td><td>0.0008</td><td>0.0001</td><td>0.0024</td><td>0.0670</td><td>0.0364</td><td>0.0213</td><td>0.0018</td><td>0.0018</td><td>0.0003</td><td>0.0278</td><td>0.0000</td><td class="largest">0.0294</td><td>0.0092</td><td>0.0093</td><td>0.0008</td><td>0.0376</td>
    </tr>
    <tr>
      <td>.c</td><td>25043</td><td>0.0536</td><td>0.0560</td><td>0.0573</td><td>0.0573</td><td>0.0555</td><td class="largest">0.0077</td><td>0.0469</td><td>0.0248</td><td>0.0276</td><td>0.0110</td><td>0.0156</td><td>0.0155</td><td>0.0174</td><td>0.0050</td><td>0.0194</td><td>0.0120</td><td>0.0053</td><td>0.0053</td><td>0.0078</td><td>0.0017</td>
    </tr>
    <tr>
      <td>.xml</td><td>1788</td><td>0.0127</td><td>0.0055</td><td>0.0022</td><td>0.0022</td><td>0.0026</td><td>0.0000</td><td>0.0005</td><td>0.0146</td><td class="largest">0.0925</td><td>0.0993</td><td>0.0014</td><td>0.0014</td><td class="largest">0.0191</td><td>0.0315</td><td>0.0000</td><td>0.0060</td><td>0.0005</td><td>0.0005</td><td class="largest">0.1242</td><td>0.0006</td>
    </tr>
    <tr>
      <td>.clj</td><td>83</td><td>0.0183</td><td>0.0064</td><td class="largest">0.0946</td><td class="largest">0.0944</td><td>0.0529</td><td>0</td><td>0.0014</td><td>0.0462</td><td>0.0034</td><td>0.0239</td><td>0.0049</td><td>0.0049</td><td>0.0001</td><td>0.0189</td><td>0.0026</td><td>0.0015</td><td>0.0339</td><td>0.0339</td><td>0.0001</td><td>0.0005</td>
    </tr>
    <tr>
      <td>.rb</td><td>8527</td><td>0.0229</td><td>0.0479</td><td>0.0264</td><td>0.0263</td><td>0.0013</td><td>0.0001</td><td>0.0018</td><td>0.0539</td><td>0.0148</td><td>0.0510</td><td>0.0062</td><td>0.0062</td><td>0.0009</td><td>0.0446</td><td>0.0002</td><td>0.0166</td><td>0.0086</td><td>0.0087</td><td>0.0141</td><td class="largest">0.0530</td>
    </tr>
    <tr>
      <td>.java</td><td>12293</td><td>0.0157</td><td>0.0262</td><td>0.0488</td><td>0.0488</td><td>0.0433</td><td>0.0001</td><td class="largest">0.0525</td><td class="largest">0.0930</td><td>0.0104</td><td>0.0118</td><td>0.0186</td><td>0.0185</td><td>0.0137</td><td>0.0032</td><td>0.0000</td><td>0.0009</td><td>0.0018</td><td>0.0018</td><td>0.0050</td><td>0.0005</td>
    </tr>
    <tr>
      <td>.go</td><td>1259</td><td>0.0265</td><td>0.0569</td><td>0.0684</td><td>0.0684</td><td>0.0043</td><td>0.0029</td><td>0.0108</td><td>0.0688</td><td>0.0111</td><td>0.0370</td><td>0.0340</td><td>0.0339</td><td>0.0009</td><td>0.0104</td><td>0.0000</td><td>0.0002</td><td>0.0106</td><td>0.0106</td><td>0.0014</td><td>0.0017</td>
    </tr>
    <tr>
      <td>.lua</td><td>3935</td><td>0.0342</td><td>0.0783</td><td>0.0526</td><td>0.0525</td><td>0.0020</td><td>0.0008</td><td>0.0017</td><td>0.0463</td><td>0.0634</td><td>0.0448</td><td>0.0173</td><td>0.0171</td><td>0.0008</td><td>0.0166</td><td>0.0001</td><td>0.0013</td><td>0.0158</td><td>0.0157</td><td>0.0010</td><td>0.0193</td>
    </tr>
    <tr>
      <td>.m</td><td>742</td><td>0.0333</td><td>0.0261</td><td>0.0530</td><td>0.0530</td><td>0.0580</td><td>0.0001</td><td>0.0201</td><td>0.0327</td><td>0.0246</td><td>0.0181</td><td>0.0190</td><td>0.0190</td><td>0.0049</td><td>0.0353</td><td>0.0003</td><td>0.0120</td><td class="largest">0.0345</td><td class="largest">0.0345</td><td>0.0018</td><td>0.0005</td>
    </tr>
  </table>
  <p>
    The ratio of a specific tokens, relative to all tokens in a file, by file type. Only the top 16 file types are present in this table - there is a very long tail of file types. I restricted this table to file types that are relatively abundant in this dataset.
  </p>
</div>

<h3>ASCII Faces</h3>
<p>
  To examine the discrepancy between left and right parenthesis I created a set of scripts to separate comments from code, in c and JavaScript files. Second, I then analyzed the comments and counted the number of ascii faces that appeared. I focused on 6 different types of smiley faces and I included 1 type of frown (See Table 3 for types of ascii faces and amount found).
</p>
<p>
   While there were more frowns in JavaScript files, the difference wasn&#8217;t statistically significant. Furthermore there was not a statistically significant difference between the total smiley faces between &#8216;.c&#8217; and &#8216;.js&#8217; files. However, there were more smiley faces in files that were in &#8220;JavaScript&#8221; github repos. For instance, Node is a JavaScript repo but includes both JavaScript and c files. This makes sense that the project, with its distinct maintainers, rules and conventions is more important in determining the number of smiley faces.
</p>
<p>
  Eighty percent of c files analyzed were found in the Linux repository, so it made sense to focus on Linux specifically. In Linux c comments I found 631 smiley faces and 73 frowns. In linux the most prevalent smiley faces was `:-)` followed by `:)` (See Table 3.).
</p>
<div class="table">
  <h2> Table 3. Ascii faces</h2>
  <table>
    <tr>
      <th></th>
      <th>Linux c files (20,060)</th>
      <th>c files (24,542)</th>
      <th>JavaScript files (6,743)</th>
    </tr>
    <tr>
      <td>All Smiley Faces</td>
      <td>0.0315 (631)</td>
      <td>0.0577 (1415)</td>
      <td>0.0721 (486)</td>
    </tr>
     <tr>
      <td>Frowns :(</td>
      <td>0.0036 (73)</td>      
      <td>0.0051 (124)</td>
      <td>0.0249 (168)</td>
    </tr>
     <tr>
      <td>:)</td>
      <td>0.0088 (172)</td>
      <td>0.0081 (198)</td>
      <td>0.0027 (18)</td>
    </tr>
     <tr>
      <td>:-)</td>
      <td>0.0088 (176)</td>
      <td>0.0284 (697)</td>
      <td>0.0001 (1)</td>
    </tr>
     <tr>
      <td>:-D</td>
      <td>0.0001 (2)</td>
      <td>0.0001 (3)</td>
      <td>0.0006 (4)</td>
    </tr>
     <tr>
      <td>:p</td>
      <td>0.0051 (102)</td>
      <td>0.0120 (295)</td>
      <td>0.0475 (320)</td>
    </tr>
     <tr>
      <td>;)</td>
      <td>0.0044 (89)</td>
      <td>0.0048 (117)</td>
      <td>0.0212 (143)</td>
    </tr>
     <tr>
      <td>;-)</td>
      <td>0.0044 (90)</td>
      <td>0.0043 (105)</td>
      <td>0.0000 (0)</td>
    </tr>
  </table>
  <p>
    The first value is the number of times the ascii faces appears, relative to other tokens, while the value in brackets is the total number of times that it appears in all files. Linux c files are a subset of the c files.
  </p>
</div>

<h2>Discussion</h2>
<h3>Shortcomings</h3>
<p>
  Despite including 100 different repositories, Linux source files represented 30% of all files in this analysis. Ideally, the number of files from each repository, and language, would be balanced. One approach would be to randomly select a numerically identical subset of files from each language. While this approach might be valid statistically it wouldn&#8217;t produce descriptive statistics on each repository, just a subset of files within each repository. Alternatively Linux could be excluded from the analysis since the number of files it contains is an outlier, relative to the other repositories.
</p>
<p>
  In all files there were 21,474 more right parenthesis than left. Given that c and JavaScript files represent nearly half of all files in this analysis, and they only had 1,901 smiley faces, it&#8217;s unlikely that the other half of the files had a nearly 20,000 smiley faces - or enough to account for the left and right parenthesis. Future analysis could attempt to locate the source for this difference (presumably within comments).
</p>
<h2>Conclusions</h2>
<p>
  It is not surprising that ratios of token types can differ dramatically between different languages, however, I was surprised that several tokens (parenthesis, square &amp; curly brackets) did not occur equally. While smiley faces can account for part of this discrepancy, they most likely do not account for all of it.  
</p>
<p>
  The biggest surprise was that number of smiley faces per file was not statistically different between JavaScript and C. Being low level I presumed that C code would be more serious, with fewer ascii faces. Interestingly, I was wrong and C code has a similar amount of smiley faces relative to JavaScript.
</p>
<p>
  Viewing Table 2 we can start to see some patterns and differences in token ratios that might help to predict a file&#8217;s language. For instance, JSON has very different token ratios than C. In the next article I will explore the power that tokens have in predicting which programming language is being used in a given file.
</p>
<p>
  If you&#8217;re interested in replicating the analysis, or obtaining the dataset, please see the links below:
</p>

<p>
<a class="github" href="https://github.com/liamks/languageStatistics"><span></span>Language Statistics</a>
</p>
<p>
<a class="github" href="https://github.com/liamks/languageStatisticsData"><span></span>Language Statistics Data</a>
</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Understanding AngularJS Directives Part 2: ngView]]></title>
    <link href="http://liamkaufman.com/blog/2013/11/11/understanding-angularjs-directives-part2-ng-view/"/>
    <updated>2013-11-11T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2013/11/11/understanding-angularjs-directives-part2-ng-view</id>
    <content type="html"><![CDATA[<p>
  In a previous article I <a href="blog/2013/05/13/understanding-angularjs-directives-part1-ng-repeat-and-compile/">explored ng-repeat, it&#8217;s implementation, and how to create a custom repeater</a>. In this article I&#8217;ll first delve into the inner workings of ngView and then walk through the creation of an &#8220;ngMultiView&#8221; directive. To get the most out of this article you&#8217;ll need an intermediate understanding of creating directives (via  <a href="blog/2013/05/13/understanding-angularjs-directives-part1-ng-repeat-and-compile/">the previous article on ng-repeat</a> and reading the <a href="http://docs.angularjs.org/guide/directive">the AngularJS directive guide</a>).
</p>

<p>
  Starting with AngualrJS 1.2, the <code>ngView</code> directive, and the <code>$route</code> service were moved into a separate module called <code>ngRoute</code>. As a result, to use routes and <code>ngView</code> your app must explicitly declare it as a dependency. Furthermore, the syntax for the &#8220;otherwise&#8221; statement is slightly different from older versions of AngularJS. Below is a complete example of a tiny AngularJS 1.2 app with two routes and a default:
</p>

<iframe width="100%" height="300" src="http://jsfiddle.net/E259J/11/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<h2>Undocumented features of ngView</h2>
<p>
  In the process of understanding the code behind ngView I came across two undocumented attributes: &#8220;onload&#8221; and &#8220;autoscroll&#8221;. The onload attribute can take any Angular expression and will execute it every time the view changes. Autoscroll uses the <a href="http://docs.angularjs.org/api/ng.$anchorScroll">$autoScroll service</a> and scrolls to a specific element based on the current value of $location.hash(). Finally, near the very end of the directive, after <code>link(currentScope)</code> is called the <code>'$viewContentLoaded'</code> is emitted within the current scope - an event which you can use within your controller. Below is a revised version of the above example that includes the onload attribute.
</p>

<iframe width="100%" height="300" src="http://jsfiddle.net/E259J/12/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<h2>How ngView Works?</h2>

<p>In order to understand ngView, I think it&#8217;s useful to create a simplified version of it. Below is ngViewLite, a version of ngView that does not include scope cleanup or animations, but is otherwise identical to ngView. </p>

<iframe width="100%" height="400" src="http://jsfiddle.net/yr22b/26/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<p>
  First, we bind a function <code>update</code> to the <code>$routeChangeSuccess</code>; when the route changes, update will be called. Right after attaching the function to the event we immediately call <code>update()</code> to load the initial contents into the view.
</p>

<p>
  The update function checks if there is a defined template for the current route, if so it proceeds by calling the linker function, passing in a new scope, and a callback function. The callback function&#8217;s only parameter is the cloned element, whose html will be replaced with the route&#8217;s current template. The cloned element is then appended to div with the ng-view-lite attribute. Afterwhich we remove the previous contents from the view. 
</p>

<p>
  Finally, the template must be compiled (<code>$compile(clone.contents())</code>) and a new scope is injected into it (<code>link(newScope)</code>). In between those two steps we check if the current route has an associated controller: if so we instantiate the controller with the newScope and the local variables from the current route.
</p>

<h2>Making an ngMultiView</h2>

<p>
  <code>ngView</code> works well, but what if you want multiple views to change according the url? According to the documentation </code>ngView</code> can only be used once within an application. To accomplish our <code>ngMultiView</code> we&#8217;ll slightly modify <code>ngView</code> and create an Angular value (<code>MultiViewPaths</code>) to hold the mapping between urls, views, controllers and templates.
</p>

<p>
  In ngMultiView, a parameter is passed into the directive <code>&lt;div ng-multi-view=&quot;secondaryContent&quot;&gt;&lt;/div&gt;</code>, in the directive this attribute will be called &#8220;panel&#8221;. Instead of binding to the <code>'$routeChangeSuccess'</code> event, we&#8217;ll bind to <code>'$locationChangeSuccess'</code> to make our directive completely independent of <code>ngRoute</code>. ngMultiView will work the following way:

</p>
<ol>
  <li>A url change will trigger <code>'$locationChangeSuccess'</code>, which in turn will call <code>update()</code></li>
  <li>Within update: grab the portion of the URL after the hash (in the code this portion is just called url).</li>
  <li>Using the url variable, and the panel, we can lookup the corresponding controller and template from the <code>MultiViewPaths</code> value.</li>
  <li>Once we have the controller and template, ngMultiView works almost identically to <code>ngView</code>.</li>
</ol>
<iframe width="100%" height="300" src="http://jsfiddle.net/WKZ5N/27/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<p>
  Our ngMultiView is very basic, it doesn&#8217;t take into account parameters being passed through urls, nor does it deal with scope cleanup, or animations. If you need more functionality I&#8217;d recommend starting with the <code>$routes</code> service and modifying it to accommodate multiple views.
</p>
<h2>Conclusion</h2>
<p>
  Creating custom directives can be intimidating at first. There&#8217;s a lot of jargon to overcome, and many little nuances. However, once those are overcome it becomes relatively easy to alter existing directives or create your own.
</p>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using AngularJS Promises]]></title>
    <link href="http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises/"/>
    <updated>2013-09-09T00:00:00-04:00</updated>
    <id>http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises</id>
    <content type="html"><![CDATA[<p>
  In my previous article I discussed the <a href="http://liamkaufman.com/blog/2013/08/06/how-angularjs-made-me-a-better-nodejs-developer/">benefits of using dependency injection</a> to make code more testable and modular. In this article I’ll focus on using promises within an AngularJS application. This article assume some prior knowledge of promises (<a href="http://wildermuth.com/2013/8/3/JavaScript_Promises">a good intro on promises</a> and <a href="http://docs.angularjs.org/api/ng.$q">AngularJS&#8217; official documentation</a>).
</p>

<p>
  Promises can be used to unnest asynchronous functions and allows one to chain multiple functions together - increasing readability and making individual functions, within the chain, more reusable.
</p>

<figure class='code'><figcaption><span>Standard Callbacks (no promises)</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">fetchData</span><span class="p">(</span><span class="nx">id</span><span class="p">,</span> <span class="nx">cb</span><span class="p">){</span>
</span><span class='line'>  <span class="nx">getDataFromServer</span><span class="p">(</span><span class="nx">id</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">result</span><span class="p">){</span>
</span><span class='line'>    <span class="k">if</span><span class="p">(</span><span class="nx">err</span><span class="p">){</span>
</span><span class='line'>      <span class="nx">cb</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="kc">null</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span><span class="k">else</span><span class="p">{</span>
</span><span class='line'>      <span class="nx">transformData</span><span class="p">(</span><span class="nx">result</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">transformedResult</span><span class="p">){</span>
</span><span class='line'>        <span class="k">if</span><span class="p">(</span><span class="nx">err</span><span class="p">){</span>
</span><span class='line'>          <span class="nx">cb</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="kc">null</span><span class="p">);</span>
</span><span class='line'>        <span class="p">}</span><span class="k">else</span><span class="p">{</span>
</span><span class='line'>          <span class="nx">saveToIndexDB</span><span class="p">(</span><span class="nx">result</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">savedData</span><span class="p">){</span>
</span><span class='line'>            <span class="nx">cb</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">savedData</span><span class="p">);</span>
</span><span class='line'>          <span class="p">});</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>      <span class="p">});</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

<p>
  Once <code>getDataFromServer()</code>, <code>transformData()</code> and <code>saveToIndexDB()</code> are converted to returning promises we can refactor the above code to:
</p>

<figure class='code'><figcaption><span>With Promises</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='javascript'><span class='line'><span class="kd">function</span> <span class="nx">fetchData</span><span class="p">(</span><span class="nx">id</span><span class="p">){</span>
</span><span class='line'>  <span class="k">return</span> <span class="nx">getDataFromServer</span><span class="p">(</span><span class="nx">id</span><span class="p">)</span>
</span><span class='line'>          <span class="p">.</span><span class="nx">then</span><span class="p">(</span><span class="nx">transformData</span><span class="p">)</span>
</span><span class='line'>          <span class="p">.</span><span class="nx">then</span><span class="p">(</span><span class="nx">saveToIndexDB</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>
  In addition to increasing readability promises can help with error handling, progress updates, and AngularJS templates.
</p>

<h2>Handling Errors</h2>
<p>
  If <code>fetchData</code> is called and an exception is raised in <code>transformData()</code> or <code>saveToIndexDB()</code>, it will trigger the final error callback.
</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">fetchData</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</span><span class='line'>  <span class="p">.</span><span class="nx">then</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">result</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>  <span class="p">},</span> <span class="kd">function</span><span class="p">(</span><span class="nx">error</span><span class="p">){</span>
</span><span class='line'>    <span class="c1">// exceptions in transformData, or saveToIndexDB</span>
</span><span class='line'>    <span class="c1">// will result in this error callback being called.</span>
</span><span class='line'>  <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>

<p>
   Unfortunately, if an exception is raised in <code>getDataFromServer()</code> it will not trigger the final error callback. This happens because <code>transformData()</code> and <code>saveToIndexDB()</code> are called within the context of <code>.then()</code>, which uses try-catch, and automatically calls <code>.reject()</code> on an exception. To bring this behaviour to the first function we can introduce a try-catch block like:
</p>

<figure class='code'><figcaption><span>getDataFromServer()</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>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">getDataFromServer</span><span class="p">(</span><span class="nx">id</span><span class="p">){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">deferred</span> <span class="o">=</span> <span class="nx">$q</span><span class="p">.</span><span class="nx">defer</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">try</span><span class="p">{</span>
</span><span class='line'>    <span class="c1">// asynchronous function, which calls</span>
</span><span class='line'>    <span class="c1">// deferred.resolve() on sucess</span>
</span><span class='line'>  <span class="p">}</span><span class="k">catch</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
</span><span class='line'>    <span class="nx">deferred</span><span class="p">.</span><span class="nx">reject</span><span class="p">(</span><span class="nx">e</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">return</span> <span class="nx">deferred</span><span class="p">.</span><span class="nx">promise</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>
  While adding try-catch made <code>getDataFromServer()</code> less elegant, it makes it more robust and easier to use as the first in a chain of promises.
</p>

<h2>Using Notify for Progress Updates</h2>

<p>
  A promise can only be resolved, or rejected, once. To provide progress updates, which may happen zero or more times, a promise also includes a notify callback (introduced in AngularJS 1.2+). Notify could be used to provide incremental progress updates on a long running asynchronous task. Below is an example of a long running function, <code>processLotsOfData()</code>, that uses <code>notify</code> to provide progress updates.
</p>
 
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">processLotsOfData</span><span class="p">(</span><span class="nx">data</span><span class="p">){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">output</span> <span class="o">=</span> <span class="p">[],</span>
</span><span class='line'>      <span class="nx">deferred</span> <span class="o">=</span> <span class="nx">$q</span><span class="p">.</span><span class="nx">defer</span><span class="p">(),</span>
</span><span class='line'>      <span class="nx">percentComplete</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">for</span><span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">data</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">){</span>
</span><span class='line'>    <span class="nx">output</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nx">processDataItem</span><span class="p">(</span><span class="nx">data</span><span class="p">[</span><span class="nx">i</span><span class="p">]));</span>
</span><span class='line'>    <span class="nx">percentComplete</span> <span class="o">=</span> <span class="p">(</span><span class="nx">i</span><span class="o">+</span><span class="mi">1</span><span class="p">)</span><span class="o">/</span><span class="nx">data</span><span class="p">.</span><span class="nx">length</span> <span class="o">*</span> <span class="mi">100</span><span class="p">;</span>
</span><span class='line'>    <span class="nx">deferred</span><span class="p">.</span><span class="nx">notify</span><span class="p">(</span><span class="nx">percentComplete</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">deferred</span><span class="p">.</span><span class="nx">resolve</span><span class="p">(</span><span class="nx">output</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">return</span> <span class="nx">deferred</span><span class="p">.</span><span class="nx">promise</span><span class="p">;</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="nx">processLotsOfData</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span>
</span><span class='line'>  <span class="p">.</span><span class="nx">then</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">result</span><span class="p">){</span>
</span><span class='line'>    <span class="c1">// success</span>
</span><span class='line'>  <span class="p">},</span> <span class="kd">function</span><span class="p">(</span><span class="nx">error</span><span class="p">){</span>
</span><span class='line'>    <span class="c1">// error</span>
</span><span class='line'>  <span class="p">},</span> <span class="kd">function</span><span class="p">(</span><span class="nx">percentComplete</span><span class="p">){</span>
</span><span class='line'>    <span class="nx">$scope</span><span class="p">.</span><span class="nx">progress</span> <span class="o">=</span> <span class="nx">percentComplete</span><span class="p">;</span>
</span><span class='line'>  <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>

<p>
  Using the notify function, we can make many updates to the $scope&#8217;s progress variable before processLotsOfData is resolved (finished), making notify ideal for progress bars.
</p>

<p>
  Unfortunately, using notify in a chain or promises is cumbersome since calls to notify do not bubble up. Every function in the chain would have to manually bubble up notifications, making code a little more difficult to read.
</p>

<h2>Templates</h2>

<p>
  <span style="text-decoration: line-through;">AngularJS templates understand promises and delays their rendering until they&#8217;re resolved, or rejected</span>. AngularJS templates no longer resolve promises - they must be resolved in the controller
  before they&#8217;re assigned to the scope. For instance let&#8217;s say our template looks like:
</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'>&lt;p>{{bio}}&lt;/p></span></code></pre></td></tr></table></div></figure>

<p>
  We could do the following in our controller:
</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='javascript'><span class='line'><span class="kd">function</span> <span class="nx">getBio</span><span class="p">(){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">deferred</span> <span class="o">=</span> <span class="nx">$q</span><span class="p">.</span><span class="nx">defer</span><span class="p">();</span>
</span><span class='line'>  <span class="c1">// async call, resolved after ajax request completes</span>
</span><span class='line'>  <span class="k">return</span> <span class="nx">deferred</span><span class="p">.</span><span class="nx">promise</span><span class="p">;</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="nx">getBio</span><span class="p">().</span><span class="nx">then</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">bio</span><span class="p">){</span>
</span><span class='line'>  <span class="nx">$scope</span><span class="p">.</span><span class="nx">bio</span> <span class="o">=</span> <span class="nx">bio</span><span class="p">;</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>

<p>
  The view renders normally, and when the promise is resolved AngularJS automatically updates the view to include the value resolved in getBio.
</p>

<h2>Limitations of Promises in AngularJS</h2>
<p>
  When a promise is resolved asynchronously, “in a future turn of the event loop”, the .resolve() function must be wrapped in a promise. In the contrived example below, a user would click a button triggering <code>goodbye()</code>, which should update the <code>$scope</code>&#8217;s greeting attribute. 
</p>


<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">app</span><span class="p">.</span><span class="nx">controller</span><span class="p">(</span><span class="s1">&#39;AppCtrl&#39;</span><span class="p">,</span>
</span><span class='line'><span class="p">[</span>   <span class="s1">&#39;$scope&#39;</span><span class="p">,</span>
</span><span class='line'>    <span class="s1">&#39;$q&#39;</span><span class="p">,</span>
</span><span class='line'>    <span class="kd">function</span> <span class="nx">AppCtrl</span><span class="p">(</span><span class="nx">$scope</span><span class="p">,</span> <span class="nx">$q</span><span class="p">){</span>
</span><span class='line'>      <span class="nx">$scope</span><span class="p">.</span><span class="nx">greeting</span> <span class="o">=</span> <span class="s2">&quot;hello&quot;</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>       <span class="kd">var</span> <span class="nx">updateGreeting</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">message</span><span class="p">){</span>
</span><span class='line'>          <span class="kd">var</span> <span class="nx">deferred</span> <span class="o">=</span> <span class="nx">$q</span><span class="p">.</span><span class="nx">defer</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>          <span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>              <span class="nx">deferred</span><span class="p">.</span><span class="nx">resolve</span><span class="p">(</span><span class="nx">message</span><span class="p">);</span>
</span><span class='line'>          <span class="p">},</span> <span class="mi">5</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>          <span class="k">return</span> <span class="nx">deferred</span><span class="p">.</span><span class="nx">promise</span><span class="p">;</span>
</span><span class='line'>       <span class="p">};</span>
</span><span class='line'>      <span class="nx">$scope</span><span class="p">.</span><span class="nx">goodbye</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>          <span class="nx">$scope</span><span class="p">.</span><span class="nx">greeting</span> <span class="o">=</span> <span class="nx">updateGreeting</span><span class="p">(</span><span class="s1">&#39;goodbye&#39;</span><span class="p">);</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">]);</span>
</span></code></pre></td></tr></table></div></figure>
<p>
  Unfortunately, it doesn&#8217;t work as expected, since the asynchronous event works outside of AngularJS&#8217; event loop. The fix for this (besides using AngularJS&#8217; setTimemout function), is to wrap the deferred&#8217;s resolve in <code>$scope.$apply</code> to trigger the digest cycle and update the <code>$scope</code> accordingly:
</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>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>  <span class="nx">$scope</span><span class="p">.</span><span class="nx">$apply</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>    <span class="nx">deferred</span><span class="p">.</span><span class="nx">resolve</span><span class="p">(</span><span class="nx">message</span><span class="p">);</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'><span class="p">},</span> <span class="mi">5</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>

<p>Jim Hoskins goes into more detail on using <code>$apply</code>: <a href="http://jimhoskins.com/2012/12/17/angularjs-and-apply.html">http://jimhoskins.com/2012/12/17/angularjs-and-apply.html</a></p>

<h2>Conclusions</h2>
<p>
  Using promises is an important part of writing an AngularJS app idiomatically and should help make your code more readable. Understanding their shortcomings, and their strengths make them much easier to work with.
</p>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How AngularJS Made Me a Better Node.js Developer]]></title>
    <link href="http://liamkaufman.com/blog/2013/08/06/how-angularjs-made-me-a-better-nodejs-developer/"/>
    <updated>2013-08-06T00:00:00-04:00</updated>
    <id>http://liamkaufman.com/blog/2013/08/06/how-angularjs-made-me-a-better-nodejs-developer</id>
    <content type="html"><![CDATA[<p>
	Over the past 6 years I’ve used Ruby on Rails, Backbone.js, Node and AngularJS.  RoR reinforced my knowledge of Model View Controller (MVC) while Backbone.js did the same for my knowledge of Publish/Subscribe. Like many who made the switch to Node, my first instinct was to try and apply MVC to my Node.js apps - however, it felt unnatural. Taking a &#8220;class&#8221;-based approach, using CoffeeScript, didn’t feel entirely natural either. 
</p>
<p>
  While I enjoyed developing in JavaScript, I always felt I was missing something - that is until I started developing with AngularJS. AngularJS uses both dependency injection and promises extensively, both of which have greatly improved my code. In this article, I&#8217;ll focus on dependency injection, and discuss promises in my next article.
</p>
<h2>Dependency Injection</h2>
<blockquote cite="http://angularjs.org">
	&#8220;Dependency injection is also a core to AngularJS. This means that any component which does not fit your needs can easily be replaced.&#8221; - angularjs.org
</blockquote>
<p>
	AngularJS doesn’t just pay lip service to dependency injection, it’s a design pattern that it uses extensively, and builders of AngularJS apps use as well. Wikipedia defines dependency injection thusly:
</p>
<blockquote cite="http://angularjs.org">
	&#8220;Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time.&#8221;
</blockquote>
<p>
	So, how has dependency injection (DI) improved my Node.js apps? Traditionally I might write a task queue like so:
</p>

<figure class='code'><figcaption><span>makeThumbnail.js</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='javascript'><span class='line'><span class="kd">var</span> <span class="nx">db</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;./database.js&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">start</span> <span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">input</span><span class="p">){</span>
</span><span class='line'>    <span class="c1">// makeThumbnail</span>
</span><span class='line'>    <span class="c1">// save timestamp</span>
</span><span class='line'>    <span class="nx">db</span><span class="p">.</span><span class="nx">save</span><span class="p">({...});</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>

<figure class='code'><figcaption><span>uploadToS3.js</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='javascript'><span class='line'><span class="kd">var</span> <span class="nx">db</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;./database.js&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">start</span> <span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">input</span><span class="p">){</span>
</span><span class='line'>    <span class="c1">// upload thumb</span>
</span><span class='line'>    <span class="c1">// perhaps save bucket name</span>
</span><span class='line'>    <span class="nx">db</span><span class="p">.</span><span class="nx">save</span><span class="p">({...});</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>
<p>
	Using dependency injection I’d change that to this:
</p>


<figure class='code'><figcaption><span>makeThumbnail.js</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">start</span> <span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">input</span><span class="p">,</span> <span class="nx">db</span><span class="p">){</span>
</span><span class='line'>    <span class="c1">// makeThumbnail</span>
</span><span class='line'>    <span class="c1">// save timestamp</span>
</span><span class='line'>    <span class="nx">db</span><span class="p">.</span><span class="nx">save</span><span class="p">({...});</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>

<figure class='code'><figcaption><span>uploadToS3.js</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">start</span> <span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">input</span><span class="p">,</span> <span class="nx">db</span><span class="p">){</span>
</span><span class='line'>    <span class="c1">// upload thumb</span>
</span><span class='line'>    <span class="c1">// perhaps save bucket name</span>
</span><span class='line'>    <span class="nx">db</span><span class="p">.</span><span class="nx">save</span><span class="p">({...});</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>

<figure class='code'><figcaption><span>taskRunner.js</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">db</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;./database.js&#39;</span><span class="p">),</span>
</span><span class='line'>    <span class="nx">makeThumbnail</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;./tasks/makeThumbnail&#39;</span><span class="p">),</span>
</span><span class='line'>    <span class="nx">uploadToS3</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;./tasks/uploadToS3&#39;</span><span class="p">),</span>
</span><span class='line'>    <span class="nx">taskToRun</span> <span class="o">=</span> <span class="nx">process</span><span class="p">.</span><span class="nx">argv</span><span class="p">[</span><span class="mi">2</span><span class="p">],</span>
</span><span class='line'>    <span class="nx">taskRunner</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="nx">taskRunner</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">task</span><span class="p">){</span>
</span><span class='line'>  <span class="nx">task</span><span class="p">.</span><span class="nx">start</span><span class="p">(</span><span class="nx">process</span><span class="p">.</span><span class="nx">argv</span><span class="p">,</span> <span class="nx">db</span><span class="p">);</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="k">if</span><span class="p">(</span><span class="nx">taskToRun</span> <span class="o">===</span> <span class="s1">&#39;uploadToS3&#39;</span><span class="p">){</span>
</span><span class='line'>  <span class="nx">taskRunner</span><span class="p">(</span><span class="nx">uploadToS3</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span><span class="k">else</span><span class="p">{</span>
</span><span class='line'>  <span class="nx">taskRunner</span><span class="p">(</span><span class="nx">makeThumbnail</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>
	While the DI example above requires more code than the original, it makes testing easier and I&#8217;d argue better. It becomes trivial to test each unit in isolation of other units of code. With the first approach, each unit test would require database calls. With the second approach, we can inject a mock database object like so:
</p>

<figure class='code'><figcaption><span>makeThumbnail.test.js</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">makeThumbnail</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;makeThumbnail&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">describe</span><span class="p">(</span><span class="s1">&#39;Make Thumbnail&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">database</span> <span class="o">=</span> <span class="p">{};</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span><span class="p">(</span><span class="s1">&#39;should make a thumbnail, and call db.save&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">done</span><span class="p">){</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">input</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>      <span class="nx">imageId</span> <span class="o">:</span> <span class="mi">1</span>
</span><span class='line'>    <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">database</span><span class="p">.</span><span class="nx">save</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">obj</span><span class="p">){</span>
</span><span class='line'>      <span class="nx">assert</span><span class="p">.</span><span class="nx">equal</span><span class="p">(</span><span class="nx">obj</span><span class="p">.</span><span class="nx">id</span><span class="p">,</span> <span class="nx">input</span><span class="p">.</span><span class="nx">imageId</span><span class="p">);</span>
</span><span class='line'>      <span class="nx">done</span><span class="p">();</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">makeThumbnail</span><span class="p">(</span><span class="nx">input</span><span class="p">,</span> <span class="nx">database</span><span class="p">);</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>
<p>
	This speeds testing up significantly and ensures that if the unit tests fails it&#8217;s not failing because of issues with the database code. Ultimately, this makes localizing bugs much quicker. In other words we can test just the creation of thumbnails, and not our database (which we&#8217;d do separately).
</p>
<p>
	DI forces one to think more rigorously about how code will be divided into modules, and what modules will be injected into other modules. This requires more diligence upfront, but leads to greater flexibility down the line. For instance, the database object is only being <code>required()</code> and injected in a single spot in the code, making it much easier to swap the database from say MySQL to Postgresql.
</p>

<h2>Why not use use require?</h2>
<p>
  On a post <a href="http://www.alexrothenberg.com/2013/02/11/the-magic-behind-angularjs-dependency-injection.html">detailing the magic behind AngularJS&#8217; DI</a>, tjholowaychuk (of Express.js, Jade and Mocha fame) asks: &#8220;why not just require() what you want? seems odd to me&#8221;?
 </p>
<p>
  <img src="http://liamkaufman.com/images/why-not-use-require.png">
</p>

<p>
  Despite asking 6 months ago, no one has replied, leaving readers pondering why. As the example above shows, requiring dependencies at the top of each file makes mocking more difficult. One could write a wrapper around each dependency, and serve it normally for development/production and serve the mocked version for test ENV, but at that point why not consider DI?
</p>
<h2>Conclusion</h2>
<p>
	As learning new programming languages makes us better developers so does learning new frameworks. Learning a new framework helps us learn, and reinforce our knowledge of design patterns. Qes, on programmers.stackexchange.com, sums up his experiences with DI:
</p>
<a href="http://programmers.stackexchange.com/questions/19203/what-are-the-benefits-of-using-dependency-injection-and-ioc-containers"><img src="http://liamkaufman.com/images/stackexchange_dependency_injection.png" alt="A quote about the importance of dependency injection."></a>

<h2>Extra Reading</h2>
<ol>
  <li><a href="http://en.wikipedia.org/wiki/Dependency_injection">Dependency Injection (Wikipedia)</a></li>
  <li><a href="http://www.alexrothenberg.com/2013/02/11/the-magic-behind-angularjs-dependency-injection.html">How DI In AngularJS Works</a></li>
  <li><a href="http://www.jacopretorius.net/2013/07/angularjs-best-practices.html">AngularJS Best Practices [questions the necessity of DI]</a></li>
</ol>


]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Understanding AngularJS Directives Part 1: ng-repeat and compile]]></title>
    <link href="http://liamkaufman.com/blog/2013/05/13/understanding-angularjs-directives-part1-ng-repeat-and-compile/"/>
    <updated>2013-05-13T00:00:00-04:00</updated>
    <id>http://liamkaufman.com/blog/2013/05/13/understanding-angularjs-directives-part1-ng-repeat-and-compile</id>
    <content type="html"><![CDATA[<p>
  My first impression of Angular.js was one of amazement. A small amount of code could do a lot. My worry with Angular, and other magical frameworks, is that initially you are productive, but eventually you hit a dead end requiring full understanding of how the magic works. In my quest to master Angular.js, I wanted to learn everything about creating custom directives - a goal that I’d hope would ameliorate the learning curve. <a href="http://www.egghead.io/">Egghead.io</a> does a good job exploring basic, and intermediate, examples of custome directives but it still wasn’t clear when to use the compile parameter in a custome directive. 
</p>
<p>
  Miško Hevery, the creator of AngularJS, <a href="http://blog.angularjs.org/2012/11/about-those-directives.html">gave a talk about directives and explained</a> that compile is rarely needed for custom directives, and it is only required for directives like <code>ng-repeat</code> and <code>ng-view</code>. So the next question: how does <code>ng-repeat</code> work?
</p>

<h2>How does ng-repeat work?</h2>
<p>
  In my quest to understand the compile function, I started examining ng-repeat. Reading the source code was difficult until I walked through an example using the Chrome debugger. After stepping through <code>ng-repeat</code> it became clear that most of its 150 lines of code are related to optimizing, error handling and handling objects or arrays. In order to really understand ng-repeat, and specifically compile, I set out to implement my own version of ng-repeat, which I will call <code>lk-repeat</code>, with just the bare minimum of code. When possible I tried to use the same variable names that ng-repeat uses, and I also used their regular expression for matching passed in attributes.
</p>

<h2>Transclusion</h2>
<p>
  Before going further it&#8217;s important to review the transclude option. Transclude has two options: 1) <code>true</code> or 2) <code>'element'</code>. First let&#8217;s examine <code>transclude : true</code>.
</p>


<figure class='code'><figcaption><span>DIV using the person directive</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='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">person</span><span class="nt">&gt;</span>Ted<span class="nt">&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>

<figure class='code'><figcaption><span>Defining the person directive</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='javascript'><span class='line'><span class="nx">app</span><span class="p">.</span><span class="nx">directive</span><span class="p">(</span><span class="s1">&#39;person&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>  <span class="k">return</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">transclude</span> <span class="o">:</span> <span class="kc">true</span><span class="p">,</span>
</span><span class='line'>    <span class="nx">template</span><span class="o">:</span> <span class="s1">&#39;&lt;h1&gt;A Person&lt;/h1&gt;&lt;div ng-transclude&gt;&lt;/div&gt;&#39;</span><span class="p">,</span>
</span><span class='line'>    <span class="nx">link</span> <span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">$scope</span><span class="p">,</span> <span class="nx">$element</span><span class="p">,</span> <span class="nx">$attr</span><span class="p">){</span>
</span><span class='line'>      <span class="c1">// some code</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>

<figure class='code'><figcaption><span>Result</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='html'><span class='line'><span class="nt">&lt;h1&gt;</span>A Person<span class="nt">&lt;/h1&gt;&lt;div</span> <span class="na">ng-transclude</span><span class="nt">&gt;&lt;span</span> <span class="na">class=</span><span class="s">&quot;ng-scope&quot;</span><span class="nt">&gt;</span>Ted<span class="nt">&lt;/span&gt;&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>

<p>
  In the above example <code>transclude : true</code> tells Angular to take the contents of the DOM element, using this directive, and insert them into the person&#8217;s template. To specify where in the template the HTML will be transcluded include <code>ng-transclude</code> in the template. The span, with class <code>ng-scope</code> is inserted by AngularJS.
</p>

<p>
  In contrast to the above example, <code>ng-repeat</code>, does not have a template, and transcludes the element that calls <code>ng-repeat</code>. Hence, <code>ng-repeat</code> calls <code>transclude : 'element'</code>, to denote that the DOM element that called <code>ng-repeat</code> will be used for transclusion.
</p>

<h2>lk-repeat</h2>
<p>Below <code>lk-repeat</code> is used the same way <code>ng-repeat</code> would be used.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;ul&gt;</span>
</span><span class='line'>  <span class="nt">&lt;li</span> <span class="na">lk-repeat=</span><span class="s">&quot;name in names&quot;</span><span class="nt">&gt;</span>{{name}}<span class="nt">&lt;/li&gt;</span>
</span><span class='line'><span class="nt">&lt;/ul&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">app</span> <span class="o">=</span> <span class="nx">angular</span><span class="p">.</span><span class="nx">module</span><span class="p">(</span><span class="s1">&#39;myApp&#39;</span><span class="p">,[]);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">app</span><span class="p">.</span><span class="nx">directive</span><span class="p">(</span><span class="s1">&#39;lkRepeat&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>  <span class="k">return</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">transclude</span> <span class="o">:</span> <span class="s1">&#39;element&#39;</span><span class="p">,</span>
</span><span class='line'>    <span class="nx">compile</span> <span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">attr</span><span class="p">,</span> <span class="nx">linker</span><span class="p">){</span>
</span><span class='line'>      <span class="k">return</span> <span class="kd">function</span><span class="p">(</span><span class="nx">$scope</span><span class="p">,</span> <span class="nx">$element</span><span class="p">,</span> <span class="nx">$attr</span><span class="p">){</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">myLoop</span> <span class="o">=</span> <span class="nx">$attr</span><span class="p">.</span><span class="nx">lkRepeat</span><span class="p">,</span>
</span><span class='line'>            <span class="nx">match</span> <span class="o">=</span> <span class="nx">myLoop</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="sr">/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/</span><span class="p">),</span>
</span><span class='line'>            <span class="nx">indexString</span> <span class="o">=</span> <span class="nx">match</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span>
</span><span class='line'>            <span class="nx">collectionString</span> <span class="o">=</span> <span class="nx">match</span><span class="p">[</span><span class="mi">2</span><span class="p">],</span>
</span><span class='line'>            <span class="nx">parent</span> <span class="o">=</span> <span class="nx">$element</span><span class="p">.</span><span class="nx">parent</span><span class="p">(),</span>
</span><span class='line'>            <span class="nx">elements</span> <span class="o">=</span> <span class="p">[];</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">// $watchCollection is called everytime the collection is modified</span>
</span><span class='line'>        <span class="nx">$scope</span><span class="p">.</span><span class="nx">$watchCollection</span><span class="p">(</span><span class="nx">collectionString</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">collection</span><span class="p">){</span>
</span><span class='line'>          <span class="kd">var</span> <span class="nx">i</span><span class="p">,</span> <span class="nx">block</span><span class="p">,</span> <span class="nx">childScope</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>          <span class="c1">// check if elements have already been rendered</span>
</span><span class='line'>          <span class="k">if</span><span class="p">(</span><span class="nx">elements</span><span class="p">.</span><span class="nx">length</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">){</span>
</span><span class='line'>            <span class="c1">// if so remove them from DOM, and destroy their scope</span>
</span><span class='line'>            <span class="k">for</span> <span class="p">(</span><span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">elements</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>              <span class="nx">elements</span><span class="p">[</span><span class="nx">i</span><span class="p">].</span><span class="nx">el</span><span class="p">.</span><span class="nx">remove</span><span class="p">();</span>
</span><span class='line'>              <span class="nx">elements</span><span class="p">[</span><span class="nx">i</span><span class="p">].</span><span class="nx">scope</span><span class="p">.</span><span class="nx">$destroy</span><span class="p">();</span>
</span><span class='line'>            <span class="p">};</span>
</span><span class='line'>            <span class="nx">elements</span> <span class="o">=</span> <span class="p">[];</span>
</span><span class='line'>          <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>          <span class="k">for</span> <span class="p">(</span><span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">collection</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">// create a new scope for every element in the collection.</span>
</span><span class='line'>            <span class="nx">childScope</span> <span class="o">=</span> <span class="nx">$scope</span><span class="p">.</span><span class="nx">$new</span><span class="p">();</span>
</span><span class='line'>            <span class="c1">// pass the current element of the collection into that scope</span>
</span><span class='line'>            <span class="nx">childScope</span><span class="p">[</span><span class="nx">indexString</span><span class="p">]</span> <span class="o">=</span> <span class="nx">collection</span><span class="p">[</span><span class="nx">i</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>            <span class="nx">linker</span><span class="p">(</span><span class="nx">childScope</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">clone</span><span class="p">){</span>
</span><span class='line'>              <span class="c1">// clone the transcluded element, passing in the new scope.</span>
</span><span class='line'>              <span class="nx">parent</span><span class="p">.</span><span class="nx">append</span><span class="p">(</span><span class="nx">clone</span><span class="p">);</span> <span class="c1">// add to DOM</span>
</span><span class='line'>              <span class="nx">block</span> <span class="o">=</span> <span class="p">{};</span>
</span><span class='line'>              <span class="nx">block</span><span class="p">.</span><span class="nx">el</span> <span class="o">=</span> <span class="nx">clone</span><span class="p">;</span>
</span><span class='line'>              <span class="nx">block</span><span class="p">.</span><span class="nx">scope</span> <span class="o">=</span> <span class="nx">childScope</span><span class="p">;</span>
</span><span class='line'>              <span class="nx">elements</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nx">block</span><span class="p">);</span>
</span><span class='line'>            <span class="p">});</span>
</span><span class='line'>          <span class="p">};</span>
</span><span class='line'>        <span class="p">});</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>
<p>
  Above you&#8217;ll note that I&#8217;m removing all the elements from the DOM, and their scope, every time the collection updates. While this makes the code easier to understand, it is extremely inefficient having to remove everything then add it again. In the real version of <code>ng-repeat</code>, only elements that are removed from the collection, are removed from the DOM. Furthermore, if an item moves within the collection (e.g. 2nd to 4th place) it doesn&#8217;t need a new scope, but it needs to be moved in the DOM. Reading <code>ng-repeat</code>&#8217;s code gives me confidence that the team behind AngularJS has created a good, well tested and efficient framework.
</p>
<p>
  <a href="http://liamkaufman.com/blog/2013/11/11/understanding-angularjs-directives-part2-ng-view/">In part 2 I examine ngView, it&#8217;s implementation, hidden features and creating your own ngMultiView.</a>
</p>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Adding Real-Time To A RESTful Rails App]]></title>
    <link href="http://liamkaufman.com/blog/2013/02/27/adding-real-time-to-a-restful-rails-app/"/>
    <updated>2013-02-27T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2013/02/27/adding-real-time-to-a-restful-rails-app</id>
    <content type="html"><![CDATA[<p>
  After rewriting <a href="http://understoodit.com">Understoodit</a> several times I’ve spent a lot of time thinking about building real-time web applications. While I elected to rewrite 100% of Understoodit in Node, there are many existing Rails and Sinatra applications that can’t be completely rewritten, but could still benefit with the addition of real-time updates. The tutorial below starts with a traditional web-app written in Backbone and Ruby on Rails (RoR). Of course the modifications could easily be applied to any (Backbone|Angular|Ember) and (Rails|Sinatra|Django|Pylons) app.
</p>
<p>
  Between the overview below, and the <a href="https://github.com/liamks/rails-realtime">code on GitHub</a>, you should be able to follow along and, in less than 50 lines of code, add real-time updates to your Rails app.
</p>
<p>
<a class="github" href="https://github.com/liamks/rails-realtime"><span></span>Adding Real-Time on Github</a>
</p>
<h2>Starting Point</h2>
<p>
In a traditional web app if a user creates a new model other users must refresh their page to see that content. Alternatively, you could poll the server every 30 second and refetch all the content. With both approaches you end up fetching all the content, and in the first case the markup as well. 
</p>

<p>
<img class="center" src="http://liamkaufman.com/images/rails-realtime-rest.png" alt="Traditional RESTful Rails app">
</p>

<p>
In Figure 1, User 1 creates a new book, but User 2 will not see that new book unless they refresh their page. 
</p>

<h2>Adding Real-Time With Redis And Socket.IO</h2>
<p>
When User 1 creates a new book, we’d like that new book to be pushed to User 2 in real-time. I’m going to cover one method that requires only a few modifications to your existing app and uses Redis, Node and Socket.IO. 
</p>

<h2>How It Will Work</h2>

<img class="center" src="http://liamkaufman.com/images/rails-realtime-with-rt.png" alt="Traditional RESTful Rails app with Real-Time">
<ol>
  <li>When User 1 creates a new book, an &#8220;after_create&#8221; callback publishes that new book to Redis on the &#8220;rt-change&#8221; channel.</li>
  <li>On the Node server, each client subscribing to &#8220;rt-change&#8221; receives that new book.</li>
  <li>The new book is pushed to the client using Socket.IO.</li>
  <li>Within the browser, Socket.IO receives that new book and &#8220;publishes&#8221; that change to our Backbone.js App.</li>
  <li>The Backbone.js books collection, listening for changes to books, adds the new book to itself.</li>
</ol>

<p>
The advantage of this approach is that it only requires tiny modifications to a Rails&#8217; model, and if your Node server crashes, your application will work as it always has (without real-time). Thus, I’d consider this a real-time enhancement that gracefully degrades to a conventional Rails RESTful web app.
</p>

<h2>Socket.IO Connection</h2>
<p>
  First, ensure that <code>socket.io.js</code> has been added to <code>lib/assets/javascripts</code>, and referenced in app/assets/javascripts/application.js. In the web app create a new module, called realtime, that includes the Socket.IO connection code. When the application initializes it calls <code>app.realtime.connect()</code> to setup the Socket.IO connection.
</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>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nb">window</span><span class="p">.</span><span class="nx">app</span><span class="p">.</span><span class="nx">realtime</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">connect</span> <span class="o">:</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>    <span class="nb">window</span><span class="p">.</span><span class="nx">app</span><span class="p">.</span><span class="nx">socket</span> <span class="o">=</span> <span class="nx">io</span><span class="p">.</span><span class="nx">connect</span><span class="p">(</span><span class="s2">&quot;http://0.0.0.0:5001&quot;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="nb">window</span><span class="p">.</span><span class="nx">app</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s2">&quot;rt-change&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">message</span><span class="p">){</span>
</span><span class='line'>      <span class="c1">// publish the change on the client side, the channel == the resource</span>
</span><span class='line'>      <span class="nb">window</span><span class="p">.</span><span class="nx">app</span><span class="p">.</span><span class="nx">trigger</span><span class="p">(</span><span class="nx">message</span><span class="p">.</span><span class="nx">resource</span><span class="p">,</span> <span class="nx">message</span><span class="p">);</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

<h2>Node Server &amp; Pub/Sub</h2>
<p>
  In the root of the Rails app create a new folder called &#8216;realtime&#8217;, where the Node server will reside. Don&#8217;t forget to create a <code>package.json</code> file and include socket.io, and redis in the dependencies. Finally, remember to run <code>npm install</code>.
</p>

<figure class='code'><figcaption><span>realtime/realtime-server.js</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">io</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;socket.io&#39;</span><span class="p">).</span><span class="nx">listen</span><span class="p">(</span><span class="mi">5001</span><span class="p">),</span>
</span><span class='line'>    <span class="nx">redis</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;redis&#39;</span><span class="p">).</span><span class="nx">createClient</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="nx">redis</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="s1">&#39;rt-change&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">io</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">&#39;connection&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">socket</span><span class="p">){</span>
</span><span class='line'>  <span class="nx">redis</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">&#39;message&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">channel</span><span class="p">,</span> <span class="nx">message</span><span class="p">){</span>
</span><span class='line'>    <span class="nx">socket</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">&#39;rt-change&#39;</span><span class="p">,</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">message</span><span class="p">));</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>

<h2>Rails Models</h2>
<p>
  Assuming you have Redis installed, add redis to your Gemfile. Next, create a file called <code>redis.rb</code> in your initializers with the following content:
</p>
<figure class='code'><figcaption><span>config/initializers/redis.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="c1">#make sure redis has been added to your Gemfile</span>
</span><span class='line'><span class="vg">$redis</span> <span class="o">=</span> <span class="no">Redis</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="ss">:host</span> <span class="o">=&gt;</span> <span class="s1">&#39;localhost&#39;</span><span class="p">,</span> <span class="ss">:port</span><span class="o">=&gt;</span> <span class="mi">6379</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>
<p>
  The Rails app now has access to Redis through the <code>$redis</code> global variable. Below, we publish changes to Redis whenever a model is created, updated or destroyed. Changes are published to &#8220;rt-change&#8221;, which our Node.js connections are listening to (see above).
</p>
<figure class='code'><figcaption><span>app/models/book.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">Book</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
</span><span class='line'>  <span class="n">attr_accessible</span> <span class="ss">:num_pages</span><span class="p">,</span> <span class="ss">:title</span>
</span><span class='line'>  <span class="n">after_create</span> <span class="p">{</span><span class="o">|</span><span class="n">book</span><span class="o">|</span> <span class="n">book</span><span class="o">.</span><span class="n">message</span> <span class="s1">&#39;create&#39;</span> <span class="p">}</span>
</span><span class='line'>  <span class="n">after_update</span> <span class="p">{</span><span class="o">|</span><span class="n">book</span><span class="o">|</span> <span class="n">book</span><span class="o">.</span><span class="n">message</span> <span class="s1">&#39;update&#39;</span> <span class="p">}</span>
</span><span class='line'>  <span class="n">after_destroy</span> <span class="p">{</span><span class="o">|</span><span class="n">book</span><span class="o">|</span> <span class="n">book</span><span class="o">.</span><span class="n">message</span> <span class="s1">&#39;destroy&#39;</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">message</span> <span class="n">action</span>
</span><span class='line'>    <span class="n">msg</span> <span class="o">=</span> <span class="p">{</span> <span class="n">resource</span><span class="p">:</span> <span class="s1">&#39;books&#39;</span><span class="p">,</span>
</span><span class='line'>            <span class="n">action</span><span class="p">:</span> <span class="n">action</span><span class="p">,</span>
</span><span class='line'>            <span class="nb">id</span><span class="p">:</span> <span class="nb">self</span><span class="o">.</span><span class="n">id</span><span class="p">,</span>
</span><span class='line'>            <span class="n">obj</span><span class="p">:</span> <span class="nb">self</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="vg">$redis</span><span class="o">.</span><span class="n">publish</span> <span class="s1">&#39;rt-change&#39;</span><span class="p">,</span> <span class="n">msg</span><span class="o">.</span><span class="n">to_json</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>


<h2>Listen For Changes in The Backbone App</h2>
<p>
  In the Books Collection, we add the code to both listen for &#8216;books&#8217; events and the handler to handle those events. For create, we simply add the new object (obj) to the collection. For update we update the existing model, while for destroy we remove the object from the collection.
</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">app</span><span class="p">.</span><span class="nx">collections</span><span class="p">.</span><span class="nx">Books</span> <span class="o">=</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">Collection</span><span class="p">.</span><span class="nx">extend</span><span class="p">({</span>
</span><span class='line'>  <span class="nx">model</span> <span class="o">:</span> <span class="nx">app</span><span class="p">.</span><span class="nx">models</span><span class="p">.</span><span class="nx">Book</span><span class="p">,</span>
</span><span class='line'>  <span class="nx">url</span> <span class="o">:</span> <span class="s1">&#39;/books&#39;</span><span class="p">,</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">initialize</span><span class="o">:</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>    <span class="nx">app</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">&#39;books&#39;</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">handle_change</span><span class="p">,</span> <span class="k">this</span><span class="p">);</span>
</span><span class='line'>  <span class="p">},</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">handle_change</span> <span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">message</span><span class="p">){</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">model</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">switch</span><span class="p">(</span><span class="nx">message</span><span class="p">.</span><span class="nx">action</span><span class="p">){</span>
</span><span class='line'>      <span class="k">case</span> <span class="s1">&#39;create&#39;</span><span class="o">:</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">add</span><span class="p">(</span><span class="nx">message</span><span class="p">.</span><span class="nx">obj</span><span class="p">);</span>
</span><span class='line'>        <span class="k">break</span><span class="p">;</span>
</span><span class='line'>      <span class="k">case</span> <span class="s1">&#39;update&#39;</span><span class="o">:</span>
</span><span class='line'>        <span class="nx">model</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">message</span><span class="p">.</span><span class="nx">id</span><span class="p">);</span>
</span><span class='line'>        <span class="nx">model</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="nx">message</span><span class="p">.</span><span class="nx">obj</span><span class="p">);</span>
</span><span class='line'>        <span class="k">break</span><span class="p">;</span>
</span><span class='line'>      <span class="k">case</span> <span class="s1">&#39;destroy&#39;</span><span class="o">:</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">remove</span><span class="p">(</span><span class="nx">message</span><span class="p">.</span><span class="nx">obj</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>

<h2>Caveats</h2>
<p>
  In production there are many edge cases to consider. For instance, if someone views your app on their mobile phone and then puts the phone in their pocket, the screen saver goes on and Socket.IO will disconnect. When the user takes the phone out of their pocket, and views the app, Socket.IO will reconnect. However, during the period of disconnection the data in the client-side app may have become out-of-date. An easy fix is just to fetch the data on reconnect. With lots of connections, or lots of data, fetching everything becomes problematic and requires a more clever method for fetching data (e.g. just fetch the new, or changed, data).
</p>
<p>
  Another issue is if two people are editing the same item, and if person 1 clicks save that will replace what person 2 is editing. To solve this you can present person 2 with a message saying that the book they are editing has been updated by someone else and prevent the version of the book they are editing from being replaced. This isn&#8217;t an ideal solution, but would be fine if the chances of two people editing the same model were minimal. 
</p>
<p>
  In the code above there is only one channel &#8216;rt-change&#8217;, meaning every connected client will get every real-time change. You may want to scope your channels by user (e.g. rt-change/[USERID]). Furthermore, you&#8217;d want to create one redis client for every Socket.IO connection (currently there&#8217;s one redis client for all connections). In other words the <code>.createClient()</code>, and <code>redis.subscribe('...')</code>, would have to take place within the Socket.IO &#8216;connection&#8217; callback (after line 6 above).
</p>

<h2>Alternatives To The Above</h2>
<h3>[update July 2014]: Realtime Rails Gem</h3>
<p>
  Mike Atlas created a <a href="http://mikeatlas.github.io/realtime-rails/">realtime gem</a> which does all the above with minimal setup.
</p>

<h3>SockJS</h3>
<p>
  Socket.IO could be swapped for <a href="https://github.com/sockjs/sockjs-client">SockJS</a>, which uses a similar API to websockets. I&#8217;ve heard from several individuals that it&#8217;s significantly more stable than the current version of Socket.IO and it&#8217;s currently <a href="https://github.com/meteor/meteor/tree/master/packages/stream">used by Meteor</a>.
</p>

<h3>Engine.IO</h3>
<p>
  Guillermo Rauch, the creator of Socket.IO, has publically stated that Socket.IO&#8217;s approach of starting with websockets and falling back to polling <a href="http://www.devthought.com/2012/07/07/the-realtime-engine/">creates issues</a>. As result, he&#8217;s been working on Engine.IO, which will power Socket.IO version 1.0, and should provide a much more stable experience. I suspect Socket.IO, v1.0, will be released in the next few months.
</p>

<h3>Rails 4.0</h3>
<p>
  Rails 4.0, <a href="http://weblog.rubyonrails.org/2013/2/25/Rails-4-0-beta1/">which is due to be released soon</a>, will include <a href="http://tenderlovemaking.com/2012/07/30/is-it-live.html">streaming</a>. Using a combination of Rails 4 streaming, and Puma, you could potentially remove Node and Socket.IO, and use Rails for real-time. Of course, you&#8217;d have to take care of some of what Socket.IO does such as reconnects and heart-beats.
</p>

<h3>RabbitMQ/ZeroMQ</h3>
<p>
  Redis&#8217; Pub/Sub functionality could be replaced by either RabbitMQ or ZeroMQ. I ended up using Redis, since I was using it for caching, and it has an extremely simple API for pub/sub. While RabbitMQ and ZeroMQ appear more complex, they do offer many more features for messaging.
</p>

<h3>Commercial Options</h3>
<p>
  If you&#8217;re not keen on tinkering with Node, or waiting for Rails 4, there are commercial options such as <a href="http://pusher.com/">Pusher</a> and <a href="http://www.pubnub.com/">PubNub</a>, that deal with real-time connections for you. While both options can be pricey, especially with many concurrent connections, they do save you the hassle of building the infrastructure yourself.
</p>

<h2>Conclusions</h2>
<p>
  Adding real-time updates to your Ruby on Rails RESTful app has never been easier. Over the next few months Rails 4, or Socket.IO v1.0, will make the process even more painless. As Google&#8217;s services make users more accustomed to real-time updates, it becomes even more important to provide a similar experience in your webapps. 
</p>

<p>
<a class="github" href="https://github.com/liamks/rails-realtime"><span></span>Adding Real-Time on Github</a>
</p>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Three Important Conversion Metrics You Should Watch]]></title>
    <link href="http://liamkaufman.com/blog/2013/02/08/three-important-conversion-metrics-you-should-watch/"/>
    <updated>2013-02-08T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2013/02/08/three-important-conversion-metrics-you-should-watch</id>
    <content type="html"><![CDATA[<p>
You’ve created an <a href="http://liamkaufman.com/blog/2013/01/22/making-software-people-want-before-launching/">app that your beta testers use</a> and <a href="http://liamkaufman.com/blog/2013/01/30/are-you-ready-to-launch/">your launch was a huge success</a>. Every day the number of registered users increases and you feel like you’re making progress and moving closer to your goals. 
</p>
<p>
It would be a mistake to hunker down and focus singularly on hammering out new features. Now that you’ve launched you have significantly more people visiting your homepage, creating accounts and using your app. You have much more data to help you prioritize what to do next. 
</p>
<p>
I’ll focus on three important metrics that are extremely important and especially so after launching. These metrics are all conversion metrics and include 1) vistors creating an account, 2) becoming an active user and 3) becoming a paying user. While there are exceptions, the order is important: a user can’t become an active user without creating an account. Likewise, paying users are most likely active users. 
</p>

<h2>Create An Account</h2>

<p><strong>What percent of visitors create accounts?</strong> There many variables that will influence the percent of visitors that create an account and they include:</p>

<h3>Relevant Keywords</h3> 
<p>Maybe visitors are arriving at your site searching for something else. If that’s the case you might have a high bounce rate (e.g. users coming to your site and immediately leaving). To fix this issue investigate ways to improve your SEO and ensure that your keywords are relevant to your product.</p>

<h3>Clear Selling Point</h3> 
<p>Have you made it as clear as possible why your product is needed? Ask colleagues unfamiliar with your product to evaluate you&#8217;re site&#8217;s copy and it&#8217;s clarity.</p>

<h3>Call-to-Action Button</h3>
<p>Have you made it obvious how they can create an account? To test this you can use a service like Optimizely to A/B test different variants of your front page and your call-to-action button.</p>

<h3>Pricing</h3> 
<p>Maybe your pricing page is too complicated, or your prices are too high, and as a result users don’t even bother creating an account. This is an issue that you should look into before you launch. Ideally you should speak with an appropriate number of potential customers to figure out if your price is within a reasonable range.</p>


<h2>Become An Active User</h2>

<p>
<strong>What percent of users become active users (e.g. use your app every day/week)?</strong> Your definition of an active user is dependent on your service. If you’re creating a new email app, or a social network, an active user might be someone who uses your app multiple times per day. If you&#8217;re creating a tax app, an active user might be someone who uses it once a year for a week. In order to measure active users first you must define who they are (duh!). 
</p>
<p>
<strong>Problem:</strong> users create an account and then never use your app again. It could be that you have a very interesting idea, but your implementation is off. Likewise you could be attracting a lot of curious users that have no intention of actually using your app, but just want to see what the fuss is about.
</p>
<p>
I’d recommend following-up on a user if they haven’t used your app in a week after registering. Ask them why they didn’t end up using it, and what *one* feature they’d need to use it. Your response rate will likely be between 5 - 10% but hopefully that should be enough to pick up trends. If possible I’d automate this step to ensure that emails are sent out consistently and you don’t waste your time sending out copy and pasted emails.
</p>
<p>
<strong>Problem:</strong> they use your app for a couple of weeks and then never use it again. While still bad, at least you have more data to work with. Check your database and determine what parts of your app they were using. For an email app, were they sending emails, but not creating contacts? Maybe creating contacts was too tricky and they gave up and stopped using your app. 
</p>
<p>
Analyze your data carefully and see if you can pick patterns that can point you to areas that need to be improved. 
Alternatively there could be temporal patterns, for instance, people who only use your app once a week quickly stop using it relative to those that use it several times a week. Finding patterns of use and comparing active users to non active users can shed further light on potential problems.
</p>

<h2>Become A Paying User</h2>
<p>
<strong>What percent of your active users become paying users?</strong> Comparing patterns of use between users who&#8217;ve converted, and those who have not, in the same cohort is useful for elucidating causality in conversions.
</p>
<p>
Unlike the previous step you should have much more data to conduct your analysis. More data means that it should be easier to find statistically significant patterns, but it may be more challenging and time consuming to do analysis. I’d recommend generating fewer than five hypotheses before you start your analysis. This will both limit the complexiy of analysis and reduce the <a href="http://en.wikipedia.org/wiki/Multiple_comparisons">multiple comparison problem</a> (e.g. with enough comparisons you’re bound to get significant differences that are due to chance alone).
</p>

<h2>Conclusions</h2>
<p>
Analyzing what your users are doing, why some are creating accounts, why some are becoming paid users and why others are not is extremely important. If you love coding, and adding new features, it can seem like a big time waster, however, doing the above will help you prioritize better.
</p>
<p>
 Although I haven’t tried either myself both Kissmetrics or Google Analytics’s Conversion feature should help you with the above. It’s crucial to be able to quickly determine why some users never become active, or never become paying users. Use hypotheses, data and outcomes to determine how to spend your time efficiently. Time is something you have little of, use it wisely.
</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Are You Ready To Launch?]]></title>
    <link href="http://liamkaufman.com/blog/2013/01/30/are-you-ready-to-launch/"/>
    <updated>2013-01-30T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2013/01/30/are-you-ready-to-launch</id>
    <content type="html"><![CDATA[<p>
  <strong>Last Week</strong>: <a href="http://liamkaufman.com/blog/2013/01/22/making-software-people-want-before-launching/">Before Launching, Build Software People Use</a>
</p>
<p>
You’ve created a product that people want to use, and now you’re eager to launch. From my experiences launching <a href="https://understoodit.com">Understoodit</a>, in May 2012, I’ve compiled a set of steps that helped Understoodit get on several big sites including <a href="http://techcrunch.com/2012/05/02/understoodit-lets-students-voice-their-confusion-without-having-to-raise-their-hands/">TechCrunch</a>, <a href="http://www.thestar.com/news/gta/article/1173277--don-t-get-what-the-prof-s-talking-about-there-s-an-app-for-that">Toronto Star</a>, and <a href="http://betakit.com/2012/05/03/understoodit-helps-confused-students-in-the-classroom">BetaKit</a>. If you have a large budget hiring a PR firm might be your best bet, otherwise the steps below will help you get started.
</p>

<h2>A Unique Angle</h2>
<p>
If you’re going to catch people’s attention in an app saturated environment, it’s important to communicate what&#8217;s unique about your app. If you’ve created a todo app, is it for Doctors, Engineers or does it something truly unique? If you can’t figure out why your product is unique it&#8217;s going to be a tough sell and it will certainly make it more difficult to get the press interested on your launch day. 
</p>
<p>
The unique angle for Understoodit was focusing on its confusion feedback feature (students can click confused, and in real-time the teacher can see what percentage of students are confused). If I had said Understoodit was a &#8220;classroom response system&#8221;, I would have had a much harder time competing for attention.
</p>
<h2>Press Release</h2>
<p>
An important step in preparing for a launch is crafting a press release. If you’ve never written one, or you aren’t a strong writer, I’d recommend hiring someone to write it with you (<a href="http://www.linkedin.com/pub/vicki-so/29/350/903">Vicki So</a> helped me). 
</p>
<p>
My familiarity with Understoodit made it difficult to objectively write about it. When you’re focused on the technical side of your product it can be easy to loose focus on what’s important to prospective users. By asking good questions, Vicki was able to tease out of me what was important about Understoodit and why educators might be interested. She was able to turn a product launch into an interesting story about how I started Understoodit. 
</p>
<p>
Reporters read many press releases each day, make sure yours is interesting, <a href="http://www.markevanstech.com/2013/01/29/why-startups-need-to-be-great-storytellers/">tells a story</a>, and is well crafted.
</p>

<h2>Reporters &amp; Bloggers</h2>
<p>
One of the most important tips Vicki gave me was: send the press release to a specific reporter, not a newspaper or website in general. A reporter who covers education is potentially more interested in Understoodit than the average person handling general enquiries. In preparation for launch I made a long list of reporters that cover education, and on launch day I emailed each of them a quick note with a press release attached. I’d also recommend adding reporters who cover small business and startups to your list, they may also be interested. 
</p>
<p>
In addition to reporters, I contacted a couple local tech bloggers and asked if I could give them a face-to-face demo. This approached allowed me to pitch a reporter at BetaKit, a Toronto-based website that covers startups. They ended up doing an <a href="http://betakit.com/2012/05/03/understoodit-helps-confused-students-in-the-classroom">article about Understoodit</a> a day after the launch.
</p>

<h2>Social Media</h2>
<p>
I’m no social media expert, but I can say it played an important role in the early success of Understoodit. Facebook and Twitter were huge sources of traffic, as were social news sites such as Hacker News. Depending on your product’s niche you might have more luck with other social networks such as Pinterest or Instagram. However, for you to have a big impact on sites like Twitter, or Pinterest, it helps to have a lot of followers. Gaining followers takes time and is something you should consider long before you launch. 
</p>

<h2>Friends &amp; Family</h2>
<p>
I owe a lot of Understoodit’s launch success to friends that not only helped me with the press release, but also tweeted, liked and voted up Understoodit on launch day. Friends and family are also critical in getting you over the trough of despair - so be kind to them!
</p>

<h2>Luck</h2>
<p>
No matter how prepared you are there is a strong component of luck to a successful launch. Was your press release the first that a reporter read, or did they read it after reading 5 others? Was there a major news event on the day of your launch? Did a writer on TechCrunch see your launch on Hacker News? All those things are mostly out of your control but can greatly affect your success. Preparation can mitigate some of those issues. For instance, it’s always a good idea to see if there might be any important news events, or tech announcements, that could overshadow your launch. 
</p>

<h2>Conclusions</h2>
<p>
After following the above actions, mixed with a healthy dose of luck, I was on the front page of Hacker News, and later that day on TechCrunch. Over a 24 hour period Understoodit received hundreds of registrations. Ultimately, that initial burst of excitement made it possible to get an article in the Toronto Star and the Chronicle of Higher Education.
</p>
<p>
<strong>Next Week</strong>: I will cover 3 important metrics that you need watch after launching your product.
</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Before Launching Build Software People Use]]></title>
    <link href="http://liamkaufman.com/blog/2013/01/22/making-software-people-want-before-launching/"/>
    <updated>2013-01-22T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2013/01/22/making-software-people-want-before-launching</id>
    <content type="html"><![CDATA[<p>
You’re a talented developer and have a great idea for a startup. You’ve read <a href="http://theleanstartup.com/"><em>The Lean Startup</em></a>, you’ve attended entrepreneur events, and you read <a href="http://news.ycombinator.com/"><em>Hacker News</em></a>. At this point you’re confident that you’ll be able to build a compelling product while avoiding common startup mistakes. 
</p>
<p>
Unfortunately, that pretty much summed up my (immodest) perception of myself prior to launching <a href="https://understoodit.com">Understoodit.com</a>. 
</p>
<p>
While the May 2012 launch of Understoodit was more successful than I anticipated, there were certainly things I could have placed more focus on prior to launching. Below I’ve informally divided the pre-launch process into 5 stages:  1) finding customers, 2) the one feature, 3) early beta testing, 4) engaged users, and 5) time to launch.
</p>
<h2>Stage 1: Finding Customers</h2>
<p>
It’s an increasingly common sentiment that you should find potential customers before you start building a product. If you have difficulty finding customers at this stage it may not get easier when you’re coding 12 hours a day. In my experience it’s easier to get help from potential customers at this stage since you aren’t necessarily selling anything yet. At this stage you’re simply doing research and building relationships with potential customers. When contacting professors for Understoodit, I found they were happy to give feedback and provide constructive criticism. If  initially I had tried to sell them something, they may not have been so forthcoming with help and criticism. If all goes well, those first few relationships will turn into paying customers, so be kind and accept their feedback without becoming defensive! 
</p>
<h2>Stage 2: The One Feature</h2>
<p>
Assuming you’ve mastered the previous step, getting feedback will be easy. In fact you’ll likely end up with a laundry list of features. Some features are nice to have, while others will be critical. Unfortunately teasing apart the critical features from the nice-to-haves is not always easy [1]. I’d recommend asking potential users: “If we added only one feature, what would be the most important?” This will force your users to prioritize what they think is the most important feature. A single user may not get this right, but the intuition of multiple users should converge on a single feature. That single feature will become your minimum viable product (MVP). Furthermore, if your users thought that feature was very important, it’s likely that others, in the same demographic, will also think it’s important. 
</p>
<h2>Stage 3: Early Beta Testing</h2>
<p>
At this stage you’ve created an MVP, with one critical feature, and you’re eager to start early beta testing. There is a lot of good advice on user testing online, so I’ll focus on one method that I’ll dub &#8220;passive watching&#8221;. Passive watching involves sitting with potential users and passively watching them create an account, use your app, perform various actions, etc. It’s important not to help them at this point. Rather, what you want to do is see where they’re getting stuck, where they’re getting frustrated, and where things are working smoothly. Don’t be defensive if they dislike the user interface, or its flow, just listen at this stage. After testing with 10 - 20 potential users, you’ll get a very good idea of what needs to be improved, removed and what needs to be added. 
</p>
<h2>Stage 4: Engaged Users?</h2>
<p>
During early beta testing you hopefully received a lot of positive feedback. (And thanks to many who gave me feedback, including readers of this blog.) But don’t conflate positive feedback with engagement. <em>Just because a user says your app is great, it doesn’t guarantee that they will actually use it, let alone pay for it</em>. However, if your early beta testers keep using it, and start telling their friends, then that’s a good sign. On the other hand, if they stop using it, it’s critical to find out why they’re not using it. If you can’t engage your early beta testers (that is, users who’ve invested a lot of time already), it will be difficult to engage new users after launch. This stage is important! So don’t fool yourself into thinking you’ve created a great product unless you have engaged users using your app regularly (self awareness and introspection are important attributes for entreprenuers [2]). If your users aren’t engaged you have to decide whether to go back to early beta testing, pivot, or scrap the idea entirely.
</p>
<h2>Stage 5: Time to launch</h2>
<p>
You’ve built a strong MVP that is used regularly by your beta testers. In turn those testers are telling friends and colleagues about your app. You’ve validated both your idea and your execution and it’s time to launch and grow the number of users. 
</p>
<p>
<strong>Next week</strong> I’ll cover some of my experiences that helped get Understoodit featured on <a href="http://techcrunch.com/2012/05/02/understoodit-lets-students-voice-their-confusion-without-having-to-raise-their-hands/">TechCrunch</a>, <a href="http://news.discovery.com/tech/understoodit-app-120514.html">Discovery.com News</a>, <a href="http://chronicle.com/blogs/wiredcampus/app-tries-to-increase-student-participation-by-simplifying-clicker-technology/37855">The Chronicle of Higher Education</a>, and the <a href="http://www.thestar.com/news/gta/article/1173277--don-t-get-what-the-prof-s-talking-about-there-s-an-app-for-that">Toronto Star</a>. Following next week’s article, on &#8220;The Launch,&#8221; I will focus on metrics that will help you decide if your startup is succeeding or floundering.
</p>
<h2>Extra Reading:</h2>
<ol>
<li><a href="http://ryanhoover.me/post/40941425921/tactics-for-better-customer-interviews">Tactics for Better Customer Interviews</a></li>
<li><a href="http://www.nytimes.com/2013/01/20/opinion/sunday/secret-ingredient-for-success.html">Secret Ingredient for Success (The New York Times)</a></li>
</ol>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Why You Should Be Nice To Your Customers]]></title>
    <link href="http://liamkaufman.com/blog/2012/11/21/why-you-should-be-nice-to-your-customers/"/>
    <updated>2012-11-21T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2012/11/21/why-you-should-be-nice-to-your-customers</id>
    <content type="html"><![CDATA[<p>
Being nice to your customers seems like a no brainer. It makes perfect business sense: happy customers are less likely to stop using your service and more likely to refer your service to their friends. However, there is another significant reason that being nice pays off. 
</p>
<p>
Running a startup can be a tough slog. You’re unsure if people like what you&#8217;re building enough for it to be successful. If you get some traction there will be people out there that will belittle your idea, or your execution. With all the unknowns, and the not-always-constructive criticism, it’s incredibly refreshing to interact with a nice customer that loves your product. 
</p>
<p> 
I’ve noticed that the nicer I am to customers the nicer they are back. This virtuous circle means that we get more and more people who are willing to provide thoughtful criticism and who are willing to meet with us and give us feedback. We have one customer that loves <a href="https://understoodit.com">Understoodit</a> so much that he just finished writing a blog post for us (to be posted in the next week). 
</p>
<p>  
After a difficult day in startup land it’s really gratifying to interact with a nice customer. It puts a face to an email address and makes the whole process of building software that much more interesting and fulfilling.
</p>
<p>
Make sure you’re nice to your customers, they may just be nice back. 
</p>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Stripe Would Be Perfect If...]]></title>
    <link href="http://liamkaufman.com/blog/2012/11/09/stripe-would-be-perfect-if/"/>
    <updated>2012-11-09T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2012/11/09/stripe-would-be-perfect-if</id>
    <content type="html"><![CDATA[<p>
I was among many Canadian developers who where happy to hear that Stripe had come to Canada. We were planning on adding subscriptions to <a href="https://understoodit.com">Understoodit.com</a>, so the timing couldn’t have been better. We assumed that it would take a couple of days to integrate Stripe, but it actually took <a href="https://twitter.com/davidmisshula">@davidmisshula</a> and me 7 days. The process gave me some insights that I thought I’d share.
</p>
<p>
I’ve heard that Stripe is significantly easier to integrate than its competitors, however, having never integrated a payment system I have no comparison. Overall I think Stripe is excellent and I’m glad we chose it, however, there are 4 areas, that if improved, would make Stripe perfect: 1) getting started, 2) taxes, 3) invoices and 4) edge cases.
</p>
<h2>Getting Started</h2>
<p>
Having never integrated a payment system into a website I wanted to be as careful as possible. I wanted to make sure that I understood as many details as possible, and had time to carefully map out all the things that needed to be done before pushing it to production. What I would have really liked was a diagram of how Stripe worked. A good diagram is much easier for me to parse, and would have helped me to understand the text documentation much quicker.
</p>
<p>
For instance, below is one possible diagram that would show the potential set of events associated with a new user signing up for a subscription plan.
</p>
<div>
<img src="http://liamkaufman.com/images/Stripe-Diagram.png" alt="A diagram of Stripe Payments">
</div>
<h2>Taxes</h2>
<p style="text-align:center;">
<img src="http://liamkaufman.com/images/stripe-response.png" alt="Stripe response to does it deal with taxes">
</p>
<p>
Understoodit is based in Canada, obligating us to collect taxes from Canadians, but not our international customers. The kicker is that different provinces have different tax rates. In total there are 4 different tax rates and then no taxes for international customers, for a total of 5 different tax levels. We currently have 3 monthly plans, and their 3 yearly equivalents. This means that we had to create (3 + 3) x 5 = 30 plans within Stripe.
</p>
<p>
It would have been significantly easier if Stripe had had a ‘tax’ feature, in the same way they have coupons. If such a feature existed we’d only have had to create 6 plans in Stripe and 4 tax levels. This would result in Stripe invoices including the subtotal, amount of taxes and total (one less thing for us to calculate). While Stripe does a great job of prorating payments, when a user switches from one plan to another, it becomes tricky for us when they switch province. While calculating taxes isn’t that difficult for us to do, it’s just one more thing we have to get right. It’s one more thing we have to calculate when sending an invoice to our customers.
</p>
<h2>Invoices</h2>
<p style="text-align:center;">
  <img src="http://liamkaufman.com/images/37signals-invoice.png" alt="picture of a 37 signals invoice">
</p>
<p>
Every online subscription that I currently have sends me a simple invoice at the end of each billing period. Some have .pdfs attached that I can easily send to an accountant. Additionally, those services include admin panels that list all the past invoices and those can easily be downloaded as pdfs. 
</p>
<p>
It would be amazing if Stripe handled 1) emailing invoices and 2) creating a .pdfs of each invoice. Developers could provide simple HTML templates for email and pdf invoices and Stripe would fill in the blanks and send the invoice at the correct time, to the correct user. I suspect people would be willing to pay extra for this feature.
</p>
<h2>Edge Cases</h2>
<p>
Like any feature, there are multiple edge cases to a payment system. For instance here are a few that we dealt with:
</p>
<ul>
  <li>Upgrade plan, and simultaneously change provinces (e.g. tax rate)</li>
  <li>Downgrade plan and simultaneously change provinces (e.g tax rate)</li>
  <li>Change credit card info, but not billing address</li>
  <li>Change plan, but keep credit card and billing info the same</li>
</ul>

<p>
Stripe employees can no doubt enumerate many more edge cases than someone adding Stripe for the first time. It would be helpful if they provided a checklist of edge cases for developers. The checklist could also include common security concerns that developers should understand before rolling payments out.
</p>
<h2>Conclusions</h2>
<p>
With all the hype on Hacker News, I had this vision of Stripe being magically easy to integrate. While it wasn’t rocket science it was certainly more effort than I envisioned. The whole process was made significantly more difficult by having to handle taxes. 
</p>
<p>
I wonder if there would be value in Stripe conducting the following usability experiment. Get a dozen computer science and engineering undergrads and ask them each to integrate Stripe into an existing website. Stripe employees would sit with them and monitor their progress (or lack of), but provide no help. I suspect that they’d find some surprises in how novices approach Stripe integration. The information gained in such an experiment could help them create better documentation, reduce development burden and ultimately create a more perfect Stripe.
</p>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Common JavaScript Errors]]></title>
    <link href="http://liamkaufman.com/blog/2012/09/09/common-javascript-errors/"/>
    <updated>2012-09-09T00:00:00-04:00</updated>
    <id>http://liamkaufman.com/blog/2012/09/09/common-javascript-errors</id>
    <content type="html"><![CDATA[<p>
 With the rise of thick client-side applications, and Node.js, JavaScript has become an increasingly important programming language. Despite its simplicity, JavaScript presents some difficulties for those new to the language. I thought it would be useful to outline several JavaScript errors that I commonly made when I was learning the language.
</p>

<h2>Scope: this, that and window</h2>
<p>
  Like many programming languages JavaScript provides internal access to objects using the keyword <code>this</code>. Unfortunately, what <code>this</code> refers to differs depending on what called the function containing <code>this</code>. A common example, shown below, is what happens when <code>setTimeout</code> is called. 
</p>
<p>
  In the example below a Dog object is created, with a bark function. The Dog ralph is instantiated with the name &#8216;Ralph&#8217; and when <code>ralph.bark()</code> is called, &#8220;Ralph&#8221; is printed to the console.
</p>
<p>
   What becomes confusing is what happens when <code>setTimeout</code> is called with the parameters <code>ralph.bark</code> and 500. After 500 milliseconds <code>ralph.bark</code> is called, however, nothing is printed to the console.
</p>

<figure class='code'><figcaption><span>The this problem</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">Dog</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span> <span class="nx">name</span> <span class="p">){</span>
</span><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">name</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="nx">Dog</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">bark</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span> <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">ralph</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Dog</span><span class="p">(</span><span class="s1">&#39;Ralph&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">ralph</span><span class="p">.</span><span class="nx">bark</span><span class="p">()</span>
</span><span class='line'><span class="c1">// Ralph is printed to the console</span>
</span><span class='line'>
</span><span class='line'><span class="nx">setTimeout</span><span class="p">(</span> <span class="nx">ralph</span><span class="p">.</span><span class="nx">bark</span> <span class="p">,</span> <span class="mi">500</span> <span class="p">);</span>
</span><span class='line'><span class="c1">// nothing is printed to the console</span>
</span></code></pre></td></tr></table></div></figure>

<p>
  Mozilla Developer Network refers to the problem above as <a href="https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout">&#8216;The &#8221;<code>this</code>&#8221; problem&#8217;</a>. What happens is <code>this</code> within <code>bark()</code> refers to the browser&#8217;s <code>window</code> variable when <code>bark()</code> is called from setTimeout.
</p>

<h3>Avoiding the <code>this</code> problem.</h3>
<figure class='code'><figcaption><span>Solutions to the this problem.</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='javascript'><span class='line'><span class="c1">// Works in JavaScript 1.8.5</span>
</span><span class='line'><span class="nx">setTimeout</span><span class="p">(</span> <span class="nx">ralph</span><span class="p">.</span><span class="nx">bark</span><span class="p">.</span><span class="nx">bind</span><span class="p">(</span><span class="nx">ralph</span><span class="p">),</span> <span class="mi">500</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// using jQuery</span>
</span><span class='line'><span class="nx">setTimeout</span><span class="p">(</span> <span class="nx">$</span><span class="p">.</span><span class="nx">proxy</span><span class="p">(</span> <span class="nx">ralph</span><span class="p">.</span><span class="nx">bark</span><span class="p">,</span> <span class="nx">ralph</span> <span class="p">),</span> <span class="mi">500</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// using undescore.js</span>
</span><span class='line'><span class="nx">setTimeout</span><span class="p">(</span> <span class="nx">_</span><span class="p">.</span><span class="nx">bind</span><span class="p">(</span> <span class="nx">ralph</span><span class="p">.</span><span class="nx">bark</span><span class="p">,</span> <span class="nx">ralph</span> <span class="p">),</span> <span class="mi">500</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// using an anonymous function</span>
</span><span class='line'><span class="nx">setTimeout</span><span class="p">(</span> <span class="kd">function</span><span class="p">(){</span> <span class="nx">ralph</span><span class="p">.</span><span class="nx">bark</span><span class="p">();</span> <span class="p">},</span> <span class="mi">500</span> <span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>
<p>In each of the above the bind, or proxy functions explicity ensure that <code>this</code> within <code>ralph.bark</code> refers to ralph and not <code>window</code>. In the final example an anonymous function is called and provides another way of fixing the <code>this</code> problem.</p>

<h2>Callbacks in Loops</h2>
<p>When I launched <a href="understoodit.com">Understoodit.com</a> in May I included a waitlist for interested users to signup. I was planning on inviting a few dozen users a day, however, due to a deluge of emails sending out invites was delayed by a week or two. 
</p>
<p>
To send the invites out, I went to Understoodit&#8217;s admin panel and seleted 40 people on the waiting list and clicked invite. A few days later I noticed that only a few individuals had accepted the invite. I looked at Postmark&#8217;s logs and noticed that invites were only sent to 5 individuals. What&#8217;s more those 5 individuals had received anywhere from 5 - 15 emails each. Meanwhile, the other 35 invitees had received no emails. The bug: I had a callback in a loop that iterated over all the selected invities and 1) called databaseModule.addInvitedUser, which created an invite token and added that invite to the database and 2) sent an email with the newly created token. Below is a simplification of the code, with error handling removed.</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>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">sendInviteEmails</span><span class="p">(</span> <span class="nx">emails</span> <span class="p">){</span>
</span><span class='line'>  <span class="k">for</span><span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">emails</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span> <span class="p">){</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">databaseModule</span><span class="p">.</span><span class="nx">addInvitedUser</span><span class="p">(</span> <span class="nx">emails</span><span class="p">[</span><span class="nx">i</span><span class="p">],</span> <span class="kd">function</span><span class="p">(</span> <span class="nx">error</span><span class="p">,</span> <span class="nx">token</span> <span class="p">){</span>
</span><span class='line'>
</span><span class='line'>      <span class="nx">emailModule</span><span class="p">.</span><span class="nx">sendInvite</span><span class="p">(</span> <span class="nx">emails</span><span class="p">[</span><span class="nx">i</span><span class="p">],</span> <span class="nx">token</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

<p>
  What went wrong was that the anonymous function <a href="http://stackoverflow.com/a/3023979/146099">&#8220;captures the variable i, not its value&#8221;</a>.  The value of <code>i</code> is dependent on when the anonymous function is called, which varries depending on how long it takes to add the invited user to the database.
</p>
<p>
  The solution I used was to wrap the anonymous function with an <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">immediately invoked function expression</a> (IIFE). The IIFE &#8220;locks&#8221; in the value of <code>i</code> ensuring that <code>emailModule.sendInvite()</code> refers to a different value of i on each IIFE call. Alternatively, one could create a second function outside of the loop and then call that (see option 2), a solution that would likely be easier to read. 
</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// option 1</span>
</span><span class='line'><span class="kd">function</span> <span class="nx">sendInviteEmails</span><span class="p">(</span> <span class="nx">emails</span> <span class="p">){</span>
</span><span class='line'>  <span class="k">for</span><span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">emails</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span> <span class="p">){</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">email</span><span class="p">){</span>
</span><span class='line'>      <span class="nx">databaseModule</span><span class="p">.</span><span class="nx">addInvitedUser</span><span class="p">(</span> <span class="nx">email</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span> <span class="nx">error</span><span class="p">,</span> <span class="nx">token</span> <span class="p">){</span>
</span><span class='line'>        <span class="nx">emailModule</span><span class="p">.</span><span class="nx">sendInvite</span><span class="p">(</span> <span class="nx">email</span><span class="p">,</span> <span class="nx">token</span> <span class="p">);</span>
</span><span class='line'>      <span class="p">});</span>
</span><span class='line'>    <span class="p">})(</span> <span class="nx">emails</span><span class="p">[</span><span class="nx">i</span><span class="p">]</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// option 2</span>
</span><span class='line'><span class="kd">function</span> <span class="nx">sendOneInviteEmail</span><span class="p">(</span> <span class="nx">email</span> <span class="p">){</span>
</span><span class='line'>  <span class="nx">databaseModule</span><span class="p">.</span><span class="nx">addInvitedUser</span><span class="p">(</span> <span class="nx">email</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span> <span class="nx">error</span><span class="p">,</span> <span class="nx">token</span> <span class="p">){</span>
</span><span class='line'>    <span class="nx">emailModule</span><span class="p">.</span><span class="nx">sendInvite</span><span class="p">(</span> <span class="nx">email</span><span class="p">,</span> <span class="nx">token</span> <span class="p">);</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">sendManyInviteEmails</span><span class="p">(</span> <span class="nx">emails</span> <span class="p">){</span>
</span><span class='line'>  <span class="k">for</span><span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">emails</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span> <span class="p">){</span>
</span><span class='line'>    <span class="nx">sendOneInviteEmail</span><span class="p">(</span> <span class="nx">emails</span><span class="p">[</span><span class="nx">i</span><span class="p">]</span> <span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

<p>
  The above quirk seems similar to a fairly common JavaScript interview question that takes the form of <a href="http://tobyho.com/2011/11/02/callbacks-in-loops/">adding event listeners to an array of links</a>.
</p>


<h2>Global Variables</h2>
<p>
  The problems with global variables have been discussed many times before. Suffice it to say that you should avoid them by using <code>var</code> (e.g. <code>var x = 0;</code> vs </code>x = 0;</code>) when first declearing a variable. If you have a variable that has unaccounted for properties or values, there&#8217;s a chance that a global variable could be to blame.
</p>
<p>
  I&#8217;d highly recommend defining all your variables at the top of the function to make it as clear as possible when a var is missing. Furthermore I&#8217;d recommend using <a href="http://www.jshint.com/">JSHint</a> which can warn you of global variables.
</p>

<h2>Values in HTML forms</h2>

<figure class='code'><figcaption><span>A drop down menu</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='html'><span class='line'><span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&quot;order-sizes&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>  <span class="nt">&lt;option</span> <span class="na">value=</span><span class="s">&quot;1&quot;</span><span class="nt">&gt;</span>Small<span class="nt">&lt;/option&gt;</span>
</span><span class='line'>  <span class="nt">&lt;option</span> <span class="na">value=</span><span class="s">&quot;2&quot;</span><span class="nt">&gt;</span>Medium<span class="nt">&lt;/option&gt;</span>
</span><span class='line'>  <span class="nt">&lt;option</span> <span class="na">value=</span><span class="s">&quot;3&quot;</span><span class="nt">&gt;</span>Large<span class="nt">&lt;/option&gt;</span>
</span><span class='line'><span class="nt">&lt;/select&gt;</span>
</span></code></pre></td></tr></table></div></figure>

<p>When it comes time to get the form&#8217;s values, and use them within an application, I usually do something like: </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>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">orderSize</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#order-sizes option:selected&#39;</span><span class="p">).</span><span class="nx">val</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="k">if</span><span class="p">(</span> <span class="nx">orderSize</span> <span class="o">===</span> <span class="mi">1</span> <span class="p">){</span>
</span><span class='line'>  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;Thanks for ordering a small!&#39;</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

<p>Unfortunately the value that jQuery returns is a <code>String</code>, and comparing it to 1, a <code>Number</code> returns false. Here are several solutions to this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="k">if</span><span class="p">(</span> <span class="nb">Number</span><span class="p">(</span> <span class="nx">orderSize</span> <span class="p">)</span> <span class="o">===</span> <span class="mi">1</span> <span class="p">){</span> <span class="p">...</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">if</span><span class="p">(</span> <span class="nb">parseInt</span><span class="p">(</span> <span class="nx">orderSize</span> <span class="p">)</span> <span class="o">===</span> <span class="mi">1</span> <span class="p">){</span> <span class="p">...</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">if</span><span class="p">(</span> <span class="nx">orderSize</span> <span class="o">==</span> <span class="mi">1</span> <span class="p">){</span> <span class="p">...</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// last solution</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">orderSize</span> <span class="o">=</span> <span class="nb">Number</span><span class="p">(</span> <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#order-sizes option:selected&#39;</span><span class="p">).</span><span class="nx">val</span><span class="p">()</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="k">if</span><span class="p">(</span> <span class="nx">orderSize</span> <span class="o">===</span> <span class="mi">1</span> <span class="p">){</span> <span class="p">...</span> <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

<p>
  In the first two examples orderSize is explicitly converted to a <code>Number</code> using the <code>Number</code> constructor and the global <code>parseInt</code> function. In the third example the double equals coerces orderSize to a <code>Number</code> before comparing to 1 (<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators?redirectlocale=en-US&redirectslug=Core_JavaScript_1.5_Reference%2FOperators%2FComparison_Operators">MDN on comparison operators</a>). However, I&#8217;d recommend going with the last approach, which allows you to use orderSize as a <code>Number</code> in multiple spots without having to repeatedly caste to a number. If you don&#8217;t like the last approach I&#8217;d recommend the first or second approach, since it seems to be generally preferred to use the strict equal (tripple equal signs) and not to use the double equal sign.
</p>

<h2>Conclusions</h2>
<p>
  Many of the above errors can be avoided by following JavaScript style guides (<a href="http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml">Google JavaScript Style Guide</a>, <a href="http://addyosmani.com/blog/javascript-style-guides-and-beautifiers/">Addy Osmani on Style Guides</a>). A sign of how tricky JavaScript is comes from <a href="https://github.com/styleguide/javascript">Github&#8217;s JavaScript Style guide</a> that goes as far to recommend avoiding JavaScript altogether and using CoffeeScript - a suggestion a few would disagree with!
</p>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Redis and Relational Data]]></title>
    <link href="http://liamkaufman.com/blog/2012/06/04/redis-and-relational-data/"/>
    <updated>2012-06-04T00:00:00-04:00</updated>
    <id>http://liamkaufman.com/blog/2012/06/04/redis-and-relational-data</id>
    <content type="html"><![CDATA[<p>
  <strong>UPDATE:</strong> Based on the feedback in the comments (Phineas), I&#8217;ve added an index to the comments table and updated the results.
</p>
<p>
  Using the right tool for the job is a basic tenant amongst programmers. However, with all the currently available database options it&#8217;s increasingly difficult to figure out what the right tool is. Sometime it&#8217;s nice to have a very simple tool that can be used for many different tasks: Redis. Over the last 4 months I&#8217;ve been using Redis heavily and I&#8217;ve even started to use it for relational data. I&#8217;ve been curious to find out the performance differences between Redis and PostgreSQL. Below I&#8217;ll provide an example of storing a simple relational dataset in Redis, and I&#8217;ll look at the performance differences between Redis and PostgreSQL.
</p>

<h2>Why use Redis for Relational data?</h2>
<p>
  I find Redis appealing because it&#8217;s the simplest database that I have ever used (relative to: MySQL, PostgreSQL, Riak &amp; Mongo). The documentation includes the time complexity of each command, and the documentation provides an interactive console to experiment with a given command. There&#8217;s also a certain appeal to using a single database instead of 2 or 3: 
  <ol>
    <li>It&#8217;s much quicker to master 1 database than 2.</li>
    <li>Two different databases means twice the updates, bugs and crashes.</li>
  </ol>
</p>

<p>
  I&#8217;ll outline a few ways Redis can be used to store relational data and the performance differences between redis and PostgreSQL. All the examples and performance tests were done using Node.js.
</p>

<h2>Storing Relational Data in Redis</h2>

<p>
  Redis values can be 1 of 5 different datatypes: strings, hashes, lists, sets and sorted sets. Each row in a relational database can be represented using a hash, and a list, set or sorted set can be used to represent a table. The datatype that&#8217;s used to represent the table is dependent on how the data needs to be retrieved.
</p>

<p>
  For example, let&#8217;s say we&#8217;re storing blog posts. In Redis, each post will be stored in its own hash, with its key corresponding to the post&#8217;s url:
</p>

<figure class='code'><figcaption><span>A Post</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="s1">&#39;a-post-about-databases&#39;</span> <span class="o">:</span>
</span><span class='line'>  <span class="p">{</span> <span class="nx">title</span> <span class="o">:</span> <span class="s1">&#39;A post about databases&#39;</span><span class="p">,</span> <span class="nx">body</span> <span class="o">:</span> <span class="s1">&#39;...&#39;</span><span class="p">,</span> <span class="nx">createdAt</span> <span class="o">:</span> <span class="mi">1338751532301</span><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

<p>
  Retrieving a single post using the url becomes O(N), where N is the size of the hash (post). Since the number of keys in a post is constant, retrieving that post becomes O(1). However, if we wanted to get all the posts, or a subset of them, it becomes useful to also store the keys in a sorted set (e.g. the &#8220;table&#8221;). Using a sorted set means that posts can be stored by their createdAt date and it allows us to retrieve all the posts, or a subset of them (useful for pagination).
</p>


<figure class='code'><figcaption><span>Retrieving a subset of all posts</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='javascript'><span class='line'><span class="nx">redis</span><span class="p">.</span><span class="nx">zrange</span><span class="p">(</span><span class="s1">&#39;posts&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">error</span><span class="p">,</span> <span class="nx">posts</span><span class="p">){</span>
</span><span class='line'>  <span class="c1">//return the keys (urls) associated with the first 11 posts</span>
</span><span class='line'><span class="p">})</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">startDate</span> <span class="o">=</span> <span class="p">(</span><span class="k">new</span> <span class="nb">Date</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">)).</span><span class="nx">getTime</span><span class="p">()</span> <span class="p">;</span> <span class="c1">// June 1st</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">endDate</span> <span class="o">=</span> <span class="p">(</span><span class="k">new</span> <span class="nb">Date</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">30</span><span class="p">)).</span><span class="nx">getTime</span><span class="p">();</span> <span class="c1">// June 30th</span>
</span><span class='line'><span class="nx">redis</span><span class="p">.</span><span class="nx">zrangebyscore</span><span class="p">(</span><span class="s1">&#39;posts&#39;</span><span class="p">,</span> <span class="nx">startDate</span><span class="p">,</span> <span class="nx">endDate</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">posts</span><span class="p">){</span>
</span><span class='line'>  <span class="c1">//returns the keys (urls) associated with all the posts from June 2012</span>
</span><span class='line'><span class="p">})</span>
</span></code></pre></td></tr></table></div></figure>

<p>
  The above example is relatively straight forward, but what about storing the post&#8217;s comments? For every post we create a new sorted set called: &#8216;comments-KEYofPOST&#8217;. The comments are sorted by their creation time. To get a post, and its comments, we could do the following:
</p>

<figure class='code'><figcaption><span>Storing a post&#8217;s comments</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">postURL</span> <span class="o">=</span> <span class="s1">&#39;a-post-about-databases&#39;</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">multi</span> <span class="o">=</span> <span class="nx">redis</span><span class="p">.</span><span class="nx">multi</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// queue up the queries</span>
</span><span class='line'><span class="nx">multi</span><span class="p">.</span><span class="nx">hgetall</span><span class="p">(</span><span class="nx">postURL</span><span class="p">);</span>
</span><span class='line'><span class="nx">multi</span><span class="p">.</span><span class="nx">zrange</span><span class="p">(</span><span class="s1">&#39;comments-&#39;</span> <span class="o">+</span> <span class="nx">postURL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// execute the queries atomically</span>
</span><span class='line'><span class="nx">multi</span><span class="p">.</span><span class="nx">exec</span><span class="p">(</span> <span class="kd">function</span><span class="p">(</span><span class="nx">error</span><span class="p">,</span> <span class="nx">results</span><span class="p">){</span>
</span><span class='line'>  <span class="cm">/*</span>
</span><span class='line'><span class="cm">  results[0] will contain the post</span>
</span><span class='line'><span class="cm">  results[1] will contain an array with all the comments</span>
</span><span class='line'><span class="cm"> */</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>

<h2>Redis vs. PostgreSQL Performance</h2>

<p>
  In SQL you might do 1 query to get the post and another to get the comments, or use a join to get the post and the comments in one query. With the approach above, using Redis, 2 queries are atomically executed, using the multi and exec commands. Both in PostgreSQL, and Redis, a single request is sent the database to retrieve 1 post and its 10 comments.
</p>

<p>
  To test the the performance I created a dataset that includes 10,000 &#8216;blog posts&#8217;, with each post having 10 comments (100,000 comments in total). All tests were run on a 2011 Macbook Pro (2.3 GHz i7, 8GB RAM). To test PostgreSQL, I sequentially fetched each post and used a join to retrieve its comments (10,000 separate queries). The test was repeated six times to produce an average time and was done for both PostgreSQL and Redis.
</p>

<div class="table">
  <h2>Redis &amp; PostgreSQL Performance</h2>
  <table>
    <tr>
      <th></th>
      <th>Average Time (Seconds)</th>
      <th>Query (Milliseconds)</th>
    </tr>

    <tr>
      <td>psql</td>
      <td>138.34</td>
      <td>13.8</td>
    </tr>

    <tr>
      <td>psql (Native Bindings - NB)</td>
      <td>125.95</td>
      <td>12.6</td>
    </tr>

    <tr>
      <td>psql (NB + Index)</td>
      <td>2.72</td>
      <td>0.27</td>
    </tr>

    <tr>
      <td>Redis (Hires)</td>
      <td>0.76</td>
      <td>0.067</td>
    </tr>

  </table>
</div>

<p>
  Using PostgreSQL, it took an average of 138.34 seconds to execute all 10,000 queries, or 13.8 milliseconds/query. Using the native bindings, that come with the psql node module, yielded an improvement and was associated with 12.6 milliseconds/query. When an index was added to comments (post_id), the time dropped to 2.72 seconds, or 0.27 milliseconds for a post and its 10 comments. In contrast, Redis can retrieve a post and its comments in 0.067 milliseconds. Of course the above is akin to comparing apples to oranges, but it still provides a glimpse into the performance differences between Redis and PostgreSQL.
</p>
<p>
  While Redis is in memory and should be fast, PostgreSQL uses caching algorithms (<a href="http://archives.postgresql.org/pgsql-hackers/2007-11/msg00562.php">LRU</a>) to keep its contents in memory. Of course, keeping everything in memory (Redis) will most likely be faster than using LRU.
</p>

<h2>Caveats to using Redis for Relational Data</h2>

<p>
  The single biggest caveat to using Redis, is that it is entirely in memory. If your relational dataset is 2.5GB (not that large), you&#8217;ll need a $160/month Linode (4GB RAM) to keep it in Redis. In contrast, a $20/month Linode (512MB RAM) has 20GB of disk space and could easily hold that same dataset using PostgreSQL. This tradeoff becomes even more of an issue as your dataset become larger than 4GB. 
</p>

<p>
  The above example only represents a very simple relationship between two pieces of data (posts and comments), mapping a many-to-many relationship in Redis would take a little more imagination. 
</p>

<h2>Conclusions</h2>
<p>
  Before storing all your app&#8217;s data in Redis it&#8217;s advisable to estimate how large your dataset will be in a year, or two, and how much much RAM will be required to use Redis. If your dataset will be greater than 4GB in a year, and money is a constraint, it probably makes sense to put all, or a portion of the data, in PostgreSQL, or use an alternative noSQL solution (e.g. Riak or Mongo).
</p>

<p>
<a class="github" href="https://github.com/liamks/Redis-and-Relational-Data"><span></span>Code on Github</a>
</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Adding Authentication, Waiting Lists and Sign Ups to an Express App Using Drawbridge.js and Redis]]></title>
    <link href="http://liamkaufman.com/blog/2012/04/21/adding-authentication-waiting-lists-and-sign-ups-to-and-express-app-using-drawbridge-and-redis/"/>
    <updated>2012-04-21T00:00:00-04:00</updated>
    <id>http://liamkaufman.com/blog/2012/04/21/adding-authentication-waiting-lists-and-sign-ups-to-and-express-app-using-drawbridge-and-redis</id>
    <content type="html"><![CDATA[<p>
There are several popular modules for adding password-based user authentication to an Express.js app. Unfortunately, they require writing lots of code to get started. I prefer the approach that authentication libraries like Devise take: they generate code and views, and you’re free to modify, or delete, what’s created. 
</p>

<p>
Given the authentication options for Express.js I wanted to create a module that would make adding user authentication quick and easy. Moreover, I also wanted developers to be free to edit and modify the generated views. In addition to authentication I wanted the module to handle sign ups (the type you see on a just-launched startup’s page) and to handle waiting lists and invitations. Based on the module&#8217;s functionality I&#8217;ve decided to call it Drawbridge.js.
</p>

<h2>User Authentication with Drawbridge.js</h2>
<p>
Drawbridge.js uses Redis to persists its data, but it’s possible for developers to create other database adapters for Drawbridge (pull-requests accepted). I chose Redis because its ability to pipeline multiple commands reducing round trips between the server and the database. The atomic nature of pipelined commands obviates a lot of complex callbacks and makes the resulting code much easier to understand. Overall Redis is easy to use, easy to understand and fast - great features for an authentication module. 
</p>
<p>
To send email, Drawbridge uses either nodemailer, or the postmark modules. I included the <a href="https://postmarkapp.com">Postmark</a> option because I&#8217;m currently using it and I like it. However, developers are free to add additional email adapters.
</p>

<h2>Drawbridge Screencast</h2>
<p>
I’ve created a short screencast to show how easy it is to add drawbridge to an existing Express.js application. Before you watch the screencast it’s important that I outline a couple of caveats:
</p>
<p>
  <ol>
    <li>Drawbridge is not ready for production - it’s basically a working prototype.</li>
    <li>Drawbridge views and variables are inconsistently named, that will need to be fixed.</li>
    <li>The code needs refactoring and more testing.</li>
    <li>Drawbridge needs to be picked apart for security issues.</li>
  </ol>
</p>
<p>
With those caveats out of the way here is the video:
</p>

<p>
<iframe src="http://player.vimeo.com/video/40780990?title=0&amp;byline=0&amp;portrait=0" width="400" height="300" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><p><a href="http://vimeo.com/40780990">Drawbridge.js</a> from <a href="http://vimeo.com/user11381617">Liam Kaufman</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
</p>

<p>
While I built Drawbridge.js to scratch my own itch, I hope others will find it useful as well. Once I refine it further I will most certainly start to use it in my own projects. If you’re interested in Drawbridge 1) watch the project on Github and 2) try and get it working on your toy Express apps. I welcome feedback on both the architecture of Drawbridge and its security.
</p>

<p>
<a class="github" href="https://github.com/liamks/Drawbridge.js"><span></span>Drawbridge.js on Github</a>
</p>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Making Hacker News Faster: Two Approaches]]></title>
    <link href="http://liamkaufman.com/blog/2012/03/22/making-hacker-news-faster-two-approaches/"/>
    <updated>2012-03-22T00:00:00-04:00</updated>
    <id>http://liamkaufman.com/blog/2012/03/22/making-hacker-news-faster-two-approaches</id>
    <content type="html"><![CDATA[<p>
Over the years traffic to <a href="http://news.ycombinator.com">Hacker News (HN)</a>, &#8220;a social news website about computer hacking and startup companies&#8221; <a href="http://en.wikipedia.org/wiki/Hacker_News">(Wikipedia)</a>, has grown consistently, with an <a href=”http://www.ycombinator.com/images/hntraffic-5mar12.png”>average of 150,000 daily uniques</a>. The growth in traffic may explain why load times seem increasingly variable. I couldn’t help but wonder if some optimizations could be made to decrease both variability and load times. I&#8217;ll propose two broad approaches, the first involves migrating away from table based layouts while the second involves consuming a JSON API.
</p>

<h2> Approach 1: Tables to Divs </h2>

<div class="table">
  <h2> Table 1. Hacker News Resource Statistics </h2>
  <table>
    <tr>
      <th>Resource</th>
      <th>Size (With Tables) </th>
      <th>Size (With Divs) </th>
      <th>% Change </th>
    </tr>
    <tr>
      <td>HTML</td>
      <td>26KB</td>
      <td>15KB</td>
      <td>-42%</td>
    </tr>
    <tr>
      <td>CSS</td>
      <td>1.7KB</td>
      <td>2.3KB</td>
      <td>+35%</td>
    </tr>
    <tr>
      <td>Logo</td>
      <td>100B</td>
      <td>0</td>
      <td>-100%</td>
    </tr>
    <tr>
      <td>Up Arrow</td>
      <td>111B</td>
      <td>0</td>
      <td>-100%</td>
    </tr>
    <tr>
      <td>Total</td>
      <td>27.9KB</td>
      <td>17.3KB</td>
      <td>-37.2%</td>
    </tr>
  </table>
  <p>
    In the DIV version, the logo and up arrow were base 64 encoded and included in the HTML and CSS files. 
  </p>
</div>

<p>
  HN&#8217;s front page is comprised of: 4 tables, 98 rows, 159 columns, 37 inline style declarations and numerous attributes that dictate style. To reduce the markup on the front page I created a new HN front page (<a href="https://github.com/liamks/Making-HN-Faster/blob/master/HackerNewsV2.html">Github link</a>) that looks identical to the existing page but does not include tables or inline css. I also went a step further and base64 encoded both the logo and the up arrow to decrease the number of requests. The completed CSS file was run through a <a href="http://www.minifycss.com/css-compressor/">css minifyer</a> to yield further reductions. With those changes only two requests are necessary, one for the HTML file and one for the CSS file. Table 1 shows that those changes yielded an overall reduction of 37%.
</p>

<p>
  I also slightly modified the JavaScript responsible for sending up-votes to the server. Instead of grabbing a vote&#8217;s id from the id of the HTML node, it gets it from the &#8216;data-id&#8217; attribute. Otherwise, the JavaScript remains identical. As an aside, if you have not examined the JavaScript that is responsible for sending votes to the server, I&#8217;ve included it below (the existing code). It&#8217;s a creative use of an image tag. An image node is created, but not added to the DOM. When the image node is assigned a &#8216;src&#8217;, which happens to include all the vote info, it then requests the &#8216;image&#8217;, using the constructed url. Thus the &#8216;image&#8217; request becomes analogous to an AJAX GET request, but without a conventional response.
</p>

<figure class='code'><figcaption><span>Votes With IMG Nodes</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">byId</span><span class="p">(</span><span class="nx">id</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">return</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="nx">id</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">vote</span><span class="p">(</span><span class="nx">node</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">v</span> <span class="o">=</span> <span class="nx">node</span><span class="p">.</span><span class="nx">id</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="sr">/_/</span><span class="p">);</span>   <span class="c1">// {&#39;up&#39;, &#39;123&#39;}</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">item</span> <span class="o">=</span> <span class="nx">v</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// hide arrows</span>
</span><span class='line'>  <span class="nx">byId</span><span class="p">(</span><span class="s1">&#39;up_&#39;</span>   <span class="o">+</span> <span class="nx">item</span><span class="p">).</span><span class="nx">style</span><span class="p">.</span><span class="nx">visibility</span> <span class="o">=</span> <span class="s1">&#39;hidden&#39;</span><span class="p">;</span>
</span><span class='line'>  <span class="nx">byId</span><span class="p">(</span><span class="s1">&#39;down_&#39;</span> <span class="o">+</span> <span class="nx">item</span><span class="p">).</span><span class="nx">style</span><span class="p">.</span><span class="nx">visibility</span> <span class="o">=</span> <span class="s1">&#39;hidden&#39;</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// ping server</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">ping</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Image</span><span class="p">();</span>
</span><span class='line'>  <span class="nx">ping</span><span class="p">.</span><span class="nx">src</span> <span class="o">=</span> <span class="nx">node</span><span class="p">.</span><span class="nx">href</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">return</span> <span class="kc">false</span><span class="p">;</span> <span class="c1">// cancel browser nav</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

<h2> Approach 2: JSON API </h2>
<p>
  Although approach 1 results in a 37% decrease in data transferred to the client, markup and data must be transferred to the client on every refresh. In approach two, the markup is only transferred to the client once, and then cached, while the data is sent the client via JSON. Using this approach would decrease the HTML file but no doubt increase the JavaScript file. However, both of those resources could be cached in browser, and cached on a CDN, drastically reducing the number of requests to HN&#8217;s server. Furthermore, the JSON representing the stories on the front page <a href="https://github.com/liamks/Making-HN-Faster/blob/master/frontpage.json">is 7.8KB</a>, much smaller than the amount size of the existing solution or even approach 1.
</p>

<p>
  Approach 2 is not without its drawbacks. It would require significant changes in both HN&#8217;s backend and large changes to the client-side. A JavaScript application and API would have to be created. This approach would likely be incompatible with bots that would not execute the JavaScript necessary to populate the page with stories. To get around this the agent-type could be detected and a static version could be served to bots. Alternatively, the webpage could be pre-populated with stories and subsequent requests would take advantage of AJAX get requests. This would simplify matters, but make caching more difficult, since the cache page would require updating every time the front page changes.
</p>

<h2> Conlusions </h2>
<p>
  By transitioning from tables to divs, and inline css to external css, HN could dramatically reduce the bandwidth required to serve its web pages. The first approach would require minimal changes to HN&#8217;s back-end making it a good candidate for adoption. While the second approach could yield even better results, it would require drastic changes to both the server and the client, making it more suitable as a long term solution.
</p>
<p>
  In addition to the two approaches above, gzip compressing both the .html and the .css would further reduce transferred data. It would also be beneficial to add the appropriate headers to enable browser caching for CSS.
</p>
<p>
  While Paul Graham may have insufficient time, or interests, in implementing some of the above changes, I suspect he knows a few individuals who would be willing to help out.
</p>

<p>
<a class="github" href="https://github.com/liamks/Making-HN-Faster"><span></span>Code on Github</a>
</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[From Digg to Reddit to Hacker News: What's Next?]]></title>
    <link href="http://liamkaufman.com/blog/2012/03/22/from-digg-to-reddit-to-hacker-news-whats-next/"/>
    <updated>2012-03-22T00:00:00-04:00</updated>
    <id>http://liamkaufman.com/blog/2012/03/22/from-digg-to-reddit-to-hacker-news-whats-next</id>
    <content type="html"><![CDATA[<p>
Dustin Curtis, the creator of <a href="http://svbtle.com/">Svbtle</a>, recently mentioned on <a href="https://twitter.com/#!/dcurtis/status/182986897444966402">Twitter</a>:
</p>
<blockquote>
I miss the Hacker News from four years ago. It was awesome. The discussions there are not even worth reading anymore. It&#8217;s sad.
</blockquote>
<p>
 Based on the number of retweets and favorites, I suspect that others agree. In fact the idea that Hacker News is degrading is common enough that it has been addressed on <a href="http://ycombinator.com/newsguidelines.html">HN’s guidelines</a>: 
</p>
<blockquote>
 If your account is less than a year old, please don&#8217;t submit comments saying that HN is turning into Reddit. (It&#8217;s a common semi-noob illusion.).
</blockquote>
<p>
  However, Mr Curtis has been on HN for <a href="http://news.ycombinator.com/user?id=dcurtis">over five years</a>, and is certainly not subject to the &#8216;common semi-noob illusion&#8217;. Is HN getting worse then?
</p>

<p>
I suspect that when HN started only those that were most passionate about hacking were familiar with HN and would take the time to comment on it. As time went on the popularity of both Y Combinator and HN may have resulted in the level of discourse regressing to the mean. That&#8217;s not to say that there aren&#8217;t still intelligent comments, in fact I&#8217;d argue that there are more intelligent comments than there were 4 or 5 years ago. However, people tend to remember the unintelligent comments more, especially when those comments contain opinions that differ from their own or originate from non-experts.
</p>

<p>
If Digg, Reddit and Hacker News are no longer the best places for discussion how can we create a place that is? While there ought to be many ways to encourage scholarly discussion, and discourage idiotic comments, I want to explore several ideas.
</p>

<h2>Exclusivity</h2>
<p>
In the early stages Digg, Reddit and Hacker News were implicitly exclusive. They didn’t discourage people from joining, but their initial lack of popularity acted as a filter to those who were technically savvy and within certain social networks. Once the exclusivity vanished the communities became diluted. <a href="http://forrst.com">Forrst</a> is explicitly exclusive and is by invitation only. Does Forrst&#8217;s exclusivity lead to a stronger community? To reiterate, is exclusivity a necessity in keeping a social news site strong and viable?
</p>
<h2>Experts</h2>
<p>
I enjoy when an article pops up on HN about physics or biology and several graduate students in those fields provide intelligent comments. Is there a way to officially denote that someone is an expert in a field and automatically give their comments more weight? In very esoteric subjects it isn&#8217;t necessary, the complexity of the subject reduces &#8220;average&#8221; comments. However, in simpler subjects, <a href="http://en.wikipedia.org/wiki/Parkinson's_Law_of_Triviality">bikeshedding</a> becomes an issue. Could bikeshedding be prevented by weighting comments based on the user&#8217;s past comments? For instance, if an individual has been voted up when discussing physics, perhaps future comments on physics should be algorithmically voted up.
</p>

<h2>Focus</h2>
<p>
One thing I really appreciate about HN is the variety of content. However, I can’t help but wonder if a social news site restricted the content to just a specific topic if that would both decrease the probability that the content, and discussion, become watered down? Forrst focuses on design and development, has their focus helped them? Reddit has addressed this issue with subreddits, but the result seems to be many hardly used subreddits. I think focus is important, but at the same time I like being exposed to new topics, can the those two wishes be balanced?
</p>
<h2>Conclusions</h2>
<p>
There is no magic bullet for maintaining the quality of a social news site, but there are a collection of concepts that may help. It would be interesting to A/B test some of those ideas. One could imagine creating several social news websites for different topics and making some exclusive and some not, or altering other variables and see which succeed. What do you think is important in a social news site?
</p>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Scraping Web Pages with jQuery, Node.js and Jsdom]]></title>
    <link href="http://liamkaufman.com/blog/2012/03/08/scraping-web-pages-with-jquery-nodejs-and-jsdom/"/>
    <updated>2012-03-08T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2012/03/08/scraping-web-pages-with-jquery-nodejs-and-jsdom</id>
    <content type="html"><![CDATA[<p>
I always found it odd that accessing DOM elements with Ruby, or Python, wasn&#8217;t as easy as it was with jQuery. Many HTML parsing libraries employ Simple API for XML (SAX) that can handle extremely large XML documents, but is cumbersome and adds complexity. Other parsing libraries use XML Path Language (XPath), which is conceptually simpler than SAX, but still more of an effort than jQuery. I was pleasantly surprised to discover that it&#8217;s possible to use jQuery to parse web pages with Node.js. This is accomplished by using <a href="https://github.com/tmpvar/jsdom">jsdom, &#8220;a javascript implementation of the W3C DOM&#8221;</a>.
</p>

<h2>jQuery and jsdom</h2>
<p>
Using jsdom you can specify a local file, or url, and jsdom will return the <code>window</code> object for that document. Additionally, JavaScript can be inserted into the document; in our case we&#8217;re inserting the jQuery library. In the example below all the links from the Hacker News front page are logged to the console.
</p>

<figure class='code'><figcaption><span>Scraping Links From Hacker News</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">jsdom</span>  <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;jsdom&#39;</span><span class="p">);</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">fs</span>     <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;fs&#39;</span><span class="p">);</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">jquery</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">readFileSync</span><span class="p">(</span><span class="s2">&quot;./jquery-1.7.1.min.js&quot;</span><span class="p">).</span><span class="nx">toString</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="nx">jsdom</span><span class="p">.</span><span class="nx">env</span><span class="p">({</span>
</span><span class='line'>  <span class="nx">html</span><span class="o">:</span> <span class="s1">&#39;http://news.ycombinator.com/&#39;</span><span class="p">,</span>
</span><span class='line'>  <span class="nx">src</span><span class="o">:</span> <span class="p">[</span>
</span><span class='line'>    <span class="nx">jquery</span>
</span><span class='line'>  <span class="p">],</span>
</span><span class='line'>  <span class="nx">done</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">errors</span><span class="p">,</span> <span class="nb">window</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">$</span> <span class="o">=</span> <span class="nb">window</span><span class="p">.</span><span class="nx">$</span><span class="p">;</span>
</span><span class='line'>    <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">).</span><span class="nx">each</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>      <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span> <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">).</span><span class="nx">attr</span><span class="p">(</span><span class="s1">&#39;href&#39;</span><span class="p">)</span> <span class="p">);</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>

<h2>Making Scraping More Robust</h2>
<p>
  Unfortunately there are few common bugs that I ran into when scraping content with jQuery and jsdom. Specifically there are two issues, that aren&#8217;t necessarily specific to jsdom, that are worth watching out for. 
</p>

<h3>jQuery Return Values</h3>
<p>
  The first issue are return values from jQuery function calls. Extra attention has to be paid to return values. Applying a method to <code>undefined</code> will crash a program, a problem that can be especially apparent in DOM parsing. Consider the example below:
</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="p">(</span><span class="nx">$</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)[</span><span class="mi">7</span><span class="p">]).</span><span class="nx">attr</span><span class="p">(</span><span class="s1">&#39;href&#39;</span><span class="p">).</span><span class="nx">split</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>
<p>
  If there are 8, or more, links on a page the 8th link will be returned and its href attribute will be split into an array. However, if there are less than 8 the <code>attr('href')</code> will return <code>undefined</code> and calling <code>split()</code> on it will crash the program. Since HTML pages aren&#8217;t as structured as API responses, its important not to assume too much and always check return values.
</p>

<h3>Web Page Errors</h3>
<p>
  It&#8217;s entirely possible that the url passed to jsdom returns an error. If the error is temporary, your scraper might miss out on important information. This issue can be mitigated by recursively retrying the url, like the example below:
</p>

<figure class='code'><figcaption><span>Managing Errors</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">getLinks</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">retries</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">if</span><span class="p">(</span><span class="nx">retries</span> <span class="o">===</span> <span class="mi">3</span><span class="p">){</span>
</span><span class='line'>    <span class="k">return</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span><span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">retries</span> <span class="o">===</span> <span class="kc">undefined</span><span class="p">){</span>
</span><span class='line'>    <span class="nx">retries</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">jsdom</span><span class="p">.</span><span class="nx">env</span><span class="p">({</span>
</span><span class='line'>    <span class="nx">html</span><span class="o">:</span> <span class="s1">&#39;http://news.ycombinator.com/&#39;</span><span class="p">,</span>
</span><span class='line'>    <span class="nx">src</span><span class="o">:</span> <span class="p">[</span>
</span><span class='line'>      <span class="nx">jquery</span>
</span><span class='line'>    <span class="p">],</span>
</span><span class='line'>    <span class="nx">done</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">errors</span><span class="p">,</span> <span class="nb">window</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>      <span class="k">if</span><span class="p">(</span><span class="nx">errors</span><span class="p">){</span>
</span><span class='line'>        <span class="k">return</span> <span class="nx">getLinks</span><span class="p">(</span><span class="nx">retries</span> <span class="o">+</span> <span class="mi">1</span><span class="p">);</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>      <span class="kd">var</span> <span class="nx">$</span> <span class="o">=</span> <span class="nb">window</span><span class="p">.</span><span class="nx">$</span><span class="p">;</span>
</span><span class='line'>      <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">).</span><span class="nx">each</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span> <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">).</span><span class="nx">attr</span><span class="p">(</span><span class="s1">&#39;href&#39;</span><span class="p">)</span> <span class="p">);</span>
</span><span class='line'>      <span class="p">});</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

<p>
With the above approach, if errors are encountered <code>getLinks</code> will be called recursively with a larger <code>retries</code> value. On the 3rd retry the function will return. If you wanted to go further you could wrap the recursive call in <code>setTimeout</code> to ensure that the recursive web request was not made immediately after the error was encountered.
</p>

<h2>Conclusions</h2>
<p>
  Parsing web pages with jQuery on the server is a much more natural experience for developers already accustomed to using jQuery in the client. However, prior to scraping it&#8217;s worth checking if the site 1) allows scraping and 2) does not already have an API. Consuming a JSON API would be even easy than scraping and parsing!
</p>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Why Riak and Node.js Make a Great Pair]]></title>
    <link href="http://liamkaufman.com/blog/2012/03/01/why-riak-and-nodejs-make-a-great-pair/"/>
    <updated>2012-03-01T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2012/03/01/why-riak-and-nodejs-make-a-great-pair</id>
    <content type="html"><![CDATA[<p>
In the last few years there has been a proliferation of noSQL databases. Searching on Google for <code>site:news.ycombinator.com nosql</code> yields over 2,500 hits, many of which include include posts asking when you&#8217;d want to use a noSQL database. If you&#8217;re used to a relational database it might seem like an unnecessary burden to learn another database paradigm, but there&#8217;s one open source noSQL database that I think is not only worth the burden, but is a perfect fit for Node.js development: <a href=”http://wiki.basho.com/What-is-Riak%3F.html”>Riak (pronounced &#8220;REE-ack&#8221;)</a>. 
</p>

<h2>Why is Riak a Good Fit with JavaScript and Node.js?</h2>

<p>
<a href="http://riakjs.org/">Riak-js</a> makes storing JavaScript objects easy. There is no need to <code>JSON.stringify()</code> a JavaScript object when saving it, or applying <code>JSON.parse()</code> when retrieving. 
</p>

<figure class='code'><figcaption><span>Riak and Node.js Basics</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">db</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;riak-js&#39;</span><span class="p">).</span><span class="nx">getClient</span><span class="p">();</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">post</span> <span class="o">=</span> <span class="p">{</span><span class="nx">id</span><span class="o">:</span> <span class="mi">17</span><span class="p">,</span>
</span><span class='line'>            <span class="nx">date</span><span class="o">:</span> <span class="k">new</span> <span class="nb">Date</span><span class="p">(),</span>
</span><span class='line'>            <span class="nx">title</span><span class="o">:</span> <span class="s1">&#39;a blog post&#39;</span><span class="p">,</span>
</span><span class='line'>            <span class="nx">body</span><span class="o">:</span> <span class="s1">&#39;A blog post about Riak&#39;</span><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="nx">db</span><span class="p">.</span><span class="nx">save</span><span class="p">(</span><span class="s1">&#39;posts&#39;</span><span class="p">,</span> <span class="nx">post</span><span class="p">.</span><span class="nx">id</span><span class="p">,</span> <span class="nx">post</span><span class="p">);</span>
</span><span class='line'><span class="nx">db</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;posts&#39;</span><span class="p">,</span> <span class="mi">17</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">data</span><span class="p">,</span> <span class="nx">meta</span><span class="p">){</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
</span><span class='line'><span class="p">});</span>
</span><span class='line'><span class="cm">/* prints</span>
</span><span class='line'><span class="cm">{ id: 17,</span>
</span><span class='line'><span class="cm">  date: &#39;2012-02-29T18:26:44.400Z&#39;,</span>
</span><span class='line'><span class="cm">  title: &#39;a blog post&#39;,</span>
</span><span class='line'><span class="cm">  body: &#39;A blog post about Riak&#39; }</span>
</span><span class='line'><span class="cm">*/</span>
</span></code></pre></td></tr></table></div></figure>

<p>
In the above example, a riak-js client is created and a post object is created. The post object is saved into the &#8216;posts&#8217; bucket, with its id as its key. To retrieve the post, the bucket and key are referenced. 
</p>

<p>
Using JavaScript in the client, and the server are nice, and being able to easily save JavaScript objects is even better. Not having to switch between languages would certainly reduce annoying syntactic problems. This would also allow you to write the entire stack in JavaScript, CoffeeScript or ClojureScript, giving you several programming paradigms to choose from.  
</p>

<p>
If you decided to use <A href="http://andyet.net/blog/2011/feb/15/re-using-backbonejs-models-on-the-server-with-node/">Backbone.js on the server</a>, calling <code>toJSON()</code> on a Backbone model would allow you to easily store the model in the Riak. 
</p>

<h2>Why Riak?</h2>

<p>
At this point you might be wondering why you’d want to use Riak when CouchDB also has a JavaScript interface and can do some of the above. As Damien Katz, the creator of CouchDB has pointed out, <a href="http://damienkatz.net/2012/01/why_couchbase.html">CouchDB is slow and can&#8217;t &#8220;scale-out on it&#8217;s own&#8221;</a>.  In contrast, Riak was built for replication and scaling out. In fact, people at Basho, the company behind Riak, <a href="http://lists.basho.com/pipermail/riak-users_lists.basho.com/2010-April/000876.html">indicate that adding new nodes actually increases throughput</a>.
</p>

<h2>Additional Features of Riak</h2>
<p>
Saving JavaScript objects and easy scaling are both good fits with node.js but Riak has some additional features, such as buckets and links, that make retrieval convenient. With buckets the following functions become possible:
</p>

<figure class='code'><figcaption><span>Riak Buckets</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>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// Get all the posts within the posts bucket</span>
</span><span class='line'><span class="nx">db</span><span class="p">.</span><span class="nx">getAll</span><span class="p">(</span><span class="s1">&#39;posts&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Get all the posts with the title ===  &#39;a blog post&#39; </span>
</span><span class='line'><span class="nx">db</span><span class="p">.</span><span class="nx">getAlll</span><span class="p">(</span><span class="s1">&#39;posts&#39;</span><span class="p">,</span> <span class="p">{</span> <span class="nx">where</span><span class="o">:</span> <span class="p">{</span><span class="nx">title</span><span class="o">:</span> <span class="s1">&#39;a blog post&#39;</span> <span class="p">}});</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Get the number of posts</span>
</span><span class='line'><span class="nx">db</span><span class="p">.</span><span class="nx">count</span><span class="p">(</span><span class="s1">&#39;posts&#39;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>

<p>
Another interesting property of Riak, is it’s concepts of links. A link establishes a &#8220;one-way relationships between objects in Riak&#8221;.  For instance, say we wanted to link similar posts the following would do:
</p>

<figure class='code'><figcaption><span>Riak Links</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>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">aNewPost</span> <span class="o">=</span> <span class="p">{</span><span class="nx">id</span><span class="o">:</span> <span class="mi">18</span><span class="p">,</span>
</span><span class='line'>                <span class="nx">date</span><span class="o">:</span> <span class="k">new</span> <span class="nb">Date</span><span class="p">(),</span>
</span><span class='line'>                <span class="nx">title</span><span class="o">:</span> <span class="s1">&#39;a second blog post&#39;</span><span class="p">,</span>
</span><span class='line'>                <span class="nx">body</span><span class="o">:</span> <span class="s1">&#39;blog post about Riak part 2&#39;</span><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Save the second post, with a link to the first post</span>
</span><span class='line'><span class="nx">db</span><span class="p">.</span><span class="nx">save</span><span class="p">(</span><span class="s1">&#39;posts&#39;</span><span class="p">,</span> <span class="nx">aNewPost</span><span class="p">.</span><span class="nx">id</span><span class="p">,</span> <span class="nx">aNewPost</span><span class="p">,</span>
</span><span class='line'>  <span class="p">{</span> <span class="nx">links</span><span class="o">:</span> <span class="p">[</span> <span class="p">{</span><span class="nx">bucket</span><span class="o">:</span> <span class="s1">&#39;posts&#39;</span><span class="p">,</span> <span class="s1">&#39;key&#39;</span><span class="o">:</span> <span class="mi">17</span> <span class="p">}</span> <span class="p">]});</span>
</span><span class='line'>
</span><span class='line'><span class="nx">db</span><span class="p">.</span><span class="nx">walk</span><span class="p">(</span><span class="s1">&#39;posts&#39;</span><span class="p">,</span> <span class="s1">&#39;18&#39;</span><span class="p">,</span> <span class="p">[{</span><span class="nx">bucket</span><span class="o">:</span><span class="s1">&#39;posts&#39;</span><span class="p">,</span><span class="nx">tag</span><span class="o">:</span><span class="s1">&#39;_&#39;</span><span class="p">}]);</span>
</span><span class='line'><span class="c1">// db.walk, traverses object 18&#39;s links, </span>
</span><span class='line'><span class="c1">// which happens to be post 17, and returns them.</span>
</span></code></pre></td></tr></table></div></figure>

<h2>Conclusions</h2>

<p>
While the above assessment is pretty rosey, Riak shouldn’t be the only database in your toolbox. Redis’ pub/sub and sorted sets are unmatched in Riak. If you’re running <a href="http://labs.linkfluence.net/nosql/2011/03/07/moving_from_couchdb_to_riak.html">map/reduce over large datasets, you’re likely better off using Hadoop</a>. Conversely if your already well-versed in SQL, and your data is relational, using Postgresql is probably a better fit. Despite those caveats being able to easily scale your database, and save JavaScript objects, is a pretty compelling reason to use Riak with Node.js
</p>

<h2>Further Riak and Node.js Reading</h2>
<ul>
<li><a href="http://www.slideshare.net/seancribbs/riak-with-nodejs">Riak with Node.js</a></li>
<li><a href="http://blogs.digitar.com/jjww/2011/03/riak-vs-couchdb-for-storing-100000-coupons/">Riak vs Couchdb for storing 100000 Coupons</a></li>
<li><a href="http://labs.linkfluence.net/nosql/2011/03/07/moving_from_couchdb_to_riak.html">Moving from Couchdb to Riak</a></li>
<li><a href="http://siculars.posterous.com/paginating-with-riak">Pagination with Riak</a></li>
</ul>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Adding Real-Time To Rails With Socket.IO, Node.js and Backbone.js (With Demo)]]></title>
    <link href="http://liamkaufman.com/blog/2012/02/25/adding_real-time_to_rails_with_socket.IO_nodejs_and_backbonejs_with_demo/"/>
    <updated>2012-02-25T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2012/02/25/adding_real-time_to_rails_with_socket.IO_nodejs_and_backbonejs_with_demo</id>
    <content type="html"><![CDATA[<p>
  <a href="http://node-chatty.herokuapp.com/chatty" target="_blank"><img src="http://liamkaufman.com/images/chatty-screen.png"></a>
</p>
<p>
  UPDATE: see my <a href="http://liamkaufman.com/blog/2013/02/27/adding-real-time-to-a-restful-rails-app/">new article on adding real-time to your Rails application</a>.
</p>
<p>
  Despite the <a href="http://gilesbowkett.blogspot.in/2012/02/rails-went-off-rails-why-im-rebuilding.html">recent distaste for Rails</a>, I still think its a nice framework for developing websites (e.g. devise &amp; active record). However, if you want real-time communication Socket.IO and Node.js seem to be the best options. If you already have an existing Rails application porting the entire application to Node.js is likely not on option. Fortunately, it is relatively easy to use Rails to serve your client-side Socket.IO web application, while Node.js and Socket.IO are used for real-time communication. The primary goal of this article is to show one method of integrating a real-time application, that is slightly more complex than a todo app, with Rails. Thus, I created Chatty, a simple chat room web application that allows a user to see all the messages in the chat room, or filter the messages by user. <a href="http://twitter.github.com/bootstrap/index.html">Twitter&#8217;s Bootstrap</a> was used for the CSS and modal dialogue. 
</p>
<p>
<a class="github" href="https://github.com/liamks/Chatty"><span></span>Code on Github</a>
</p>
<p>
  Rather than explain the code step-by-step, I&#8217;ll provide a high level overview of:
  <ul>
    <li>File organization</li>
    <li>JavaScript Templates and EJS</li>
    <li>Application Archicture and Publish/Subscribe</li>
    <li>Module Architecture</li>
    <li>Deploying to Heroku</li>
  </ul> 
<p>

<h2>File Organization</h2>
<p>
  The entire client-side Backbone.js application is within <code>app/assets/javascripts</code>. Using a JavaScript manifest file (<code>backboneApp.js</code>) all of the application&#8217;s JavaScript files are specified.
</p>

<figure class='code'><figcaption><span>Manifest file (app/assets/javasripts/bacboneApp.js)</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='text'><span class='line'>//= require jquery
</span><span class='line'>//= require bootstrap
</span><span class='line'>//= require underscore
</span><span class='line'>//= require backbone
</span><span class='line'>//= require socket.io
</span><span class='line'>//= require app
</span></code></pre></td></tr></table></div></figure>
<p>
  The Backbone application is within the <code>app</code> folder, which also has a manifest file. The manifest files describe all the JavaScript files that comprise the application. Within the application&#8217;s html file only a single line of code is needed to include the manifest file: <code>=javascript_include_tag "backboneApp"</code> (haml for templating). The actual organization of the files is as follows:
</p>

<figure class='code'><figcaption><span>app/assets</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>javascripts
</span><span class='line'>├── app
</span><span class='line'>│   ├── index.js
</span><span class='line'>│   ├── launch.js.coffee
</span><span class='line'>│   ├── main.js.coffee
</span><span class='line'>│   ├── modules
</span><span class='line'>│   │   ├── index.js
</span><span class='line'>│   │   ├── loadModule.js.coffee
</span><span class='line'>│   │   ├── messageModule.js.coffee
</span><span class='line'>│   │   ├── socketModule.js.coffee
</span><span class='line'>│   │   └── userModule.js.coffee
</span><span class='line'>│   └── templates
</span><span class='line'>│       ├── message.jst.ejs
</span><span class='line'>│       ├── modal.jst.ejs
</span><span class='line'>│       └── user.jst.ejs
</span><span class='line'>├── application.js
</span><span class='line'>├── backboneApp.js
</span><span class='line'>└── backbone_app.js.coffee
</span></code></pre></td></tr></table></div></figure>

<p>
  <code>main.js.coffee</code> is where the app object is defined, while `launch.js.coffee` is called last, after all the files have loaded, to launch the Backbone.js application. Each module, which might contain models, collections and views, are stored within the modules folder. The module structure was modelled after <a href="http://tbranyen.github.com/backbone-boilerplate/">Backbone Boilerplate</a>.
</p>

<h2>JavaScript Templates and EJS</h2>
<p>
  To take full advantage of the asset pipeline it seems as if Sam Stephenson&#8217;s excellent <a href="https://github.com/sstephenson/ruby-ejs">EJS Gem</a> was the most hassle free approach for JavaScript templates. Both the &#8216;ejs&#8217; and &#8216;jst&#8217; extensions are require for the EJS gem to compile the template, and include it within a JavaScript file. Access to the template is done with the global <code>JST</code> object.
</p>

<h2>Application Architecture - Publish/Subscribe</h2>
<p>
  Before creating the application I decided to forgo the use of asynchronous module definition (AMD) and use a publish/subscribe (pub/sub) architecture (<a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/#detailedobserver">see Addy Osmani&#8217;s description of Pub/Sub</a>). Specifically, each module is wrapped in an <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">immediately-invoked function expression</a>, and within each module functions can attach themselves to events (subscribe), or trigger events (publish). Using this approach the applcation&#8217;s only global variable is <code>app</code> which contains a copy of Backbone&#8217;s event object. 
</p>
<p>
  To reiterate none of the modules call methods from other modules, all communication occurs with pub/sub. This design pattern was a pleasure to use; adding new functionality often required simply subscribing to events! I found that my code stayed much cleaner than previous attemps with Backbone.js.
</p>

<h2>Module Architecture</h2>
<p>The application is comprised of two types of modules, those that contain Backbone.js code (messageModule, userModule), and one that contains the Socket.IO code (socketModule). If either the messageModule, or the userModule, require content from Socket.IO they subscribe to events that the socketModule trigger. Likewise, Socket.IO messages sent to the server are the result of the socketModule suscribing to events triggered by the messageModule and userModule.
</p>
<p>
  Below is an example module that contains skeleton code for an additional Backbone.js module. The ExampleModule class is used to glue all the Backbone.js objects together. In this case their is only one, the ExampleView, in Chatty&#8217;s MessageModule there are two distinct views instantiated within its MessageModule object. 
</p>
<figure class='code'><figcaption><span>Example Module</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">ExampleModel = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Model</span><span class="p">.</span><span class="nx">extend</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'><span class="nv">ExampleCollection = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Collection</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">model: </span><span class="nx">ExampleModel</span>
</span><span class='line'>
</span><span class='line'><span class="c1"># View for a single model</span>
</span><span class='line'><span class="nv">ExampleView = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">render: </span><span class="nf">() -&gt;</span>
</span><span class='line'>    <span class="nx">@$el</span><span class="p">.</span><span class="nx">html</span> <span class="nx">app</span><span class="p">.</span><span class="nx">template</span> <span class="s1">&#39;example&#39;</span><span class="p">,</span> <span class="nx">@model</span><span class="p">.</span><span class="nx">toJSON</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">@$el</span>
</span><span class='line'>
</span><span class='line'><span class="c1"># View for a collection of models</span>
</span><span class='line'><span class="nv">ExamplesView = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">initialize: </span><span class="nf">() -&gt;</span>
</span><span class='line'>    <span class="vi">@collection = </span><span class="k">new</span> <span class="nx">ExampleCollection</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">@collection</span><span class="p">.</span><span class="kc">on</span> <span class="s1">&#39;add&#39;</span><span class="p">,</span> <span class="nx">@addExample</span><span class="p">,</span> <span class="err">@</span>
</span><span class='line'>    <span class="nx">@eventHandlers</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">eventHandlers: </span><span class="nf">() -&gt;</span>
</span><span class='line'>    <span class="c1"># Subscribe to the app-wide event &#39;new-example&#39;. When </span>
</span><span class='line'>    <span class="c1"># the event is called, the call-back function is provided</span>
</span><span class='line'>    <span class="c1"># with an example model, which is then added to the collection.</span>
</span><span class='line'>    <span class="nx">app</span><span class="p">.</span><span class="nx">events</span><span class="p">.</span><span class="kc">on</span> <span class="s1">&#39;new-example&#39;</span><span class="p">,</span> <span class="p">(</span><span class="nx">example</span><span class="p">)</span> <span class="o">=&gt;</span>
</span><span class='line'>      <span class="nx">@collection</span><span class="p">.</span><span class="nx">add</span> <span class="nx">example</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">addExample: </span><span class="nf">(example) -&gt;</span>
</span><span class='line'>    <span class="nv">exampleView = </span><span class="k">new</span> <span class="nx">ExampleView</span>
</span><span class='line'>      <span class="nv">model: </span><span class="nx">example</span>
</span><span class='line'>    <span class="nx">@$el</span><span class="p">.</span><span class="nx">append</span> <span class="nx">exampleView</span><span class="p">.</span><span class="nx">render</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'><span class="k">class</span> <span class="nx">ExampleModule</span>
</span><span class='line'>  <span class="nv">constructor: </span><span class="nf">() -&gt;</span>
</span><span class='line'>    <span class="vi">@examplesView = </span><span class="k">new</span> <span class="nx">ExamplesView</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'><span class="k">new</span> <span class="nx">ExampleView</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>
<h2>Deploying Node.js and Rails App to Heroku</h2>
<h3>Deploying the Node.js server</h3>

<p>
  Heroku requires the following code to create the Socket.IO server and listen for connections (note that Heroku doesn&#8217;t support websockets):
<p>
<figure class='code'><figcaption><span>Socket.IO server</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">app</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;http&#39;</span><span class="p">).</span><span class="nx">createServer</span><span class="p">();</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">io</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;socket.io&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">io</span> <span class="o">=</span> <span class="nx">io</span><span class="p">.</span><span class="nx">listen</span><span class="p">(</span><span class="nx">app</span><span class="p">);</span>
</span><span class='line'><span class="nx">io</span><span class="p">.</span><span class="nx">configure</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>  <span class="nx">io</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="s2">&quot;transports&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s2">&quot;xhr-polling&quot;</span><span class="p">]);</span>
</span><span class='line'>  <span class="nx">io</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="s2">&quot;polling duration&quot;</span><span class="p">,</span> <span class="mi">10</span><span class="p">);</span>
</span><span class='line'>  <span class="nx">io</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="s2">&quot;close timeout&quot;</span><span class="p">,</span> <span class="mi">10</span><span class="p">);</span>
</span><span class='line'>  <span class="nx">io</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="s2">&quot;log level&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">);</span>
</span><span class='line'><span class="p">})</span>
</span><span class='line'>
</span><span class='line'><span class="nx">io</span><span class="p">.</span><span class="nx">sockets</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">&#39;connection&#39;</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">socket</span><span class="p">)</span> <span class="p">{}</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">port</span> <span class="o">=</span> <span class="nx">process</span><span class="p">.</span><span class="nx">env</span><span class="p">.</span><span class="nx">PORT</span> <span class="o">||</span> <span class="mi">5001</span><span class="p">;</span>
</span><span class='line'><span class="nx">app</span><span class="p">.</span><span class="nx">listen</span><span class="p">(</span><span class="nx">port</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>
<p>
  Unfortunately, Heroku&#8217;s documentation only contains fragments of the above code. The above code, along with deploying instructions, is posted across several pages: <a href="http://devcenter.heroku.com/articles/node-js">getting started with Node.js on Heroku/Cedar</a> and <a href="http://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku">using Socket.IO with Node.js on Heroku</a>. The `close timeout` option was added since the default 25 seconds made the chat app seem buggy (a user would log out but other users would seem them logged in for 25 seconds).
</p>

<h3>Deploying the Rails app</h3>
<p>
  Deploying a Rails application is relatively well documented, but I thought I&#8217;d provide a few additional tips.
</p>
<p>
  The URL for the production and development Socket.IO server differ. To accommodate this the Backbone.js app makes an Ajax request to the Rails app and gets the URL of the Socket.IO server along with a unique id for the current user. The Rails app can serve a different Socket.IO URL depending on whether it is currently in production or development.
</p>
<p>
  The other thing that might be new for nacent Rail&#8217;s developers is the inclusion of the <code>response.headers</code> code in the show method, this tells the browser to cache the Backbone.js app for 25,300 seconds.
</p>
<figure class='code'><figcaption><span>Controller associated with Backbone.js App</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">BackboneAppController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
</span><span class='line'>  <span class="n">layout</span> <span class="s1">&#39;backboneApp&#39;</span>
</span><span class='line'>  <span class="n">respond_to</span> <span class="ss">:html</span><span class="p">,</span> <span class="ss">:json</span>
</span><span class='line'>  <span class="k">def</span> <span class="nf">show</span>
</span><span class='line'>    <span class="n">response</span><span class="o">.</span><span class="n">headers</span><span class="o">[</span><span class="s1">&#39;Cache-Control&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="s1">&#39;public, max-age=25300&#39;</span> <span class="k">if</span> <span class="no">Rails</span><span class="o">.</span><span class="n">env</span><span class="o">.</span><span class="n">production?</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">user_info</span>
</span><span class='line'>    <span class="n">respond_with</span><span class="p">({</span>
</span><span class='line'>        <span class="s1">&#39;uuid&#39;</span> <span class="o">=&gt;</span> <span class="no">UUIDTools</span><span class="o">::</span><span class="no">UUID</span><span class="o">.</span><span class="n">random_create</span><span class="o">.</span><span class="n">to_s</span><span class="p">,</span>
</span><span class='line'>        <span class="s1">&#39;socketURL&#39;</span> <span class="o">=&gt;</span> <span class="nb">self</span><span class="o">.</span><span class="n">get_socket_url</span>
</span><span class='line'>    <span class="p">})</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="kp">protected</span>
</span><span class='line'>  <span class="k">def</span> <span class="nf">get_socket_url</span>
</span><span class='line'>    <span class="no">Rails</span><span class="o">.</span><span class="n">env</span><span class="o">.</span><span class="n">production?</span> <span class="p">?</span> <span class="s2">&quot;http://chatty-server.herokuapp.com/&quot;</span> <span class="p">:</span> <span class="s2">&quot;http://0.0.0.0:5001&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>
  In order for Heroku to manage the asset pipeline your application must be <a href="http://devcenter.heroku.com/articles/rails3">deployed to Heroku Cedar&#8217;s stack</a>. Unfortunately the Cedar stack doesn&#8217;t include Varnish caching, requiring you to enable caching via <a href="http://devcenter.heroku.com/articles/memcache#deploying_to_heroku">memcache and the dalli gem</a>. I found that deploying a new version would not necessarily clear the cache and and I had to do it manually (connect to console: <code>heroku run console</code>):
</p>

<figure class='code'><figcaption><span>Clearing the cache</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">dc</span> <span class="o">=</span> <span class="no">Dalli</span><span class="o">::</span><span class="no">Client</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s1">&#39;localhost:11211&#39;</span><span class="p">)</span>
</span><span class='line'><span class="n">dc</span><span class="o">.</span><span class="n">flush_all</span>
</span></code></pre></td></tr></table></div></figure>

<h2>Final Thoughts</h2>
<p>Relying entirely on pub/sub to communicate between modules worked really well in this application, but I wonder if it would scale to a larger application? I&#8217;d also be curious to know how other developers are combining Backbone apps with Rails, I suspect there are a number of ways to do it.</p>

<p>
<a class="github" href="https://github.com/liamks/Chatty"><span></span>Code on Github</a>
</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Integrating Backbone Boilerplate with Rails 3]]></title>
    <link href="http://liamkaufman.com/blog/2012/02/18/integrating-backbone-boilerplate-with-rails3/"/>
    <updated>2012-02-18T00:00:00-05:00</updated>
    <id>http://liamkaufman.com/blog/2012/02/18/integrating-backbone-boilerplate-with-rails3</id>
    <content type="html"><![CDATA[<p>
Despite making several small Backbone.js apps in the past year, Backbone.js had never really clicked with me. I wasn&#8217;t crazy about having to spend time thinking about file and folder organizing for JavaScript and template files. I was also unsure how all the pieces would fit together. Thanks to Tim Branyen&#8217;s <a href="http://tbranyen.github.com/backbone-boilerplate/">Backbone Boilerplate</a> those issues have been significantly reduced. According to Backbone Boilerplate&#8217;s documentation: &#8220;This boilerplate is the product of much research and frustration. Existing boilerplates freely modify Backbone core, lack a build process, and are very prescriptive; this boilerplate changes that.&#8221;
</p>
<p>
While I was excited to use Backbone Boilerplate, it wasn&#8217;t immediately clear how I&#8217;d integrate it with Rails 3. After several hours of tinkering I came up with an approach that places the build product of your backbone app in the <code>lib/assets</code> folder. This approach means that the application can be integrated into the assets pipeline and easily deployed to heroku.

<p>
<a class="github" href="https://github.com/liamks/Rails-Backbone-boilerplate"><span></span>Code on Github</a>
</p>

<h2> Creating the Rails App</h2>

<figure class='code'><figcaption><span>Getting Started</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>// create a new rails app
</span><span class='line'>rails new rails-bb
</span><span class='line'><span class="nb">cd </span>rails-bb/lib
</span><span class='line'>
</span><span class='line'>//remove the index file
</span><span class='line'>rm -r public/index.html
</span><span class='line'>
</span><span class='line'><span class="nb">cd </span>lib
</span><span class='line'>git clone https://github.com/tbranyen/backbone-boilerplate.git
</span><span class='line'><span class="nb">cd </span>backbone-boilerplate
</span><span class='line'>
</span><span class='line'>//switch to the amd branch
</span><span class='line'>git checkout amd
</span><span class='line'>rm -rf .git
</span></code></pre></td></tr></table></div></figure>
<h2> Changing Build Settings </h2>
<p>
In biolerplate&#8217;s config.js file modify the following to:
</p>

<figure class='code'><figcaption><span>line 49 - lib/backbone-boilerplate/build/config.js</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="nx">concat</span><span class="o">:</span> <span class="p">{</span>
</span><span class='line'>  <span class="s2">&quot;dist/debug/require.js&quot;</span><span class="o">:</span> <span class="p">[</span>
</span><span class='line'>    <span class="s2">&quot;assets/js/libs/almond.js&quot;</span><span class="p">,</span>
</span><span class='line'>    <span class="s2">&quot;dist/debug/templates.js&quot;</span><span class="p">,</span>
</span><span class='line'>    <span class="s2">&quot;dist/debug/require.js&quot;</span>
</span><span class='line'>  <span class="p">],</span>
</span><span class='line'>
</span><span class='line'>  <span class="s2">&quot;../assets/javascripts/require-app.js&quot;</span><span class="o">:</span> <span class="p">[</span>
</span><span class='line'>    <span class="s2">&quot;assets/js/libs/almond.js&quot;</span><span class="p">,</span>
</span><span class='line'>    <span class="s2">&quot;dist/debug/templates.js&quot;</span><span class="p">,</span>
</span><span class='line'>    <span class="s2">&quot;dist/debug/require.js&quot;</span>
</span><span class='line'>  <span class="p">]</span>
</span><span class='line'><span class="p">},</span>
</span></code></pre></td></tr></table></div></figure>
<figure class='code'><figcaption><span>line 67 - lib/backbone-boilerplate/build/config.js</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='javascript'><span class='line'><span class="nx">mincss</span><span class="o">:</span> <span class="p">{</span>
</span><span class='line'>  <span class="s2">&quot;dist/release/index.css&quot;</span><span class="o">:</span> <span class="p">[</span>
</span><span class='line'>    <span class="s2">&quot;assets/css/style.css&quot;</span>
</span><span class='line'>  <span class="p">],</span>
</span><span class='line'>
</span><span class='line'>  <span class="s2">&quot;../assets/stylesheets/index.css&quot;</span><span class="o">:</span> <span class="p">[</span>
</span><span class='line'>    <span class="s2">&quot;assets/css/style.css&quot;</span>
</span><span class='line'>  <span class="p">]</span>
</span><span class='line'><span class="p">},</span>
</span></code></pre></td></tr></table></div></figure>

<h2> Creating a Rails Layout and Controller </h2>
<p>
To build the app, go to <code>lib/backbone-boilerplate</code> and run <code>node build default mincss</code>. The build script will create <code>lib/assets/javascripts/require-app.js</code> that includes both the backbone-boilerplate application and the template files. In next step create a rails layout file <code>app/views/layouts/bbapp.html.erb</code> with the following content:
</p>

<figure class='code'><figcaption><span>bbapp.html.erb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="cp">&lt;!DOCTYPE html&gt;</span>
</span><span class='line'><span class="nt">&lt;html&gt;</span>
</span><span class='line'><span class="nt">&lt;head&gt;</span>
</span><span class='line'>  <span class="nt">&lt;meta</span> <span class="na">charset=</span><span class="s">&quot;utf-8&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>  <span class="nt">&lt;meta</span> <span class="na">http-equiv=</span><span class="s">&quot;X-UA-Compatible&quot;</span> <span class="na">content=</span><span class="s">&quot;IE=edge,chrome=1&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>  <span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">&quot;viewport&quot;</span> <span class="na">content=</span><span class="s">&quot;width=device-width,initial-scale=1&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nt">&lt;title&gt;</span>RailsBb<span class="nt">&lt;/title&gt;</span>
</span><span class='line'>  <span class="err">&lt;</span>%= stylesheet_link_tag    &quot;application&quot;, :media =&gt; &quot;all&quot; %&gt;
</span><span class='line'>  <span class="err">&lt;</span>%= csrf_meta_tags %&gt;
</span><span class='line'><span class="nt">&lt;/head&gt;</span>
</span><span class='line'><span class="nt">&lt;body&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c">&lt;!-- Main container --&gt;</span>
</span><span class='line'>  <span class="nt">&lt;div</span> <span class="na">role=</span><span class="s">&quot;main&quot;</span> <span class="na">id=</span><span class="s">&quot;main&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c">&lt;!-- Application source --&gt;</span>
</span><span class='line'>  <span class="err">&lt;</span>%= javascript_include_tag &quot;bbapp&quot;, &quot;data-main&quot; =&gt; &quot;app/index&quot; %&gt;
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;/body&gt;</span>
</span><span class='line'><span class="nt">&lt;/html&gt;</span>
</span></code></pre></td></tr></table></div></figure>

<p>
To plug the backbone app into the asset pipeline create <code>assets/javascript/bbapp.js</code> with the following contents:
</p>

<figure class='code'><figcaption><span>bbapp.js</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">//</span>
</span><span class='line'><span class="c1">//= require require-app</span>
</span></code></pre></td></tr></table></div></figure>
<p>
Now we need to let rails know that it needs to compile bbapp.js for production. To do this open <code>config/environments/production.rb</code> and after <code>config.assets.compile = false</code> add:  
</p>

<figure class='code'><figcaption><span>config\environments\production.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">config</span><span class="o">.</span><span class="n">assets</span><span class="o">.</span><span class="n">precompile</span> <span class="o">+=</span> <span class="sx">%w( bbapp.js )</span>
</span></code></pre></td></tr></table></div></figure>

<p>
To test that this works, we&#8217;ll create a controller that has a single action that uses the <code>bbapp.html.erb</code> layout. From the root of the rails-bb application:
</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>rails generate controller BackBoneBoilerplate app
</span></code></pre></td></tr></table></div></figure>

<p>
Go to the controller that was just created: <code>back_bone_boilerplate_controller.rb</code> and specify the layout:
</p>

<figure class='code'><figcaption><span>app/controllers/back_bone_boilerplate_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>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">BackBoneBoilerplateController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">layout</span> <span class="s1">&#39;bbapp&#39;</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">app</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>

<h2> Final Steps </h2>
<p>
In <code>config/routes.rb</code> a root route is added to point to the controller actiona associated with the backbone app: <code>root :to => 'back_bone_boilerplate#app'</code> At this point we&#8217;re nearly done. Unfortunately to get the backbone.png to load I changed the src attribute, of the img tag on line 2, in <code>lib/backbone-boilerplate/templates/example.html</code> to <code>src="/assets/backbone.png"</code> and then from <code>lib/backbone-boilerplate</code>:
</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>cp assets/img/backbone.png ../app/assets/images/backbone.png
</span><span class='line'>
</span><span class='line'><span class="se">\\</span>recompile
</span><span class='line'>node build default mincss
</span><span class='line'>
</span><span class='line'><span class="nb">cd</span> ..
</span><span class='line'>rails server
</span></code></pre></td></tr></table></div></figure>

<p>
If all went well, when you go to http://0.0.0.0:3000 you should see:
</p>
<p>
<img src="http://liamkaufman.com/images/backbone-boilerplate.png">
</p>

<p>
While the above approach works, it was laborious and requires rebuilding the application with each change. Watching for changes with <code>node build watch</code> would certainly help. I think the advantage of this approach is that in development you can debug the JavaScript, while in production the javascript is minified and goes through the asset pipeline like any other JavaScript file in a Rails app.
</p>]]></content>
  </entry>
  
</feed>
