<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 
 <title>Brandon Tilley</title>
 <link href="http://brandontilley.com/atom.xml" rel="self" />
 <link href="http://brandontilley.com/" />
 <updated>2013-02-03T22:30:55-08:00</updated>
 <id>http://brandontilley.com/</id>
 <author>
   <name>Brandon Tilley</name>
   <email>brandon@brandontilley.com</email>
 </author>

 
 <entry>
   <title>Controlling an Arduino from Node.js</title>
   <link href="http://brandontilley.com/2012/03/02/controlling-an-arduino-from-nodejs.html"/>
   <updated>2012-03-02T07:08:00-08:00</updated>
   <id>http://brandontilley.com/2012/03/02/controlling-an-arduino-from-nodejs</id>
   <content type="html">&lt;p&gt;After expressing an interested in learning microcontroller programming, a friend of mine purchased for me an &lt;a href=&quot;http://arduino.cc/en/Main/arduinoBoardDuemilanove&quot;&gt;Arduino Duemilanove&lt;/a&gt;, which arrived yesterday. Being someone who enjoys web programming, I of course wasted no time in figuring out how I could get it connected to a web page. I opted to use &lt;a href=&quot;http://nodejs.org/&quot;&gt;Node.js&lt;/a&gt; for my integration.&lt;/p&gt;

&lt;p&gt;To communicate with the microcontroller, I used &lt;a href=&quot;https://github.com/voodootikigod/node-serialport&quot;&gt;node-serialport&lt;/a&gt;, which allows you to make a connection to a serial port for reading and writing. For this test, I wrote a sketch to turn the onboard LED on pin 13 off when a &lt;code&gt;0&lt;/code&gt; is read from the serial connection, and to turn the LED on when a &lt;code&gt;1&lt;/code&gt; is read. The contents of this sketch follows; just upload it to your Arduino.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/1962067.js?file=00-sketch.c&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;const int outputPin = 13;

void setup()
{
  pinMode(outputPin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  if (Serial.available() &amp;gt; 0) {
    int incomingByte = Serial.read();

    if (incomingByte == 0x01) {
      digitalWrite(outputPin, HIGH);
    } else if (incomingByte == 0x00) {
      digitalWrite(outputPin, LOW);
    }
  }
}&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;Next up, we need to send a &lt;code&gt;0&lt;/code&gt; or &lt;code&gt;1&lt;/code&gt; byte to the Arduino from Node; here’s a short CoffeeScript program that will blink the LED every second (I’ve hardcoded the device where my Arduino lives; substitute your own).&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/1962067.js?file=01-blink.coffee&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;{SerialPort} = require('serialport')
fs = require 'fs'

port   = '/dev/tty.usbserial-A600enDA'
serial = null
value  = 0x00

toggle = =&amp;gt;
  value = if value == 0x00 then 0x01 else 0x00
  serial.write new Buffer([value])

console.log &amp;quot;Starting...&amp;quot;
fs.stat port, (err, stats) -&amp;gt;
  if err?
    console.log &amp;quot;Couldn't stat #{port}&amp;quot;
    process.exit()

  console.log &amp;quot;Started.&amp;quot;

  serial = new SerialPort port, baudrate: 9600
  setInterval toggle, 1000&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;From here, it’s not difficult to adapt this example into a more complete sample including a web server. Here’s a complete listing of my program, including a web page to access at the root URL to control the LED using jQuery Ajax requests.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/1962067.js?file=02-server.coffee&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;{SerialPort} = require('serialport')
fs = require 'fs'

port = '/dev/tty.usbserial-A600enDA'
express = require 'express'
serial = null
interval = null
lightOn = false

turnOn = =&amp;gt;
  lightOn = true
  serial.write new Buffer([0x01])

turnOff = =&amp;gt;
  lightOn = false
  serial.write new Buffer([0x00])

toggle = =&amp;gt;
  if lightOn
    turnOff()
  else
    turnOn()

app = express.createServer()

app.get '/', (req, res) -&amp;gt;
  res.sendfile 'index.htm'

app.get '/on', (req, res) -&amp;gt;
  clearInterval interval
  turnOn()
  res.end()

app.get '/off', (req, res) -&amp;gt;
  clearInterval interval
  turnOff()
  res.end()

app.get '/blink', (req, res) -&amp;gt;
  clearInterval interval
  interval = setInterval toggle, 500
  res.end()

console.log &amp;quot;Starting...&amp;quot;
fs.stat port, (err, stats) -&amp;gt;
  if err?
    console.log &amp;quot;Couldn't stat #{port}&amp;quot;
    process.exit()

  console.log &amp;quot;Started.&amp;quot;

  serial = new SerialPort port, baudrate: 9600
  app.listen(8080)&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;script src=&quot;https://gist.github.com/1962067.js?file=03-index.htm&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Online Lightswitch&amp;lt;/title&amp;gt;
    &amp;lt;script src=&amp;quot;http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script&amp;gt;
      $(function() {
        $(&amp;quot;#on&amp;quot;).click(function() {
          $.ajax('/on');
        });

        $(&amp;quot;#off&amp;quot;).click(function() {
          $.ajax('/off');
        });

        $(&amp;quot;#blink&amp;quot;).click(function() {
          $.ajax('/blink');
        });
      });
    &amp;lt;/script&amp;gt;
    &amp;lt;style&amp;gt;
      button {
        font-size: 20pt;
      }
    &amp;lt;/style&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;button id=&amp;quot;on&amp;quot;&amp;gt;On!&amp;lt;/button&amp;gt;
    &amp;lt;button id=&amp;quot;off&amp;quot;&amp;gt;Off!&amp;lt;/button&amp;gt;
    &amp;lt;button id=&amp;quot;blink&amp;quot;&amp;gt;Blink!&amp;lt;/button&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;Start the server and visit &lt;code&gt;http://localhost:8080&lt;/code&gt; and click the buttons to control the lights!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Programmer Criticism</title>
   <link href="http://brandontilley.com/2012/01/08/programmer-criticism.html"/>
   <updated>2012-01-08T09:30:00-08:00</updated>
   <id>http://brandontilley.com/2012/01/08/programmer-criticism</id>
   <content type="html">&lt;p&gt;I stumbled across &lt;a href=&quot;http://commandcenter.blogspot.com/2011/12/esmereldas-imagination.html&quot;&gt;a very interesting post&lt;/a&gt; today. The topic of conversation used to make the point is Go and Dart, but you may substitute them with almost any new technology or language and the article reads the same (which is much of the point).&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;It was unnecessary to try Go or Dart before commenting publicly on them; in fact, it was important not to (for one thing, trying them would require programming). The criticisms were loud and vociferous but irrelevant because they weren’t about the languages at all. They were just a standard reaction to something new, empty of meaning, the result of a modern programmer’s need to complain about everything different.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;…&lt;/p&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;A while after Go launched, the criticisms changed tenor somewhat. Some people had actually tried it, but there were still many complainers, including the one quoted above. The problem now was that imagination had failed: Go is a language for writing Go programs, not Java programs or Haskell programs or any other language’s programs. You need to think a different way to write good Go programs. But that takes time and effort, more than most will invest.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I urge you to &lt;a href=&quot;http://commandcenter.blogspot.com/2011/12/esmereldas-imagination.html&quot;&gt;read the post for yourself&lt;/a&gt;, but if you take nothing else away, how about the author’s closing statement:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;I resolve to recognize that a complaint reveals more about the complainer than the complained-about. Authority is won not by rants but by experience and insight, which require practice and imagination. And maybe some programming.&lt;/p&gt;
&lt;/blockquote&gt;
</content>
 </entry>
 
 <entry>
   <title>Socket.IO and the Latest Chrome</title>
   <link href="http://brandontilley.com/2011/08/13/socket-io-and-the-latest-chrome.html"/>
   <updated>2011-08-13T04:05:00-07:00</updated>
   <id>http://brandontilley.com/2011/08/13/socket-io-and-the-latest-chrome</id>
   <content type="html">&lt;p&gt;I spent some time this morning working on an issue, and when I discovered the problem, I thought I’d share my findings.&lt;/p&gt;

&lt;p&gt;The issue is Socket.IO not working quite right on the latest Chrome build (definitely the latest dev build, and I’ve heard people are having issues with the latest stable build as well). Specifically, Socket.IO over WebSockets isn’t working. I received the following error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;warn  - websocket connection invalid
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It turns out that this is because recent builds of Chrome &lt;a href=&quot;http://googlechromereleases.blogspot.com/2011/07/chrome-dev-channel-release.html&quot;&gt;implement a newer version of the WebSocket protocol&lt;/a&gt;. Although the folks at Socket.IO are &lt;a href=&quot;https://github.com/LearnBoost/socket.io/issues/429&quot;&gt;working on a fix&lt;/a&gt;, it’s still not quite ready.&lt;/p&gt;

&lt;p&gt;Interestingly enough, I didn’t have this issue at work, where we’re running the latest dev build of Chrome; instead, I discovered it while working on the same project at home, where I’m running dev Chrome on Ubuntu, so YMMV.&lt;/p&gt;

&lt;p&gt;In the meantime, for development purposes, I’ve simply set Socket.IO to only use AJAX long polling for my app while the issue is sorted out. You can do this in your server code with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;socket.set('transports', ['xhr-polling']);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Give Your JavaScript a Coffee-Infused Backbone</title>
   <link href="http://brandontilley.com/2011/04/18/give-your-javascript-a-coffee-infused-backbone.html"/>
   <updated>2011-04-18T00:55:00-07:00</updated>
   <id>http://brandontilley.com/2011/04/18/give-your-javascript-a-coffee-infused-backbone</id>
   <content type="html">&lt;p&gt;Recently I was working on a little &lt;a href=&quot;https://github.com/BinaryMuse/wow-realm-status-js&quot;&gt;demo web app&lt;/a&gt; that involved completely client-side code. My JavaScript-fu is the weaker of my multi-lingual toolbox, although I’ve been working on it more recently (with more client-side experiments, such as this one, as well as projects in Node.js). Anyway, the first time through the code, I ended up with what was essentially &lt;a href=&quot;https://github.com/BinaryMuse/wow-realm-status-js/blob/f34e70dbace182df4b3cc83fd2f9d663e3031123/js/app.js#files&quot;&gt;a bunch of jQuery statements&lt;/a&gt; strewn about. It worked, but it wasn’t really very pretty. I decided that it was time that I learn how to do something about it. I ended up with two neat tools: &lt;strong&gt;CoffeeScript&lt;/strong&gt; and &lt;strong&gt;Backbone&lt;/strong&gt;.&lt;/p&gt;

&lt;h1 id=&quot;coffeescript&quot;&gt;CoffeeScript&lt;/h1&gt;

&lt;p&gt;&lt;a href=&quot;http://jashkenas.github.com/coffee-script/&quot;&gt;CoffeeScript&lt;/a&gt; is “a little language that compiles into JavaScript.” It offers a syntax reminiscent of Ruby and a few other niceties that make writing JavaScript a lot easier and more fun (in my opinion).&lt;/p&gt;

&lt;p&gt;I bring it up in this post because code samples later will utilize it. For the basics, check out &lt;a href=&quot;http://jashkenas.github.com/coffee-script/#overview&quot;&gt;the overview&lt;/a&gt;—it should be plenty to allow you to grok the code in this post.&lt;/p&gt;

&lt;h1 id=&quot;backbone&quot;&gt;Backbone&lt;/h1&gt;

&lt;p&gt;&lt;a href=&quot;http://documentcloud.github.com/backbone/&quot;&gt;Backbone.js&lt;/a&gt; is the library that really helped bring shape to my code. It provides models, collections, views, routing and more. Your views respond to events in your models or collections to get stuff done. It even has “magic support” for jQuery, so you don’t have to write UI code without it.&lt;/p&gt;

&lt;p&gt;While Backbone is a JavaScript application framework, it doesn’t include a widget library and other frills like several others. If you want to roll your own JavaScript but struggle to keep it in check, it might be what you need.&lt;/p&gt;

&lt;h2 id=&quot;my-app&quot;&gt;My App&lt;/h2&gt;

&lt;p&gt;My application was a &lt;a href=&quot;http://binarymuse.net/misc/wow-realm-status-js/&quot;&gt;World of Warcraft server status page&lt;/a&gt; designed to demonstrate some new API’s that Blizzard is providing. I wanted it to be able to show the current status of every server (fetched via JSONP and refreshed every five minutes) and I wanted the list to be searchable with an input box on the page. Let’s take a look at the various pieces of the app.&lt;/p&gt;

&lt;h2 id=&quot;realm-model&quot;&gt;Realm Model&lt;/h2&gt;

&lt;p&gt;First, I created a model for a single server (aka “realm”). This model holds the name of the realm, its type, current population, whether or not the server is running, and whether or not there is a queue to play on the server. (Although it’s not necessary to set defaults, as all poperties are set automatically from JSON later, I did so here.)&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/924755.js?file=realm_model.coffee&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;window.Realm = Backbone.Model.extend
  initialize: -&amp;gt;
    # Only set default data if it doesn't already exist.
    unless this.get(&amp;quot;name&amp;quot;)?
      this.set
        name:       &amp;quot;unknown&amp;quot;
        slug:       &amp;quot;unknown&amp;quot;
        type:       &amp;quot;n/a&amp;quot;
        population: &amp;quot;n/a&amp;quot;
        queue:      false
        status:     false
&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;h2 id=&quot;realmlist-collection&quot;&gt;RealmList Collection&lt;/h2&gt;

&lt;p&gt;Next up, I created a collection to hold a list of models. It’s through this object that I fetch new data from the JSONP endpoint and update the models accordingly.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/924755.js?file=realmlist_model.coffee&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;window.RealmList = Backbone.Collection.extend
  model: Realm
  url:   &amp;quot;http://us.battle.net/api/wow/realm/status?jsonp=?&amp;quot;

  initialize: -&amp;gt;
    _.bindAll this, 'update', 'parse', 'processUpdate', 'filter'
    # After the first refresh, we no longer want to replace the models
    # in the collection with new ones. Thus, we will use our own 'refresh'
    # method which simply updates all the models with the new data.
    this.bind 'refresh', -&amp;gt;
      this.refresh = this.processUpdate

  # A wrapper around fetch() to (1) fire a &amp;quot;loading&amp;quot; event and
  # (2) ensure that a timer is set so another update happens in the future.
  update: -&amp;gt;
    this.trigger 'refresh:start' # Indicates data is being collected.
    this.fetch()
    window.setTimeout this.update, 1000 * 60 * 5 # update every 5 minutes

  # Custom parse method (1) extracts the array from Blizzard's JSON API and
  # (2) adds an &amp;quot;id&amp;quot; attribute to every model equal to that Realm's slug.
  parse: (response) -&amp;gt;
    _.each response.realms, (realm) -&amp;gt;
      realm.id = realm.slug
    this.trigger 'refresh:end' # Indicates data collection has ended.
    response.realms

  # Our replacement 'refresh' method, for every refresh after the first.
  # Iterates over the models in the collection and updates each one's data.
  processUpdate: (models, options) -&amp;gt;
    list = this
    _.each models, (model) -&amp;gt;
      id = model.id
      original_model = list.get(id)
      original_model.set(model)

  # Called by our controller when the hash tag changes.
  # We simply fire an event indicating the term has changed, and any view
  # that is interested will handle the work of hiding or showing elements.
  filter: (term) -&amp;gt;
    this.trigger 'filter:change', term&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;I struggled with this for a little while, as Backbone is really designed to help where CRUD and REST are in heavy use. For example, a call to &lt;code&gt;RealmList.fetch()&lt;/code&gt; replaces all the models it holds with new models rather than updating the old models. This wasn’t exactly what I wanted, and since I had to update the entire list of realms via JSONP every time, I did a bit of hackery to overide the collection’s &lt;code&gt;refresh&lt;/code&gt; function &lt;em&gt;after&lt;/em&gt; the initial download.&lt;/p&gt;

&lt;p&gt;The other thing to note here is the &lt;code&gt;_.bindAll&lt;/code&gt; method. This is an &lt;a href=&quot;http://documentcloud.github.com/underscore/&quot;&gt;Underscore.js&lt;/a&gt; method (Backbone depends on Underscore) that ensures that anytime any of the named methods are invoked, they are called in the context of the current object (so &lt;code&gt;this&lt;/code&gt; always refers to the object where the method lives).&lt;/p&gt;

&lt;h2 id=&quot;realm-view&quot;&gt;Realm View&lt;/h2&gt;

&lt;p&gt;Next up is the view for a single realm; that is, one instance of a server in the list.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/924755.js?file=realm_view.coffee&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;window.RealmView = Backbone.View.extend
  tagName:  &amp;quot;div&amp;quot;
  template: _.template $(&amp;quot;#realm_template&amp;quot;).html()

  initialize: -&amp;gt;
    _.bindAll this, 'render', 'show', 'hide'
    # Whenever the data changes, the view with automatically re-render itself.
    this.model.bind 'change', this.render
    this.model.view = this

  # Render a single realm based on the template embedded in the HTML.
  render: -&amp;gt;
    $(this.el).html(this.template(this.model.toJSON()))
    this

  show: -&amp;gt;
    $(this.el).show()

  hide: -&amp;gt;
    $(this.el).hide()&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;Notice the call to &lt;code&gt;_.template&lt;/code&gt; when defining the view’s template. This is another Underscore method; it compiles JavaScript templates into functions that can be used later for rendering by passing in a context object to fill in values. Here, I created a hidden &lt;code&gt;div&lt;/code&gt; on the page, and read that HTML in to the template. In a larger app, I would probably use &lt;a href=&quot;https://github.com/pvande/Milk&quot;&gt;Milk&lt;/a&gt; for rendering templates.&lt;/p&gt;

&lt;p&gt;Also, it’s easy to miss the magic here; it’s really only one line:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;this.model.bind 'change', this.render
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This line of code binds its model’s &lt;code&gt;change&lt;/code&gt; event to the view’s &lt;code&gt;render&lt;/code&gt; element; the end result is that the view will automatically re-render itself any time its model’s data changes.&lt;/p&gt;

&lt;h2 id=&quot;application-view&quot;&gt;Application View&lt;/h2&gt;

&lt;p&gt;Finally we get to the view for the application; while it’s a bit longer than the other objects, it’s actually relatively simple, mostly taking responsibility for binding various UI changes to events from the realm list.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/924755.js?file=app_view.coffee&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;window.AppView = Backbone.View.extend
  el: $(&amp;quot;#main&amp;quot;)
  events:
    &amp;quot;keyup input&amp;quot;: &amp;quot;search&amp;quot;

  initialize: -&amp;gt;
    _.bindAll this, 'addOne', 'addAll', 'search', 'initSearch', 'filter', 'startLoading', 'stopLoading', 'updateTime'
    Realms.bind 'refresh',       this.addAll
    Realms.bind 'refresh:start', this.startLoading
    Realms.bind 'refresh:end',   this.stopLoading
    Realms.bind 'refresh:end',   this.updateTime
    Realms.bind 'filter:change', this.filter
    Realms.update()
    this.initSearch()

  # Add a single realm to the page.
  addOne: (realm) -&amp;gt;
    view = new RealmView(model: realm)
    this.el.append view.render().el

  # Add an entire list of realms to the page.
  # Deletages to this.addOne.
  addAll: -&amp;gt;
    view = this
    _.each Realms.models, (realm) -&amp;gt;
      unless realm.view?
        view.addOne realm
    # Now that the initial data is shown, start the controller's routing.
    Backbone.history.start()

  # Called when the &amp;quot;keyup&amp;quot; event is fired from the input box.
  # Sets the hash tag, which the controller picks up on and fires
  # events to ask the app to filter based on the input.
  search: -&amp;gt;
    window.location.hash = this.$(&amp;quot;input&amp;quot;).val()

  # Set the initial value of the search box to be whatever is in the URL.
  initSearch: -&amp;gt;
    this.$(&amp;quot;input&amp;quot;).val(window.location.hash.substring(1))
    this.$(&amp;quot;input&amp;quot;).focus()

  # Called when the realm list's filter:change event is triggered.
  # Iterates over the realms to see if each matches the search value.
  filter: (term) -&amp;gt;
    this.$(&amp;quot;input&amp;quot;).val(term)
    if term == &amp;quot;&amp;quot;
      this.$(&amp;quot;#reset&amp;quot;).hide()
    else
      this.$(&amp;quot;#reset&amp;quot;).show()
    Realms.each (realm) -&amp;gt;
      if realm.get('name').startsWith(term)
        realm.view.show()
      else
        realm.view.hide()

  startLoading: -&amp;gt;
    this.$(&amp;quot;#loading img&amp;quot;).show()

  stopLoading: -&amp;gt;
    this.$(&amp;quot;#loading img&amp;quot;).hide()

  updateTime: -&amp;gt;
    now      = new Date
    hours    = now.getHours()
    minutes  = now.getMinutes()
    seconds  = now.getSeconds()
    meridian = if hours &amp;lt; 12 then &amp;quot;AM&amp;quot; else &amp;quot;PM&amp;quot;

    hours   -= 12 if hours &amp;gt; 12
    hours    = 12 if hours == 0
    minutes  = &amp;quot;0#{minutes}&amp;quot; if minutes &amp;lt; 10
    seconds  = &amp;quot;0#{seconds}&amp;quot; if seconds &amp;lt; 10
    this.$(&amp;quot;#time span&amp;quot;).text(&amp;quot;#{hours}:#{minutes}:#{seconds} #{meridian}&amp;quot;)&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;It’s also primary responsible for handling the search functionality for the app, iterating over the list of realms and checking to see if the name starts with the serch string, and hiding or showing the views accordingly. It does this when it receives the &lt;code&gt;filter:change&lt;/code&gt; event fired from &lt;code&gt;RealmList.filter&lt;/code&gt;. But how does that method know when to fire that event? The answer comes from our last object, the controller.&lt;/p&gt;

&lt;h2 id=&quot;controller&quot;&gt;Controller&lt;/h2&gt;

&lt;p&gt;The controller is analagous to the router in a traditional Rails app; it handles changes in the hash string. Here’s our controller:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/924755.js?file=controller.coffee&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;window.Controller = Backbone.Controller.extend
  routes:
    &amp;quot;:realm&amp;quot;: &amp;quot;realm&amp;quot;

  # Match any string in the hash tag to be the name of a realm to search for.
  realm: (realm)-&amp;gt;
    Realms.filter(realm)&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;The controller simply takes any hash string and passes it on to the realm list, which then fires the necessary event so that the view does the filtering.&lt;/p&gt;

&lt;h1 id=&quot;in-conclusion&quot;&gt;In Conclusion&lt;/h1&gt;

&lt;p&gt;I hope this post has given you a glimpse into the power of Backbone (and the syntax of CoffeeScript). There’s a bit more code I didn’t go over (and parts of the code that I did show that I glossed over). Please feel free to take a look at the &lt;a href=&quot;https://github.com/BinaryMuse/wow-realm-status-js/blob/gh-pages/js/app.coffee#files&quot;&gt;complete CoffeeScript source&lt;/a&gt; for the app; you can also find a &lt;a href=&quot;https://github.com/BinaryMuse/wow-realm-status-js/blob/d05a70e3222700d28d8a5ff597b56859cc08428c/js/app.coffee&quot;&gt;snapshot of the code&lt;/a&gt; from the time I wrote this post, and you can check out the &lt;a href=&quot;https://github.com/BinaryMuse/wow-realm-status-js&quot;&gt;entire project’s source&lt;/a&gt; if you’re interested). Don’t hesitate to comment here or shoot me an email if you have any questions.&lt;/p&gt;

&lt;p&gt;It’s becoming incresingly apparent that JavaScript and other client-side technologies are where the real power is in modern web apps; be sure you leverage the tools necessary to keep your JavaScript just as clean and decoupled as your server-side code!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Stack Overflow can Make You a Better Learner, Too</title>
   <link href="http://brandontilley.com/2011/02/06/stack-overflow-can-make-you-a-better-learner-too.html"/>
   <updated>2011-02-06T03:58:00-08:00</updated>
   <id>http://brandontilley.com/2011/02/06/stack-overflow-can-make-you-a-better-learner-too</id>
   <content type="html">&lt;p&gt;Jeff Atwood recently &lt;a href=&quot;http://www.codinghorror.com/blog/2011/02/how-to-write-without-writing.html&quot;&gt;posted on his blog&lt;/a&gt;, Coding Horror, about how asking and answering questions on &lt;a href=&quot;http://stackoverflow.com/&quot;&gt;Stack Overflow&lt;/a&gt;, the community-driven programmer question and answer site, can make you a better writer. It’s a good read with a good point, and I completely agree. However, over the past few weeks, as I’ve tried to be more engaged with Stack Overflow by finding questions that I can answer, I’ve learned something else: Stack Overflow can make you a better &lt;em&gt;learner&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;I usually only utilize Stack Overflow for asking questions when I feel I’ve hit a dead-end with Google–when I feel I’ve exhausted my other options and I &lt;a href=&quot;http://stackoverflow.com/questions/2533892/running-a-java-daemon-with-a-gwt-front-end-served-by-embedded-jetty&quot;&gt;just can’t find an answer to the problem I’m having&lt;/a&gt;. In that way alone, I feel Stack Overflow has changed the way I look for answers to a problem. I tend to search for longer and in more ways before posting to Stack Overflow.&lt;/p&gt;

&lt;p&gt;Recently, though, I’ve been learning a lot from &lt;em&gt;answering&lt;/em&gt; questions. That sounds counter-intuitive, I know. How can you answer a question unless you already know the answer? And the answer, of course, is that you find it. That is where I feel Stack Overflow has helped me the most. By finding questions (usually related to topics I’m interested in) that I don’t know the answer to and finding the answer, I’ve learned new ways of finding answers. In particular, I’m much less intimidated than I used to be about &lt;a href=&quot;http://stackoverflow.com/questions/4911191/preventing-paperclip-from-deleting-overwriting-attachments-on-update#4911386&quot;&gt;reading source code written by other people&lt;/a&gt;, which is an &lt;em&gt;excellent&lt;/em&gt; way to learn about software.&lt;/p&gt;

&lt;p&gt;The other way I feel Stack Overflow has changed the way I think is by exposing me to problems I wouldn’t necessarily come up against in my own day-to-day coding. People have a lot of potentially &lt;a href=&quot;http://stackoverflow.com/search?q=weird+problem&quot;&gt;weird problems&lt;/a&gt; on Stack Overflow, and reading them and trying to come up with an answer expands my capabilities in ways that I otherwise would never have happened upon.&lt;/p&gt;

&lt;p&gt;So even if the users with thousands of rep and super-detailed answers intimidate you a little, I recommend taking some time each day and trying to answer some questions for people on Stack Overflow. Who knows what you’ll learn?&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Gist Tag for Jekyll</title>
   <link href="http://brandontilley.com/2011/01/30/gist-tag-for-jekyll.html"/>
   <updated>2011-01-30T23:58:00-08:00</updated>
   <id>http://brandontilley.com/2011/01/30/gist-tag-for-jekyll</id>
   <content type="html">&lt;p&gt;One of the many reasons I &lt;a href=&quot;/2011/01/30/so-long-wordpress.html&quot;&gt;moved away from WordPress&lt;/a&gt; was to make it easier to support code-laden posts. &lt;a href=&quot;https://gist.github.com/&quot;&gt;Gists&lt;/a&gt; have been a favored way of incorporating code into posts (and automatically keeping them up to date!), but WordPress didn’t show the &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag in its editor, making it difficult edit the document around them, especially in posts with several code sections.&lt;/p&gt;

&lt;p&gt;While Jekyll makes it crazy-easy to insert the necessary tags into your documents, there’s still one small problem: people who read the posts in an RSS reader miss out on the code-goodness! Sure, you can toss a quick &lt;code&gt;&amp;lt;noscript&amp;gt;&lt;/code&gt; in there with a link to the post or to the Gist, but that feels like cheating. So, I wrote a Fluid tag for Jekyll to take care of the problem:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/803483.js?file=gist_tag.rb&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;require 'cgi'
require 'digest/md5'
require 'net/https'
require 'uri'

module Jekyll
  class GistTag &amp;lt; Liquid::Tag
    def initialize(tag_name, text, token)
      super
      @text           = text
      @cache_disabled = false
      @cache_folder   = File.expand_path &amp;quot;../_gist_cache&amp;quot;, File.dirname(__FILE__)
    end

    def render(context)
      if parts = @text.match(/([\d]*) (.*)/)
        gist, file = parts[1].strip, parts[2].strip
        script_url = script_url_for gist, file
        code       = get_cached_gist(gist, file) || get_gist_from_web(gist, file)
        html_output_for script_url, code
      else
        &amp;quot;&amp;quot;
      end
    end

    def html_output_for(script_url, code)
      code = CGI.escapeHTML code
      &amp;quot;&amp;lt;script src='#{script_url}'&amp;gt;&amp;lt;/script&amp;gt;&amp;lt;noscript&amp;gt;&amp;lt;pre&amp;gt;&amp;lt;code&amp;gt;#{code}&amp;lt;/code&amp;gt;&amp;lt;/pre&amp;gt;&amp;lt;/noscript&amp;gt;&amp;quot;
    end

    def script_url_for(gist_id, filename)
      &amp;quot;https://gist.github.com/#{gist_id}.js?file=#{filename}&amp;quot;
    end

    def get_gist_url_for(gist, file)
      &amp;quot;https://gist.github.com/raw/#{gist}/#{file}&amp;quot;
    end

    def cache(gist, file, data)
      cache_file = get_cache_file_for gist, file
      File.open(cache_file, &amp;quot;w&amp;quot;) do |io|
        io.write data
      end
    end

    def get_cached_gist(gist, file)
      return nil if @cache_disabled
      cache_file = get_cache_file_for gist, file
      File.read cache_file if File.exist? cache_file
    end

    def get_cache_file_for(gist, file)
      bad_chars = /[^a-zA-Z0-9\-_.]/
      gist      = gist.gsub bad_chars, ''
      file      = file.gsub bad_chars, ''
      md5       = Digest::MD5.hexdigest &amp;quot;#{gist}-#{file}&amp;quot;
      File.join @cache_folder, &amp;quot;#{gist}-#{file}-#{md5}.cache&amp;quot;
    end

    def get_gist_from_web(gist, file)
      gist_url          = get_gist_url_for gist, file
      raw_uri           = URI.parse gist_url
      https             = Net::HTTP.new raw_uri.host, raw_uri.port
      https.use_ssl     = true
      https.verify_mode = OpenSSL::SSL::VERIFY_NONE
      request           = Net::HTTP::Get.new raw_uri.request_uri
      data              = https.request request
      data              = data.body
      cache gist, file, data unless @cache_disabled
      data
    end
  end

  class GistTagNoCache &amp;lt; GistTag
    def initialize(tag_name, text, token)
      super
      @cache_disabled = true
    end
  end
end

Liquid::Template.register_tag('gist', Jekyll::GistTag)
Liquid::Template.register_tag('gistnocache', Jekyll::GistTagNoCache)
&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;(The above Gist is being shown with the Gist tag; how very meta.)&lt;/p&gt;

&lt;p&gt;The code takes a Fluid tag in the form of &lt;code&gt;{% gist gist-number file-name %}&lt;/code&gt; and inserts the necessary &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tags into the document to display the given file from the given Gist. However, it also downloads the raw form of the Gist and inserts it into a &lt;code&gt;&amp;lt;noscript&amp;gt;&amp;lt;pre&amp;gt;&amp;lt;code&amp;gt;&lt;/code&gt; block. It also caches the contents of the Gist into the &lt;code&gt;_gist_cache&lt;/code&gt; folder of your Jekyll site (which should be added to your &lt;code&gt;.gitignore&lt;/code&gt; file, etc) to make future compiles faster.&lt;/p&gt;

&lt;p&gt;If you are rapidly iterating over multiple commits in your gist, you can use the &lt;code&gt;gistnocache&lt;/code&gt; tag; taking the form &lt;code&gt;{% gistnocache gist-number file-name %}&lt;/code&gt;, this tag does the exact same thing but skips reading from or writing to the Gist cache. Once you’re happy with your Gist, you can change the &lt;code&gt;gistnocache&lt;/code&gt; tag to a regular &lt;code&gt;gist&lt;/code&gt; tag. Of course, there’s always the chance that you need to remove a specific cached Gist from the cache; in that case, the files in &lt;code&gt;_gist_cache&lt;/code&gt; are named intelligently to help you locate the file you need to delete.&lt;/p&gt;

&lt;p&gt;Overall, it seems to be working fairly well. I hope this is of some use to others! Please let me know in the comments to this post or the comments to the Gist if you have any problems or suggestions.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>So Long, WordPress</title>
   <link href="http://brandontilley.com/2011/01/30/so-long-wordpress.html"/>
   <updated>2011-01-30T03:44:00-08:00</updated>
   <id>http://brandontilley.com/2011/01/30/so-long-wordpress</id>
   <content type="html">&lt;p&gt;WordPress has served me well for a long time. I’ve used it on multiple sites over the years. But I’ve found, lately, that it just feels big and bloated. I want something small, lean, and customizable. I want something that’ll let me focus on creating content and stay out of the way. That something is &lt;a href=&quot;https://github.com/mojombo/jekyll&quot;&gt;Jekyll&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Jekyll brings, to my mind, several advantages:&lt;/p&gt;

&lt;h1 id=&quot;static-content&quot;&gt;Static Content&lt;/h1&gt;

&lt;p&gt;Jekyll is described by its creator as “&lt;a href=&quot;http://tom.preston-werner.com/2008/11/17/blogging-like-a-hacker.html&quot;&gt;blogging like a hacker&lt;/a&gt;.” At it’s most basic level, Jekyll is a static site generator. It takes HTML, Markdown, Textile and others and compiles it into static HTML. That static HTML is then fit to be served and cached like any other HTML. No server-side processing required!&lt;/p&gt;

&lt;h1 id=&quot;simplicity&quot;&gt;Simplicity&lt;/h1&gt;

&lt;p&gt;Jekyll is beautiful and elegant in its simplicity. Write posts in your favorite text editor in your favorite format. Store them in your Git repository for built-in backup. Create branches as you work on future posts. And publishing is as easy as an rsync to your server of choice.&lt;/p&gt;

&lt;h1 id=&quot;flexibility&quot;&gt;Flexibility&lt;/h1&gt;

&lt;p&gt;Jekyll imposes very few rules on you. Any file with a &lt;a href=&quot;https://github.com/mojombo/jekyll/wiki/yaml-front-matter&quot;&gt;YAML front matter block&lt;/a&gt; is processed by Jekyll, making it easy to provide RSS feeds and other “special” files. Jekyll’s &lt;a href=&quot;http://www.liquidmarkup.org/&quot;&gt;Liquid&lt;/a&gt; layout provides plenty of flexibility without the gross (IMO) “&lt;a href=&quot;http://codex.wordpress.org/The_Loop&quot;&gt;WordPress Loop&lt;/a&gt;”.&lt;/p&gt;

&lt;p&gt;So, over the next few days or weeks, I’ll be moving some of the posts from my &lt;a href=&quot;http://binarymuse.net/&quot;&gt;old blog&lt;/a&gt; over to this one. Be sure to &lt;a href=&quot;/atom.xml&quot;&gt;resubscribe to the feed&lt;/a&gt;, as the URL has changed!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Serving Rails Apps with RVM, Nginx, Unicorn and Upstart</title>
   <link href="http://brandontilley.com/2011/01/29/serving-rails-apps-with-rvm-nginx-unicorn-and-upstart.html"/>
   <updated>2011-01-29T13:49:00-08:00</updated>
   <id>http://brandontilley.com/2011/01/29/serving-rails-apps-with-rvm-nginx-unicorn-and-upstart</id>
   <content type="html">&lt;p&gt;Ever since reading &lt;a href=&quot;https://github.com/blog/517-unicorn&quot;&gt;GitHub’s blog post on Unicorn&lt;/a&gt;, I’ve been interested in trying it out. This post will document the process I used to get Unicorn serving a Rails application behind Nginx, with RVM managing Ruby. If you’ve read GitHub’s post, some of the config will look very familiar. Ideally, though, you should be able to follow this post from start to finish and have a working setup going.&lt;/p&gt;

&lt;h1 id=&quot;introduction&quot;&gt;Introduction&lt;/h1&gt;

&lt;p&gt;I installed this setup on Ubuntu 10.04 LTS Server Edition, 64-bit. You should be able to follow along pretty well on any sane system; that being said, I do use Upstart to manage the services toward the end of the guide. If you don’t use Upstart, you will need to substitute in your own SysVinit scripts (or scripts for whatever you use instead).&lt;/p&gt;

&lt;p&gt;In a few listings, I use curl with Gist URLs to fetch the contents of files; the contents of these files are shown below the shell commands, for reference.&lt;/p&gt;

&lt;h1 id=&quot;installing-rvm&quot;&gt;Installing RVM&lt;/h1&gt;

&lt;p&gt;Since we’ll use RVM to manage our Rubies and gemsets on the server, we’ll start with a server-wide install of RVM. We’ll start out by installing curl and git, if necessary, then RVM, and finally the other packages RVM asks us to install. (Be sure to pay attention to these; you can view them again via &lt;code&gt;rvm notes&lt;/code&gt;. You may need to install additional packages for your distro of Linux or for the Rubies you wish to use). I’m using Ruby 1.9.2-p136 here.&lt;/p&gt;

&lt;p&gt;We’ll also take care to add the current user to the ‘rvm’ group. Finally, we’ll create a user called ‘unicorn’ to own our test application, later.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/802568.js?file=00_rvm.sh&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;# Install RVM and dependencies
sudo aptitude install curl git-core
sudo bash &amp;lt; &amp;lt;( curl -L http://bit.ly/rvm-install-system-wide )
sudo aptitude install build-essential bison openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev
sudo adduser `whoami` rvm
echo 'source /usr/local/lib/rvm' &amp;gt;&amp;gt; ~/.bashrc
# Set up users and groups
sudo useradd --home /var/www --create-home --groups rvm unicorn &amp;amp;&amp;amp; sudo chmod g+w /var/www
sudo adduser `whoami` unicorn
#
# &amp;gt;&amp;gt; Log out and back in to SSH, open a new shell, etc. -- something to reload your environment
#
# Install Ruby 1.9.2-p136 and make it default
rvm install ruby-1.9.2-p136
# Make a sandwich while you wait (or have someone make you one: http://xkcd.com/149/)
rvm use ruby-1.9.2-p136 --default&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;h1 id=&quot;installing-and-configuring-nginx&quot;&gt;Installing and Configuring Nginx&lt;/h1&gt;

&lt;p&gt;For simplicity’s sake, we’ll be using Nginx from APT. To make sure we’re up to date, we’ll use Nginx’s PPA.&lt;/p&gt;

&lt;p&gt;You can see in the configuration file that I’ve jumped the gun and included the location of the shared socket we’ll use with our Unicorn application.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/802568.js?file=01_nginx.sh&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;# Install Nginx
sudo bash -c 'echo &amp;quot;deb http://ppa.launchpad.net/nginx/stable/ubuntu $(lsb_release -cs) main&amp;quot; &amp;gt; /etc/apt/sources.list.d/nginx-stable-$(lsb_release -cs).list'
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C300EE8C &amp;amp;&amp;amp; sudo aptitude update
sudo aptitude install nginx
sudo bash -c 'curl -L https://gist.github.com/raw/802568/3a62636146eb2615cf42081b2574e8602d199658/nginx.conf &amp;gt; /etc/nginx/nginx.conf'&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;&lt;code&gt;/etc/nginx/nginx.conf&lt;/code&gt;:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/802568.js?file=etc_nginx.conf&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;worker_processes 1;
user www-data www-data;

pid /tmp/nginx.pid;
error_log /tmp/nginx.error.log;

events {
  worker_connections 1024;
  accept_mutex off;
}

http {
  include mime.types;
  default_type application/octet-stream;
  access_log /tmp/nginx.access.log combined;

  sendfile on;
  tcp_nopush on;
  tcp_nodelay off;

  gzip on;
  gzip_http_version 1.0;
  gzip_proxied any;
  gzip_min_length 500;
  gzip_disable &amp;quot;MSIE [1-6]\.&amp;quot;;
  gzip_types text/plain text/html text/xml text/css
             text/comma-separated-values
             text/javascript application/x-javascript
             application/atom+xml;

  upstream unicorn_test {
    server unix:/var/www/test_app/tmp/sockets/unicorn.sock fail_timeout=0;
  }

  server {
    listen 80;
    client_max_body_size 4G;
    server_name _;

    keepalive_timeout 5;

    root /var/www/test_app/public;

    location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;

      if (!-f $request_filename) {
        proxy_pass http://unicorn_test;
        break;
      }
    }

    error_page 500 502 503 504 /500.html;
    location = /500.html {
      root /var/www/test_app/public;
    }
  }
}&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;h1 id=&quot;configuring-upstart-for-nginx&quot;&gt;Configuring Upstart for Nginx&lt;/h1&gt;

&lt;p&gt;If you don’t use Upstart, or you don’t want to use Upstart, feel free to skip this section. By default, you can start Nginx with &lt;code&gt;sudo /etc/init.d/nginx start&lt;/code&gt;.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/802568.js?file=02_nginx_upstart.sh&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;sudo rm /etc/init.d/nginx
for file in $(ls /etc/rc*/*nginx); do sudo rm $file; done
sudo bash -c 'curl -L https://gist.github.com/raw/802568/e210f8754abdf137027daeb4c41db8cc301b36ad/nginx.conf &amp;gt; /etc/init/nginx.conf'
sudo start nginx&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;&lt;code&gt;/etc/init/nginx.conf&lt;/code&gt;:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/802568.js?file=init_nginx.conf&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;description &amp;quot;nginx http daemon&amp;quot;

start on runlevel [2]
stop on runlevel [016]

console owner

exec /usr/sbin/nginx -c /etc/nginx/nginx.conf -g &amp;quot;daemon off;&amp;quot;

respawn&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;h1 id=&quot;creating-a-sample-rails-application&quot;&gt;Creating a Sample Rails Application&lt;/h1&gt;

&lt;p&gt;Now we’ll create a test Rails application in /var/www/test_app. We’ll use a gemset called rails_app to demonstrate Unicorn’s ability to figure out which gemset it should use for our application (for more details on this, check out step four in &lt;a href=&quot;/2011/01/29/rvm-unicorn-and-upstart.html&quot;&gt;my earlier post on Unicorn and Upstart&lt;/a&gt;). For this to work, we’ll also create an RVM wrapper for Unicorn. And, of course, don’t forget your config/unicorn.rb file.&lt;/p&gt;

&lt;p&gt;Again, we’ll use Upstart to start and manage our Unicorn process, but you can use whatever you’d like. If you just want to test it out, try running &lt;code&gt;unicorn -c /var/www/test_app/config/unicorn.rb&lt;/code&gt; from the ‘global’ gemset.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/802568.js?file=03_sample_app.sh&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;# Install Unicorn in the global gemset, and create a wrapper (yo yo yo in the hooouuuuuse!?)
rvm use ruby-1.9.2-p136@global
gem install unicorn --no-ri --no-rdoc
rvm wrapper ruby-1.9.2-p136 r192 unicorn
# Create and switch to a new gemset
rvm gemset create rails_app &amp;amp;&amp;amp; rvm gemset use rails_app
gem install rails --no-ri --no-rdoc
# Create a sample Rails application
cd /var/www
rails new test_app
echo 'rvm use ruby-1.9.2-p136@rails_app --create' &amp;gt; test_app/.rvmrc
cd test_app
#
# &amp;gt;&amp;gt; Accept the .rvmrc warning
#
echo &amp;quot;gem 'unicorn'&amp;quot; &amp;gt;&amp;gt; Gemfile &amp;amp;&amp;amp; bundle install
curl -L https://gist.github.com/raw/802568/998ac7c702e43d600f94fc3ee63ea05179315a0d/unicorn.rb &amp;gt; config/unicorn.rb
sudo bash -c 'curl -L https://gist.github.com/raw/802568/ee3f5f320c34ec2e1d1b55521776d7dccd9140d4/test_app.conf &amp;gt; /etc/init/test_app.conf'
sudo start test_app&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;&lt;code&gt;/etc/init/test_app.conf&lt;/code&gt;:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/802568.js?file=test_app.conf&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;description &amp;quot;Test rails application&amp;quot;

start on runlevel [2]
stop on runlevel [016]

console owner

exec /usr/local/rvm/bin/r192_unicorn -c /var/www/test_app/config/unicorn.rb

respawn&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;&lt;code&gt;/var/www/test_app/config/unicorn.rb&lt;/code&gt;:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/802568.js?file=unicorn.rb&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;APP_ROOT = File.expand_path(File.dirname(File.dirname(__FILE__)))

if ENV['MY_RUBY_HOME'] &amp;amp;&amp;amp; ENV['MY_RUBY_HOME'].include?('rvm')
  begin
    rvm_path = File.dirname(File.dirname(ENV['MY_RUBY_HOME']))
    rvm_lib_path = File.join(rvm_path, 'lib')
    $LOAD_PATH.unshift rvm_lib_path
    require 'rvm'
    RVM.use_from_path! APP_ROOT
  rescue LoadError
    raise &amp;quot;RVM ruby lib is currently unavailable.&amp;quot;
  end
end

ENV['BUNDLE_GEMFILE'] = File.expand_path('../Gemfile', File.dirname(__FILE__))
require 'bundler/setup'

worker_processes 4
working_directory APP_ROOT

preload_app true

timeout 30

listen APP_ROOT + &amp;quot;/tmp/sockets/unicorn.sock&amp;quot;, :backlog =&amp;gt; 64

pid APP_ROOT + &amp;quot;/tmp/pids/unicorn.pid&amp;quot;

stderr_path APP_ROOT + &amp;quot;/log/unicorn.stderr.log&amp;quot;
stdout_path APP_ROOT + &amp;quot;/log/unicorn.stdout.log&amp;quot;

before_fork do |server, worker|
  defined?(ActiveRecord::Base) &amp;amp;&amp;amp; ActiveRecord::Base.connection.disconnect!

  old_pid = RAILS_ROOT + '/tmp/pids/unicorn.pid.oldbin'
  if File.exists?(old_pid) &amp;amp;&amp;amp; server.pid != old_pid
    begin
      Process.kill(&amp;quot;QUIT&amp;quot;, File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
      puts &amp;quot;Old master alerady dead&amp;quot;
    end
  end
end

after_fork do |server, worker|
  defined?(ActiveRecord::Base) &amp;amp;&amp;amp; ActiveRecord::Base.establish_connection
end&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;h1 id=&quot;profit&quot;&gt;Profit!&lt;/h1&gt;

&lt;p&gt;And that’s that! Upstart will manage both Nginx and Unicorn (although either could benefit from something like Monit or God, but I’ll leave that as an exercise for the reader and/or a future blog post).&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>RVM, Unicorn and Upstart</title>
   <link href="http://brandontilley.com/2011/01/29/rvm-unicorn-and-upstart.html"/>
   <updated>2011-01-29T07:01:00-08:00</updated>
   <id>http://brandontilley.com/2011/01/29/rvm-unicorn-and-upstart</id>
   <content type="html">&lt;p&gt;I had a heck of a time this week trying to figure out how to get Upstart to start an instance of Unicorn due to the fact that Ruby was being managed with RVM. I finally realized I had been going about it the wrong way, and that RVM provided the tool that I needed: wrapper scripts. I opted to use a single wrapper script for the version of Ruby I was running, and to let Unicorn decide what gemset to use based on the .rvmrc file in the project. Here’s the whole process:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Make sure Unicorn is installed in the global gemset&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;rvm use ruby-1.9.2-p136@global
gem install unicorn
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Create a wrapper script for Unicorn&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;rvm wrapper ruby-1.9.2-p136 r192 unicorn
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Modify your Upstart configuration file’s “exec” line&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;exec /usr/local/rvm/bin/r192_unicorn -c /path/to/app/config/unicorn.rb
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Modify your config/unicorn.rb file&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use the following code at the top of your unicorn.rb file to tell Unicorn to set up the environment based on the .rvmrc file in the root of the project:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if ENV['MY_RUBY_HOME'] &amp;amp;&amp;amp; ENV['MY_RUBY_HOME'].include?('rvm')
  begin
    rvm_path     = File.dirname(File.dirname(ENV['MY_RUBY_HOME']))
    rvm_lib_path = File.join(rvm_path, 'lib')
    $LOAD_PATH.unshift rvm_lib_path
    require 'rvm'
    RVM.use_from_path! File.dirname(File.dirname(__FILE__))
  rescue LoadError
    raise &quot;The RVM Ruby library is not available.&quot;
  end
end

ENV['BUNDLE_GEMFILE'] = File.expand_path('../Gemfile', File.dirname(__FILE__))
require 'bundler/setup'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Start your service&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now you should be able to start your Unicorn app via &lt;code&gt;sudo service start appname&lt;/code&gt;.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>git diff with Color in the Browser</title>
   <link href="http://brandontilley.com/2010/09/25/git-diff-with-color-in-the-browser.html"/>
   <updated>2010-09-25T06:22:00-07:00</updated>
   <id>http://brandontilley.com/2010/09/25/git-diff-with-color-in-the-browser</id>
   <content type="html">&lt;p&gt;If you’re anything like me (I feel sorry for you), then you use git diff pretty heavily. I like making sure I’m definitely committing what I think I’m committing, and I also like to verify my indentation, trailing whitespace, line endings, and so on are correct before I commit. I don’t tend to use many GUI tools for Git, so I end up paging through terminal output. While this works fine, I’ve discovered a solution I like more.&lt;/p&gt;

&lt;p&gt;It involves &lt;a href=&quot;http://rtomayko.github.com/bcat/&quot;&gt;Ryan Tomayko’s bcat&lt;/a&gt;, which is a pipe-to-browser utility. Since it supports ANSI/VT100 escape sequences, we even get nice color formatting. After &lt;a href=&quot;http://github.com/rtomayko/bcat/blob/master/INSTALLING#files&quot;&gt;installing&lt;/a&gt; bcat, our options are two-fold for using it with Git:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Pipe output to bcat&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you only want to use bcat from time to time, you can easily pipe ouptut from a Git command to bcat:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git diff | bcat
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To get color, specify it as an option to git diff:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git diff --color | bcat 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;2. Set bcat as Git’s pager&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you want to use bcat for every operation Git sends to your pager, try the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;export GIT_PAGER=bcat
git diff
git log
git log --oneline --decorate
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And there you have it! Easy reviewing if your diffs in your browser. Be sure to check out the other examples on bcat’s homepage for some really neat uses!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>GWT-Wizard: A Wizard Widget for Your Project</title>
   <link href="http://brandontilley.com/2010/04/22/gwt-wizard-a-wizard-widget-for-your-project.html"/>
   <updated>2010-04-22T12:51:00-07:00</updated>
   <id>http://brandontilley.com/2010/04/22/gwt-wizard-a-wizard-widget-for-your-project</id>
   <content type="html">&lt;p&gt;I thought I would take a quick moment to preset &lt;a href=&quot;http://gwt-wizard.binarymuse.net/&quot;&gt;GWT-Wizard&lt;/a&gt;, a wizard widget I designed for GWT.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/gwt-wizard-sample.png&quot; alt=&quot;GWT-Wizard&quot; title=&quot;GWT-Wizard&quot; /&gt;&lt;/p&gt;

&lt;p&gt;GWT-Wizard is very configurable, allowing you to customize everything about the Wizard–down to creating your own custom view to plug into the widget–but also comes with a set of sane defaults that allow you to get up and running quickly. If you’re interested, &lt;a href=&quot;https://github.com/BinaryMuse/gwt-wizard&quot;&gt;check it out on GitHub&lt;/a&gt;. I have a hard time sometimes with over thinking and over planning things, so I’m trying to get code out to the open source community more. The project is still very young, but I’m using the widget in a production system for one of my projects, and I feel the codebase offers enough to be useful now.&lt;/p&gt;

&lt;p&gt;If you have any comments or questions, or are using this widget in production somewhere, I’d be very interested to hear about it!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Serving a GWT Application with an Embedded Jetty Server</title>
   <link href="http://brandontilley.com/2010/03/27/serving-a-gwt-application-with-an-embedded-jetty-server.html"/>
   <updated>2010-03-27T04:12:00-07:00</updated>
   <id>http://brandontilley.com/2010/03/27/serving-a-gwt-application-with-an-embedded-jetty-server</id>
   <content type="html">&lt;p&gt;For a new project I am interested in starting, I want to serve a GWT application with an embedded Jetty server. I wasn’t sure how to go about doing so, but it turns out it’s easier than I could ever have expected! Check it out below.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/346622.js?file=EmbeddedGwt.java&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;package net.binarymuse.EmbeddedGwt;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;

public class EmbeddedGwt {

    public static void main(String[] args) throws Throwable {

        // Create an embedded Jetty server on port 8080
        Server server = new Server(8080);

        // Create a handler for processing our GWT app
        WebAppContext handler = new WebAppContext();
        handler.setContextPath(&amp;quot;/&amp;quot;);
        handler.setWar(&amp;quot;./apps/GwtApplication.war&amp;quot;);

        // If your app isn't packaged into a WAR, you can do this instead
        WebAppContext altHandler = new WebAppContext();
        altHandler.setResourceBase(&amp;quot;./apps/GwtApplication&amp;quot;);
        altHandler.setDescriptor(&amp;quot;./apps/GwtApplication/WEB-INF/web.xml&amp;quot;);
        altHandler.setContextPath(&amp;quot;/&amp;quot;);
        altHandler.setParentLoaderPriority(true);

        // Add it to the server
        server.setHandler(handler);

        // Other misc. options
        server.setThreadPool(new QueuedThreadPool(20));

        // And start it up
        server.start();
        server.join();
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;You do, of course, need the &lt;a href=&quot;http://download.eclipse.org/jetty/&quot;&gt;Jetty jars&lt;/a&gt; (I used the ones from the ‘lib’ folder in the Jetty distribution) in your classpath.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Engineer Thinking and the Art of Software Engineering</title>
   <link href="http://brandontilley.com/2010/03/12/engineer-thinking-and-the-art-of-software-engineering.html"/>
   <updated>2010-03-12T02:06:00-08:00</updated>
   <id>http://brandontilley.com/2010/03/12/engineer-thinking-and-the-art-of-software-engineering</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://mattgemmell.com/2010/03/09/engineer-thinking&quot;&gt;Matt Gemmell brings up an interesting point&lt;/a&gt; in a recent blog post regarding user choice and defaults in software design.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;But a problem arises when you allow precision-based design principles to hinder user experience. All too often, when faced with a decision about how to implement certain functionality, engineers take the extreme position that:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;ol&gt;
    &lt;li&gt;A feature must be exactly what 100% of users want.&lt;/li&gt;
    &lt;li&gt;If the above isn’t true (and it almost never is), the feature must be configurable.&lt;/li&gt;
  &lt;/ol&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;This binary approach is gravely wrong, and unjustly offloads decision-making onto the user of the software. We’ve all seen where this approach ends up: multi-row sets of tabs, scrolling panes of checkboxes, nested radio-buttons and a general overload of configuration.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;He goes on to talk about technical complexity and the responsibility of software to “mask uncertainty and to make the effort to provide a sensible default behavior.” However, as the post progresses, it evolves into an article that talks about the art of software engineering. One paragraph in particular really stood out to me:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;It all comes down to a question of art. Our art (that of software engineering) is not in making it work. If you see it as a significant success that you managed to name some methods, or write code that compiles and runs (or implemented a heap sort, or found the bounding box for a set of points, or parsed some XML), then your career goals are low indeed. Anyone in this industry can do that stuff, including any reasonably proficient final-year undergraduate in Computing Science. That’s core-skillset, vocational learning. You’re not aiming high enough.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This got me to thinking: how often do I put ultimate importance on making something work? I’ve always been a proponent of attention to details and good UI design, but I’ve certainly been guilty of, as Matt puts it, setting my career goals too low. Something to think about.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Current Working Git or SVN Branch on the Prompt</title>
   <link href="http://brandontilley.com/2010/02/22/current-working-git-or-snv-branch-on-the-prompt.html"/>
   <updated>2010-02-22T08:36:00-08:00</updated>
   <id>http://brandontilley.com/2010/02/22/current-working-git-or-snv-branch-on-the-prompt</id>
   <content type="html">&lt;p&gt;This is a nifty tip I picked up somewhere on the Internet to show the Git or Subversion branch you are currently working in on the command line prompt, which I modified to include your stash level. I haven’t done a ton of serious programming under Subversion, but I know with Git I’m branching all the time (&lt;a href=&quot;http://whygitisbetterthanx.com/#cheap-local-branching&quot;&gt;branches are so cheap in Git&lt;/a&gt;!). I wasn’t sure if I’d like the results before I tried it, but as it turns out, it’s even more helpful than I thought it’d be.&lt;/p&gt;

&lt;p&gt;Edit your &lt;code&gt;~/.bash_profile&lt;/code&gt; to mirror the following functions. Of course, you may change the details of PS1 to your liking; it’s the &lt;code&gt;\$(parse_git_branch)\$(parse_svn_branch)&lt;/code&gt; that’s important.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/447949.js?file=DND (blog): git on prompt.sh&quot;&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;&lt;code&gt;parse_git_branch() {
  git branch 2&amp;gt; /dev/null | sed -e '/^[^*]/d' -e &amp;quot;s/* \(.*\)/ (\1$(parse_git_stash))/&amp;quot;
}
parse_git_stash() {
  git stash list 2&amp;gt; /dev/null | wc -l | sed -e &amp;quot;s/ *\([0-9]*\)/\ \+\1/g&amp;quot; | sed -e &amp;quot;s/ \+0//&amp;quot;
}
parse_svn_branch() {
  parse_svn_url | sed -e 's#^'&amp;quot;$(parse_svn_repository_root)&amp;quot;'##g' | awk -F / '{print &amp;quot; (&amp;quot;$1 &amp;quot;/&amp;quot; $2 &amp;quot;)&amp;quot;}'
}
parse_svn_url() {
  svn info 2&amp;gt;/dev/null | grep -e '^URL*' | sed -e 's#^URL: *\(.*\)#\1#g '
}
parse_svn_repository_root() {
  svn info 2&amp;gt;/dev/null | grep -e '^Repository Root:*' | sed -e 's#^Repository Root: *\(.*\)#\1\/#g '
}

export PS1=&amp;quot;[\u \w\$(parse_git_branch)\$(parse_svn_branch)]: &amp;quot;&lt;/code&gt;&lt;/pre&gt;&lt;/noscript&gt;

&lt;p&gt;And what you end up with looks like (in this particular case):&lt;/p&gt;

&lt;p&gt;&lt;code&gt;[BinaryMuse ~/repo.git/src (FIX-15013 +2)]:&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Enjoy!&lt;/p&gt;
</content>
 </entry>
 
 
</feed>