<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Nick Gauthier</title>
  <link href="http://ngauthier.com/atom.xml" rel="self"/>
  <link href="http://ngauthier.com/"/>
  <updated>2021-10-25T14:16:40+00:00</updated>
  <id>http://ngauthier.com/</id>
  <author>
    <name>Nick Gauthier</name>
    <email>ngauthier@gmail.com</email>
  </author>
  
  
  <entry>
    <title>Rails Systems Tests with Headless Chrome on Windows Bash (WSL)</title>
    <link href="http://ngauthier.com/2017/09/rails-system-tests-with-headless-chrome-on-windows-bash-wsl.html"/>
    <updated>2017-09-08T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2017/09/rails-system-tests-with-headless-chrome-on-windows-bash-wsl</id>
    <content type="html">&lt;p&gt;I’ve been using the Windows Subsystem for Linux for a few months now, but one thing I hadn’t figured out was how to run selenium tests from it. WSL doesn’t support GUI applications, and Chrome is especially difficult to get working. So even thought I want to use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chromedriver&lt;/code&gt; with the new &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;headless&lt;/code&gt; option, Chrome still doesn’t work properly in WSL out of the box.&lt;/p&gt;

&lt;p&gt;Thanks to &lt;a href=&quot;https://twitter.com/jessfraz/status/905936903358345216&quot;&gt;a tweet from Jessie Frazelle&lt;/a&gt; in which she mentioned that you can run Windows binaries from WSL, I had the idea to give this another shot: have my Rails tests in WSL call out to &lt;em&gt;Windows chromedriver.exe&lt;/em&gt; to drive a headless browser using Windows Chrome. Turns out it works! Here’s how to do it.&lt;/p&gt;

&lt;h2 id=&quot;start-with-a-blog-of-course&quot;&gt;Start with a blog of course&lt;/h2&gt;

&lt;p&gt;So we need some kind of Rails app. I’m going to show you how to set it up so that if you just want to tinker you can try it out quickly.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
$ rails new blog
$ cd blog
$ rails generate system_test hello
$ rails db:migrate
$ rails test:system
&lt;/pre&gt;

&lt;p&gt;It should show no tests to run. Let’s write one to try it out. Edit &lt;strong&gt;test/system/hellos_test.rb&lt;/strong&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
require &quot;application_system_test_case&quot;

class HellosTest &amp;lt; ApplicationSystemTestCase
  test &quot;visiting the index&quot; do
    visit '/'
    assert page.has_content?('oh hai')
  end
end
&lt;/pre&gt;

&lt;p&gt;If you run this, it won’t work, because Selenium can’t find the chromedriver:&lt;/p&gt;

&lt;pre&gt;
$ rails test:system
Run options: --seed 9949

# Running:

E

Error:
HellosTest#test_visiting_the_index:
Selenium::WebDriver::Error::WebDriverError:  Unable to find chromedriver. Please download the server from http://chromedriver.storage.googleapis.com/index.html and place it somewhere on your PATH. More info at https://github.com/SeleniumHQ/selenium/wiki/Chr
omeDriver.

    test/system/hellos_test.rb:5:in `block in &amp;lt;class:HellosTest&amp;gt;'

Error:
HellosTest#test_visiting_the_index:
Selenium::WebDriver::Error::WebDriverError:  Unable to find chromedriver. Please download the server from http://chromedriver.storage.googleapis.com/index.html and place it somewhere on your PATH. More info at https://github.com/SeleniumHQ/selenium/wiki/Chr
omeDriver.




bin/rails test test/system/hellos_test.rb:4



Finished in 0.749730s, 1.3338 runs/s, 0.0000 assertions/s.
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
&lt;/pre&gt;

&lt;h2 id=&quot;install-chromedriver&quot;&gt;Install chromedriver&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://sites.google.com/a/chromium.org/chromedriver/&quot;&gt;Go download chromedriver from Google&lt;/a&gt;. Put it somewhere you plan on adding to your path. Like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Documents\bin&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now, add that directory to your path:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Hit the Windows key and type &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;environment&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Open the “Edit the system environment variables” app&lt;/li&gt;
  &lt;li&gt;Click “Environment Variables”.&lt;/li&gt;
  &lt;li&gt;Click “Path”&lt;/li&gt;
  &lt;li&gt;Click “Edit”&lt;/li&gt;
  &lt;li&gt;Click “New”&lt;/li&gt;
  &lt;li&gt;Click “Browse”&lt;/li&gt;
  &lt;li&gt;Browse to your directory you’re going to use (I used &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Documents\bin&lt;/code&gt;)&lt;/li&gt;
  &lt;li&gt;Click OK, OK, OK&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now &lt;strong&gt;relaunch your terminal&lt;/strong&gt; to pick up the new environment variables. You can &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;echo $PATH&lt;/code&gt; to ensure it’s on there. You should be able to run:&lt;/p&gt;

&lt;pre&gt;
$ chromedriver.exe -v
ChromeDriver 2.32.498550 (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a)
&lt;/pre&gt;

&lt;p&gt;Finally, we need to do one of two things:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Rename &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chromedriver.exe&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chromedriver&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Make a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chromedriver&lt;/code&gt; bash wrapper inside WSL&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is because Selenium looks for a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chromedriver&lt;/code&gt; binary, not &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chromedriver.exe&lt;/code&gt;. Renaming is the easiest, that’s what I did.&lt;/p&gt;

&lt;h2 id=&quot;run-it-and-go-headless&quot;&gt;Run it and go headless&lt;/h2&gt;

&lt;p&gt;If you run your tests now, it should pop open a Windows Chrome window and fail the test (because we didn’t actually write code to pass it).&lt;/p&gt;

&lt;pre&gt;
$ rails test:system
/home/nick/.gems/gems/railties-5.1.3/lib/rails/app_loader.rb:40: warning: Insecure world writable dir /mnt/c/Users/Nick/Documents/GitHub/blog in PATH, mode 040777
Run options: --seed 5589

# Running:

Puma starting in single mode...
* Version 3.10.0 (ruby 2.4.1-p111), codename: Russell's Teapot
* Min threads: 0, max threads: 1
* Environment: test
* Listening on tcp://0.0.0.0:50511
Use Ctrl-C to stop
2017-09-08 09:44:45 -0400: Rack app error handling request { GET / }
#&amp;lt;ActionController::RoutingError: No route matches [GET] &quot;/&quot;&amp;gt;
/home/nick/.gems/gems/actionpack-5.1.3/lib/action_dispatch/middleware/debug_exceptions.rb:63:in `call'
/home/nick/.gems/gems/actionpack-5.1.3/lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
/home/nick/.gems/gems/railties-5.1.3/lib/rails/rack/logger.rb:36:in `call_app'
/home/nick/.gems/gems/railties-5.1.3/lib/rails/rack/logger.rb:24:in `block in call'
/home/nick/.gems/gems/activesupport-5.1.3/lib/active_support/tagged_logging.rb:69:in `block in tagged'
/home/nick/.gems/gems/activesupport-5.1.3/lib/active_support/tagged_logging.rb:26:in `tagged'
/home/nick/.gems/gems/activesupport-5.1.3/lib/active_support/tagged_logging.rb:69:in `tagged'
/home/nick/.gems/gems/railties-5.1.3/lib/rails/rack/logger.rb:24:in `call'
/home/nick/.gems/gems/actionpack-5.1.3/lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
/home/nick/.gems/gems/actionpack-5.1.3/lib/action_dispatch/middleware/request_id.rb:25:in `call'
/home/nick/.gems/gems/rack-2.0.3/lib/rack/method_override.rb:22:in `call'
/home/nick/.gems/gems/rack-2.0.3/lib/rack/runtime.rb:22:in `call'
/home/nick/.gems/gems/activesupport-5.1.3/lib/active_support/cache/strategy/local_cache_middleware.rb:27:in `call'
/home/nick/.gems/gems/actionpack-5.1.3/lib/action_dispatch/middleware/executor.rb:12:in `call'
/home/nick/.gems/gems/actionpack-5.1.3/lib/action_dispatch/middleware/static.rb:125:in `call'
/home/nick/.gems/gems/rack-2.0.3/lib/rack/sendfile.rb:111:in `call'
/home/nick/.gems/gems/railties-5.1.3/lib/rails/engine.rb:522:in `call'
/home/nick/.gems/gems/rack-2.0.3/lib/rack/urlmap.rb:68:in `block in call'
/home/nick/.gems/gems/rack-2.0.3/lib/rack/urlmap.rb:53:in `each'
/home/nick/.gems/gems/rack-2.0.3/lib/rack/urlmap.rb:53:in `call'
/home/nick/.gems/gems/rack-2.0.3/lib/rack/builder.rb:153:in `call'
/home/nick/.gems/gems/capybara-2.15.1/lib/capybara/server.rb:44:in `call'
/home/nick/.gems/gems/puma-3.10.0/lib/puma/configuration.rb:225:in `call'
/home/nick/.gems/gems/puma-3.10.0/lib/puma/server.rb:605:in `handle_request'
/home/nick/.gems/gems/puma-3.10.0/lib/puma/server.rb:437:in `process_client'
/home/nick/.gems/gems/puma-3.10.0/lib/puma/server.rb:301:in `block in run'
/home/nick/.gems/gems/puma-3.10.0/lib/puma/thread_pool.rb:120:in `block in spawn_thread'
[Screenshot]: tmp/screenshots/failures_test_visiting_the_index.png

E

Error:
HellosTest#test_visiting_the_index:
ActionController::RoutingError: No route matches [GET] &quot;/&quot;



bin/rails test test/system/hellos_test.rb:4



Finished in 6.261807s, 0.1597 runs/s, 0.0000 assertions/s.
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
/home/nick/.gems/gems/childprocess-0.7.1/lib/childprocess/unix/process.rb:32:in `waitpid2': Invalid argument (Errno::EINVAL)
        from /home/nick/.gems/gems/childprocess-0.7.1/lib/childprocess/unix/process.rb:32:in `exited?'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:138:in `process_exited?'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:123:in `stop_process'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:83:in `ensure in stop'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:83:in `stop'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/chrome/driver.rb:69:in `quit'
        from /home/nick/.gems/gems/capybara-2.15.1/lib/capybara/selenium/driver.rb:276:in `quit'
        from /home/nick/.gems/gems/capybara-2.15.1/lib/capybara/selenium/driver.rb:32:in `block in browser'
/home/nick/.gems/gems/childprocess-0.7.1/lib/childprocess/unix/process.rb:32:in `waitpid2': Invalid argument (Errno::EINVAL)
        from /home/nick/.gems/gems/childprocess-0.7.1/lib/childprocess/unix/process.rb:32:in `exited?'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:138:in `process_exited?'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:123:in `stop_process'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:83:in `ensure in stop'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:83:in `stop'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:69:in `block in start'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/platform.rb:138:in `block in exit_hook'
&lt;/pre&gt;

&lt;p&gt;Also you’ll notice there’s an error at the end with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;waitpid2&lt;/code&gt;. I don’t know how to fix that. But it does run our test so I’m happy enough for now.&lt;/p&gt;

&lt;p&gt;Let’s pass the test. Edit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config/routes.rb&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
Rails.application.routes.draw do
  root to: 'application#index'
end
&lt;/pre&gt;

&lt;p&gt;Edit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app/views/application/index.html.erb&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
oh hai
&lt;/pre&gt;

&lt;p&gt;And run. It should pass now.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://robots.thoughtbot.com/headless-feature-specs-with-chrome&quot;&gt;Following this post from thoughtbot&lt;/a&gt; edit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;test/application_system_test_case.rb&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
require &quot;test_helper&quot;

class ApplicationSystemTestCase &amp;lt; ActionDispatch::SystemTestCase
  driven_by :headless_chrome, screen_size: [1400, 1400]
end


Capybara.register_driver :headless_chrome do |app|
  capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
    chromeOptions: { args: %w(headless disable-gpu) }
  )

  Capybara::Selenium::Driver.new app,
    browser: :chrome,
    desired_capabilities: capabilities
end
&lt;/pre&gt;

&lt;p&gt;And run it, and it’s headless! Super cool.&lt;/p&gt;

&lt;pre&gt;
$ rails test:system
/home/nick/.gems/gems/railties-5.1.3/lib/rails/app_loader.rb:40: warning: Insecure world writable dir /mnt/c/Users/Nick/Documents/GitHub/blog in PATH, mode 040777
Run options: --seed 28393

# Running:

Puma starting in single mode...
* Version 3.10.0 (ruby 2.4.1-p111), codename: Russell's Teapot
* Min threads: 0, max threads: 1
* Environment: test
* Listening on tcp://0.0.0.0:50621
Use Ctrl-C to stop
.

Finished in 4.973954s, 0.2010 runs/s, 0.2010 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
/home/nick/.gems/gems/childprocess-0.7.1/lib/childprocess/unix/process.rb:32:in `waitpid2': Invalid argument (Errno::EINVAL)
        from /home/nick/.gems/gems/childprocess-0.7.1/lib/childprocess/unix/process.rb:32:in `exited?'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:138:in `process_exited?'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:123:in `stop_process'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:83:in `ensure in stop'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:83:in `stop'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/chrome/driver.rb:69:in `quit'
        from /home/nick/.gems/gems/capybara-2.15.1/lib/capybara/selenium/driver.rb:276:in `quit'
        from /home/nick/.gems/gems/capybara-2.15.1/lib/capybara/selenium/driver.rb:32:in `block in browser'
/home/nick/.gems/gems/childprocess-0.7.1/lib/childprocess/unix/process.rb:32:in `waitpid2': Invalid argument (Errno::EINVAL)
        from /home/nick/.gems/gems/childprocess-0.7.1/lib/childprocess/unix/process.rb:32:in `exited?'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:138:in `process_exited?'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:123:in `stop_process'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:83:in `ensure in stop'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:83:in `stop'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/service.rb:69:in `block in start'
        from /home/nick/.gems/gems/selenium-webdriver-3.5.2/lib/selenium/webdriver/common/platform.rb:138:in `block in exit_hook'
&lt;/pre&gt;
</content>
  </entry>
  
  <entry>
    <title>Elm on Rails with Webpack</title>
    <link href="http://ngauthier.com/2017/08/elm-on-rails-with-webpack.html"/>
    <updated>2017-08-30T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2017/08/elm-on-rails-with-webpack</id>
    <content type="html">&lt;p&gt;Continuing from &lt;a href=&quot;/2017/08/preact-on-rails-with-webpack.html&quot;&gt;part 1: Preact on Rails with Webpack&lt;/a&gt;, today we’re going to look at how to set up Elm in front of Rails using Rails 5.1’s new webpack scaffolding.&lt;/p&gt;

&lt;p&gt;Elm is a very interesting language to me for a couple of reasons. First, I’ve been doing Go for a few years now, and I’ve found its simplicity (one way to do things), static type system, and auto formatting to be very relieving. As a programmer, I have not had to think as hard about the details of solving a problem, and instead I can just go right to solving it. Elm seems to share some of these ideas too.&lt;/p&gt;

&lt;p&gt;Elm has a formatter, like Go, so code always looks the same (and you don’t have to worry about typing it perfectly). It has a static type system that makes writing and refactoring code easier because it surfaces errors faster (at compile time) letting you skip right to behavioral errors in your code (through tests of course!) Elm also promises zero runtime errors, which sounds incredible!&lt;/p&gt;

&lt;p&gt;In my opinion, the tradeoff Elm asks in exchange for these features is that it’s an additional language to put on your stack, which comes with it’s own overhead of learning the language and maintaining the tooling as part of your build process. Additionally, Elm takes additional effort to integrate with existing JavaScript through its ports system. The ports system makes sense to me, as creating a safe barrier into the “error-free” world of Elm. But it means we’re going to have some overhead.&lt;/p&gt;

&lt;p&gt;Luckily, while Elm has its own binary tooling, they’ve made it distributable through npm and buildable through webpack, meaning that you can pretend like it’s another JavaScript framework (I mean, I guess it kind of is!) On top of that, it is a first-class citizen in the new Rails 5.1 webpack scaffolding, meaning Rails can set up Elm for us.&lt;/p&gt;

&lt;p&gt;Let’s get started.&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Similar to Part 1, you’ll need this before we continue:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Ruby &amp;gt;2.2.2 (I’m using 2.4.0)&lt;/li&gt;
  &lt;li&gt;Rails &amp;gt;5.1 (I’m using 5.1.4.rc1)&lt;/li&gt;
  &lt;li&gt;NodeJS &amp;gt;6 (I’m using 6.11.2)&lt;/li&gt;
  &lt;li&gt;Yarn &amp;gt;0.20.1 (I’m using 0.27.5)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;creating-a-new-rails-app-with-webpack-and-elm&quot;&gt;Creating a new Rails App with Webpack and Elm&lt;/h2&gt;

&lt;p&gt;Slightly different from part 1, we can use Rails’s Elm webpack scaffold to give us a jumpstart:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
rails new hello \
  --skip-action-cable \
  --skip-sprockets \
  --skip-coffee \
  --skip-javascript \
  --skip-turbolinks \
  --webpack=elm
&lt;/pre&gt;

&lt;p&gt;Note the last line, where instead of just &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;--webpack&lt;/code&gt; to setup the webpack pipeline, we can say &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;--webpack=elm&lt;/code&gt; and Rails will add Elm as a dependency and set it up with webpack to detect and package Elm files.&lt;/p&gt;

&lt;h3 id=&quot;using-webpacker--master&quot;&gt;Using Webpacker @ master&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Heads up! There’s currently a bug with automatic compilation so we’re going to use Webpack @ master&lt;/strong&gt;. Once a release &amp;gt; 2.0.0 of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rails/webpacker&lt;/code&gt; is released, you should be able to use that instead of this step.&lt;/p&gt;

&lt;p&gt;Edit our Gemfile, and modify the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;webpacker&lt;/code&gt; line to use master from GitHub:&lt;/p&gt;

&lt;pre class=&quot;prettyprint ruby&quot;&gt;
gem 'webpacker', github: 'rails/webpacker'
&lt;/pre&gt;

&lt;p&gt;Then update it:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
bundle update webpacker
&lt;/pre&gt;

&lt;p&gt;As of the writing of this post, I’m on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;master@691389f&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Finally, reinstall webpacker:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
rails webpacker:install
&lt;/pre&gt;

&lt;p&gt;(you can answer &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a&lt;/code&gt; to allow all updates)&lt;/p&gt;

&lt;h2 id=&quot;hello-elm&quot;&gt;Hello Elm&lt;/h2&gt;

&lt;p&gt;Since Webpacker sets Elm up for us automatically, all we have to do is edit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app/views/layouts/application.html.erb&lt;/code&gt; and remove the stylesheet tag and replace it with a webpack tag:&lt;/p&gt;

&lt;pre class=&quot;prettyprint html&quot;&gt;
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Hello&amp;lt;/title&amp;gt;
    &amp;lt;%= csrf_meta_tags %&amp;gt;

    &amp;lt;%= javascript_pack_tag 'hello_elm' %&amp;gt;
  &amp;lt;/head&amp;gt;

  &amp;lt;body&amp;gt;
    &amp;lt;%= yield %&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;

&lt;p&gt;The Elm Webpacker install automatically creates a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;hello_elm&lt;/code&gt; pack for us to start with as a “hello world” example. In order to see this example though, we need a page in our app. We’re going to be lazy and just add a view to the application controller:&lt;/p&gt;

&lt;p&gt;In &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config/routes.rb&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint ruby&quot;&gt;
Rails.application.routes.draw do
  root to: 'application#index'
end
&lt;/pre&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
$ mkdir app/views/application
$ touch app/views/application/index.html.erb
&lt;/pre&gt;

&lt;p&gt;Now run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rails server&lt;/code&gt; open up your app, and it should say “Hello Elm!”. Pretty easy, huh!&lt;/p&gt;

&lt;h2 id=&quot;trimming-the-fat&quot;&gt;Trimming the Fat&lt;/h2&gt;

&lt;p&gt;Webpack is great because it sets up everything we need to get started, but when using Elm it brings in a lot more than we need. First, we can start by removing old asset pipeline paths:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
rm -rf app/assets lib/assets
&lt;/pre&gt;

&lt;p&gt;Next, let’s open up &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;package.json&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint json&quot;&gt;
{
  &quot;name&quot;: &quot;hello&quot;,
  &quot;private&quot;: true,
  &quot;dependencies&quot;: {
    &quot;autoprefixer&quot;: &quot;^7.1.3&quot;,
    &quot;babel-core&quot;: &quot;^6.26.0&quot;,
    &quot;babel-loader&quot;: &quot;7.x&quot;,
    &quot;babel-plugin-syntax-dynamic-import&quot;: &quot;^6.18.0&quot;,
    &quot;babel-plugin-transform-class-properties&quot;: &quot;^6.24.1&quot;,
    &quot;babel-plugin-transform-object-rest-spread&quot;: &quot;^6.26.0&quot;,
    &quot;babel-polyfill&quot;: &quot;^6.26.0&quot;,
    &quot;babel-preset-env&quot;: &quot;^1.6.0&quot;,
    &quot;coffee-loader&quot;: &quot;^0.8.0&quot;,
    &quot;coffee-script&quot;: &quot;^1.12.7&quot;,
    &quot;compression-webpack-plugin&quot;: &quot;^1.0.0&quot;,
    &quot;css-loader&quot;: &quot;^0.28.5&quot;,
    &quot;elm&quot;: &quot;^0.18.0&quot;,
    &quot;elm-webpack-loader&quot;: &quot;^4.3.1&quot;,
    &quot;extract-text-webpack-plugin&quot;: &quot;^3.0.0&quot;,
    &quot;file-loader&quot;: &quot;^0.11.2&quot;,
    &quot;glob&quot;: &quot;^7.1.2&quot;,
    &quot;js-yaml&quot;: &quot;^3.9.1&quot;,
    &quot;node-sass&quot;: &quot;^4.5.3&quot;,
    &quot;path-complete-extname&quot;: &quot;^0.1.0&quot;,
    &quot;postcss-cssnext&quot;: &quot;^3.0.2&quot;,
    &quot;postcss-loader&quot;: &quot;^2.0.6&quot;,
    &quot;postcss-smart-import&quot;: &quot;^0.7.5&quot;,
    &quot;precss&quot;: &quot;^2.0.0&quot;,
    &quot;rails-erb-loader&quot;: &quot;^5.2.1&quot;,
    &quot;resolve-url-loader&quot;: &quot;^2.1.0&quot;,
    &quot;sass-loader&quot;: &quot;^6.0.6&quot;,
    &quot;style-loader&quot;: &quot;^0.18.2&quot;,
    &quot;webpack&quot;: &quot;^3.5.5&quot;,
    &quot;webpack-manifest-plugin&quot;: &quot;^1.3.1&quot;,
    &quot;webpack-merge&quot;: &quot;^4.1.0&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;elm-hot-loader&quot;: &quot;^0.5.4&quot;,
    &quot;webpack-dev-server&quot;: &quot;^2.7.1&quot;
  }
}
&lt;/pre&gt;

&lt;p&gt;Because we’re not going to use any JavaScript except for some vanilla Elm bindings, we can remove a few packages:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
yarn remove \
  coffee-loader \
  coffee-script \
  rails-erb-loader
&lt;/pre&gt;

&lt;p&gt;And we can also remove Webpack’s loaders:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
rm \
  config/webpack/loaders/coffee.js \
  config/webpack/loaders/erb.js
&lt;/pre&gt;

&lt;p&gt;And we can also remove the following extensions from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config/webpacker.yml&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;.coffee&lt;/li&gt;
  &lt;li&gt;.erb&lt;/li&gt;
  &lt;li&gt;.jsx&lt;/li&gt;
  &lt;li&gt;.ts&lt;/li&gt;
  &lt;li&gt;.vue&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;wrapping-up&quot;&gt;Wrapping Up&lt;/h2&gt;

&lt;p&gt;Similar to part 1, I wanted to look at Elm’s page weight. I was sure it would be higher than Preact because we’re adding an entire language, but I was pleasantly surprised. To see production weight, compile the pack in production mode:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
RAILS_ENV=production ./bin/webpack
&lt;/pre&gt;

&lt;p&gt;Then run the server again:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
rails server
&lt;/pre&gt;

&lt;p&gt;Now our hello-elm JavaScript file weighs just 20KB. This was definitely less than I expected.&lt;/p&gt;

&lt;p&gt;I was also surprised at how easy setting up Elm was. In fact, I was disappointed because I wanted to be challenged to actually write hello world in Elm on my own. So, I guess that means I’ll have to write a follow up post!&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Preact on Rails with Webpack</title>
    <link href="http://ngauthier.com/2017/08/preact-on-rails-with-webpack.html"/>
    <updated>2017-08-29T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2017/08/preact-on-rails-with-webpack</id>
    <content type="html">&lt;p&gt;I needed to brush up my front-end skills, since I’ve been in Gopherland for a couple years now,
so I decided to write a few tutorials about using Rails with modern front-end frameworks. I’m
learning this as I go, so please feel free to comment or message me on Twitter if you have some
tips about the setup.&lt;/p&gt;

&lt;p&gt;In this article, we’re going to walk through how to set up Rails 5.1 with Webpack to use Preact
as a front-end framework. Rails 5.1 is the first version of Rails to support Webpack as part of
the application scaffolding process, which makes it easy (well … eas&lt;em&gt;ier&lt;/em&gt;) to get started with.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://preactjs.com/&quot;&gt;Preact&lt;/a&gt; is an alternate implementation of React using native dom features
and with a focus on being small and light and lower in dependencies. I like the idea of Preact
because it seems more approachable because of its smaller source code. I know I can just dig
through it if I encounter something unexpected. I mean, &lt;a href=&quot;https://unpkg.com/preact@8.2.5&quot;&gt;look at its source code&lt;/a&gt;
(seriously, open that link, that’s Preact without ES6 and JSX).&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;In order to run through this tutorial, you’ll need:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Ruby &amp;gt;2.2.2 (I’m using 2.4.0)&lt;/li&gt;
  &lt;li&gt;Rails &amp;gt;5.1 (I’m using 5.1.4.rc1)&lt;/li&gt;
  &lt;li&gt;NodeJS &amp;gt;6 (I’m using 6.11.2)&lt;/li&gt;
  &lt;li&gt;Yarn &amp;gt;0.20.1 (I’m using 0.27.5)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;creating-a-new-rails-app-with-webpack&quot;&gt;Creating a new Rails App with Webpack&lt;/h2&gt;

&lt;p&gt;The first thing we need to do is make a new Rails app with Webpack. We’re also going to remove
all the things we won’t need, since we’ll be using Preact. Here’s how we set up our application:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
rails new hello \
  --skip-action-cable \
  --skip-sprockets \
  --skip-coffee \
  --skip-javascript \
  --skip-turbolinks \
  --webpack
&lt;/pre&gt;

&lt;p&gt;We’re going to skip action cable, sprockets, coffeescript, rails javascript helpers, and turbolinks. And we’re going to turn on Webpack.&lt;/p&gt;

&lt;h3 id=&quot;using-webpacker--master&quot;&gt;Using Webpacker @ master&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Heads up! There’s currently a bug with automatic compilation so we’re going to use Webpack @ master&lt;/strong&gt;. Once a release &amp;gt; 2.0.0 of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rails/webpacker&lt;/code&gt; is released, you should be able to use that instead of this step.&lt;/p&gt;

&lt;p&gt;Edit our Gemfile, and modify the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;webpacker&lt;/code&gt; line to use master from GitHub:&lt;/p&gt;

&lt;pre class=&quot;prettyprint ruby&quot;&gt;
gem 'webpacker', github: 'rails/webpacker'
&lt;/pre&gt;

&lt;p&gt;Then update it:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
bundle update webpacker
&lt;/pre&gt;

&lt;p&gt;As of the writing of this post, I’m on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;master@691389f&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Finally, reinstall webpacker:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
rails webpacker:install
&lt;/pre&gt;

&lt;p&gt;(you can answer &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a&lt;/code&gt; to allow all updates)&lt;/p&gt;

&lt;h2 id=&quot;trimming-the-fat&quot;&gt;Trimming the Fat&lt;/h2&gt;

&lt;p&gt;Webpacker’s install is great because it brings in everything you might need. But, we can trim down a bunch of its
dependencies since we will just be using Preact. First off, lets remove some vestigal asset pipeline folders:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
rm -rf app/assets/ lib/assets/
&lt;/pre&gt;

&lt;p&gt;Also, &lt;strong&gt;edit app/views/layouts/application.html.erb&lt;/strong&gt; and remove the stylesheet tag and replace it with a
webpack tag:&lt;/p&gt;

&lt;pre class=&quot;prettyprint html&quot;&gt;
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Hello&amp;lt;/title&amp;gt;
    &amp;lt;%= csrf_meta_tags %&amp;gt;

    &amp;lt;%= javascript_pack_tag 'application' %&amp;gt;
  &amp;lt;/head&amp;gt;

  &amp;lt;body&amp;gt;
    &amp;lt;%= yield %&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;

&lt;p&gt;Next, let’s check out our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;package.json&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint json&quot;&gt;
{
  &quot;name&quot;: &quot;hello&quot;,
  &quot;private&quot;: true,
  &quot;dependencies&quot;: {
    &quot;autoprefixer&quot;: &quot;^7.1.3&quot;,
    &quot;babel-core&quot;: &quot;^6.26.0&quot;,
    &quot;babel-loader&quot;: &quot;7.x&quot;,
    &quot;babel-plugin-syntax-dynamic-import&quot;: &quot;^6.18.0&quot;,
    &quot;babel-plugin-transform-class-properties&quot;: &quot;^6.24.1&quot;,
    &quot;babel-plugin-transform-object-rest-spread&quot;: &quot;^6.26.0&quot;,
    &quot;babel-polyfill&quot;: &quot;^6.26.0&quot;,
    &quot;babel-preset-env&quot;: &quot;^1.6.0&quot;,
    &quot;coffee-loader&quot;: &quot;^0.8.0&quot;,
    &quot;coffee-script&quot;: &quot;^1.12.7&quot;,
    &quot;compression-webpack-plugin&quot;: &quot;^1.0.0&quot;,
    &quot;css-loader&quot;: &quot;^0.28.5&quot;,
    &quot;extract-text-webpack-plugin&quot;: &quot;^3.0.0&quot;,
    &quot;file-loader&quot;: &quot;^0.11.2&quot;,
    &quot;glob&quot;: &quot;^7.1.2&quot;,
    &quot;js-yaml&quot;: &quot;^3.9.1&quot;,
    &quot;node-sass&quot;: &quot;^4.5.3&quot;,
    &quot;path-complete-extname&quot;: &quot;^0.1.0&quot;,
    &quot;postcss-cssnext&quot;: &quot;^3.0.2&quot;,
    &quot;postcss-loader&quot;: &quot;^2.0.6&quot;,
    &quot;postcss-smart-import&quot;: &quot;^0.7.5&quot;,
    &quot;precss&quot;: &quot;^2.0.0&quot;,
    &quot;rails-erb-loader&quot;: &quot;^5.2.1&quot;,
    &quot;resolve-url-loader&quot;: &quot;^2.1.0&quot;,
    &quot;sass-loader&quot;: &quot;^6.0.6&quot;,
    &quot;style-loader&quot;: &quot;^0.18.2&quot;,
    &quot;webpack&quot;: &quot;^3.5.5&quot;,
    &quot;webpack-manifest-plugin&quot;: &quot;^1.3.1&quot;,
    &quot;webpack-merge&quot;: &quot;^4.1.0&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;webpack-dev-server&quot;: &quot;^2.7.1&quot;
  }
}
&lt;/pre&gt;

&lt;p&gt;Wow, that’s a lot of stuff! We can remove the coffeescript packages since we’ll be using ES6:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
yarn remove coffee-loader coffee-script
&lt;/pre&gt;

&lt;p&gt;We can also remove the rails-erb-loader since we won’t be using any erb templates in our javascript:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
yarn remove rails-erb-loader
&lt;/pre&gt;

&lt;p&gt;Now we can remove those loaders from webpack:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
rm config/webpack/loaders/coffee.js config/webpack/loaders/erb.js
&lt;/pre&gt;

&lt;p&gt;And in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config/webpacker.yml&lt;/code&gt; we can remove the following extensions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;.coffee&lt;/li&gt;
  &lt;li&gt;.erb&lt;/li&gt;
  &lt;li&gt;.ts&lt;/li&gt;
  &lt;li&gt;.vue&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Just to make sure you didn’t break anything, you can run:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
./bin/webpack
&lt;/pre&gt;

&lt;p&gt;to bundle up your assets. Mine looks like this:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
Hash: 77d3b57fb7806bb9009c
Version: webpack 3.5.5
Time: 262ms
                              Asset      Size  Chunks             Chunk Names
application-8f8bdd9f4ff51391ec46.js   4.47 kB       0  [emitted]  application
                      manifest.json  68 bytes          [emitted]
   [0] ./app/javascript/packs/application.js 515 bytes {0} [built]
&lt;/pre&gt;

&lt;h2 id=&quot;installing-preact&quot;&gt;Installing Preact&lt;/h2&gt;

&lt;p&gt;Installing Preact is as easy as:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
$ yarn add preact
yarn add v0.27.5
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
└─ preact@8.2.5
Done in 3.96s.
&lt;/pre&gt;

&lt;p&gt;Of course, that doesn’t do anything to our app, because we’re not using Preact anywhere yet.
In order to try it out, we’re going to need a page to work with in our app. I’m going to be
lazy and just add a view to the application controller.&lt;/p&gt;

&lt;p&gt;In &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config/routes.rb&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint ruby&quot;&gt;
Rails.application.routes.draw do
  root to: 'application#index'
end
&lt;/pre&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
$ mkdir app/views/application
$ touch app/views/application/index.html.erb
&lt;/pre&gt;

&lt;p&gt;Now we can run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rails server&lt;/code&gt; and it should just be a blank screen, but in the console, we should see:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
Hello World from Webpacker
&lt;/pre&gt;

&lt;p&gt;Yay! Just for a sanity check, edit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app/javascript/packs/application.js&lt;/code&gt; and edit the message and refresh your
browser and you should see a new message (because Rails should recompile your assets for you with webpacker).&lt;/p&gt;

&lt;p&gt;Additionally, we’re going to use JSX, so we need to install the babel JSX transformer:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
yarn add babel-plugin-transform-react-jsx
&lt;/pre&gt;

&lt;p&gt;And in order to map this transformer to Preact’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h&lt;/code&gt; method, add this line inside &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;plugins&lt;/code&gt; in your &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.babelrc&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint json&quot;&gt;
[&quot;transform-react-jsx&quot;, { &quot;pragma&quot;:&quot;h&quot; }]
&lt;/pre&gt;

&lt;h2 id=&quot;preact-hello-world&quot;&gt;Preact Hello World&lt;/h2&gt;

&lt;p&gt;Now it’s time to actually use Preact (finally, whew). Edit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app/javascript/packs/application.js&lt;/code&gt; and add this line:&lt;/p&gt;

&lt;pre class=&quot;prettyprint js&quot;&gt;
import('hello.js')
&lt;/pre&gt;

&lt;p&gt;That’s going to import &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app/javascript/hello.js&lt;/code&gt; (which we are about to write) into your app.&lt;/p&gt;

&lt;p&gt;Here’s what we put into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app/javascript/hello.js&lt;/code&gt; (which is straight from &lt;a href=&quot;https://preactjs.com/guide/getting-started&quot;&gt;Preact’s tutorial&lt;/a&gt;):&lt;/p&gt;

&lt;pre class=&quot;prettyprint js&quot;&gt;
import { h, render, Component } from 'preact';

render((
    &amp;lt;div id=&quot;foo&quot;&amp;gt;
        &amp;lt;span&amp;gt;Hello, world!&amp;lt;/span&amp;gt;
        &amp;lt;button onClick={ e =&amp;gt; alert(&quot;hi!&quot;) }&amp;gt;Click Me&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
), document.body);
&lt;/pre&gt;

&lt;p&gt;Now, we should be able to refresh our site, and see the Preact demo. Click the button and it says “Hi!”. We did it.&lt;/p&gt;

&lt;h2 id=&quot;wrapping-up&quot;&gt;Wrapping up&lt;/h2&gt;

&lt;p&gt;One of the things I was interested in is page weight. When running our app in dev mode, I saw two JS files, one is
application.js, which contains a bunch of webpack code for dynamically loading all our JS files separately. This is
great in development because we only have to rebuild what we change. So that’s why there’s a second “chunk” file
also being loaded.&lt;/p&gt;

&lt;p&gt;Doing a production asset build is as easy as:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
RAILS_ENV=production ./bin/webpack
&lt;/pre&gt;

&lt;p&gt;Then run our dev server again:&lt;/p&gt;

&lt;pre class=&quot;prettyprint bash&quot;&gt;
rails server
&lt;/pre&gt;

&lt;p&gt;As long as you don’t touch any JS files our production built JS files are used. From here I was able to see that
our application.js was just shy of 1kB, and our chunk with hello.js and preact in it are 3.7KB. Great! So we’re
under 5KB, which is awesome.&lt;/p&gt;

&lt;p&gt;I’m not sure if it’s possible to have just one application.js file (no chunks) so if you know how, let me know!&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Linux Workstation PC Build</title>
    <link href="http://ngauthier.com/2016/11/linux-workstation-pc-build.html"/>
    <updated>2016-11-01T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2016/11/linux-workstation-pc-build</id>
    <content type="html">&lt;p&gt;I got great response on Twitter from people who were interested in building a
Linux workstation. In this post, we’ll build a ridiculous PC for under $1,000,
plus show a couple add-ons you can make to fit your use case.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prices were noted at the time of the writing of the post, they may have changed!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/nzxt-s340.png&quot; alt=&quot;NZXT S340&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;base-spec&quot;&gt;Base Spec&lt;/h2&gt;

&lt;p&gt;This is the base version of the PC we’re going to build. You can only buy the
parts here and you’ll have an amazing linux machine.&lt;/p&gt;

&lt;h3 id=&quot;cpu-329&quot;&gt;CPU $329&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;http://amzn.to/2e9J8C1&quot;&gt;Intel Core i7 6700K 4.00 GHz Unlocked Quad Core Skylake Desktop Processor&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This processor is a year old, and Kaby Lake is just coming out soon. However,
Kaby Lake is not going to be a big boost over Skylake, it’s just a minor
iteration. The Kaby lake version of this chip will be at 4.2 GHz.&lt;/p&gt;

&lt;p&gt;But, this is unlocked! That’s the K at the end of the SKU. There are reports of
folks overclocking it to 4.8 GHz (with voltage changes). I wouldn’t be surprised
if you can push it to 4.5 GHz without changing the voltage. My trusty 3770k is
still humming along at 4.0 GHz overclock, and it’s four and a half years old!&lt;/p&gt;

&lt;h3 id=&quot;motherboard-149&quot;&gt;Motherboard $149&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;http://amzn.to/2eXuoaY&quot;&gt;ASUS Z170-A&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I love ASUS motherboards, I’ve been building on them for fifteen years. This is
the cream of the crop. It’s got m2 for insane solid state speeds, ddr4 ram, and
it can leverage the intel chip’s graphics to drive up to three displays over
displayport. It’s got USB3 and gigabit LAN, of course. It also has a USB-C port,
neat!&lt;/p&gt;

&lt;p&gt;Speaking of displays, this combined with the intel chip above can drive a
4K display over displayport. So you don’t need additional graphics.&lt;/p&gt;

&lt;p&gt;Also, it has 5-way optimization, which is an auto-tuning tool. You boot into
the bios, tell it to do it’s thing, and it will auto-overclock the whole system!&lt;/p&gt;

&lt;h3 id=&quot;ram-85&quot;&gt;RAM $85&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;http://amzn.to/2eXwQ13&quot;&gt;Corsair Vengeance LPX 16GB (2x8GB) DDR4 DRAM 2133MHz&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A pair of 8GB sticks brings us to 16GB. You can get two orders for a total of
32GB if you’d like. I don’t need more than 8GB on linux, but I have 16GB right
now because I play games. I think 32GB is excessive, and you can always purchase
it later. Or treat yourself!&lt;/p&gt;

&lt;h3 id=&quot;power-supply-70&quot;&gt;Power Supply $70&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;http://amzn.to/2e9Mk0t&quot;&gt;Seasonic M12II 620&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I love Seasonic supplies. They are very quiet. This one is also modular, so
that keeps the clutter down inside the system. 620W is more than enough, even
if you purchase the add-ons below (more graphics).&lt;/p&gt;

&lt;h3 id=&quot;case-75&quot;&gt;Case $75&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;http://amzn.to/2fdrn5V&quot;&gt;NZXT S340&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I love the look of this case. You can pick a different color if you’d like,
they have a bunch of great options. NZXT’s build quality is great, and this case
has two included 120mm fans, which will be great for cooling and quiet too.&lt;/p&gt;

&lt;h3 id=&quot;ssd-185&quot;&gt;SSD $185&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;http://amzn.to/2fr4wZf&quot;&gt;Samsung 950 PRO 256GB M.2&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The new M.2 SSDs are crazy. This one packs 2,200MB/s Read and 900MB/s write.
Wow. It’s 256GB but the link I posted has a 512GB option that is 2,500MB/s and
1,500MB/s if you love speed.&lt;/p&gt;

&lt;p&gt;NOTE: you can only put one of these in the system. Motherboard has only one M.2
slot. You can buy an M.2 PCIe card and RAID them, or buy a PCIe SSD, or buy a
SATA SSD if you need more.&lt;/p&gt;

&lt;h3 id=&quot;base-spec-summary&quot;&gt;Base Spec Summary&lt;/h3&gt;

&lt;p&gt;OK, that’s it for the base!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Total before taxes: $893&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you’re used to Apple, this price may shock you. Welcome to the real world ;)&lt;/p&gt;

&lt;h2 id=&quot;add-ons&quot;&gt;Add-ons&lt;/h2&gt;

&lt;p&gt;Here are two more things you may want to add to your system.&lt;/p&gt;

&lt;h3 id=&quot;liquid-cooler-105&quot;&gt;Liquid Cooler $105&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;http://amzn.to/2ej3fRE&quot;&gt;NZXT Technologies Kraken X41&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I love the new all-in-one liquid coolers. You don’t have to mess with pipes or
leaks or anything. They’re entirely self-contained. This NZXT cooler fits on
the front of the case (inside it) we picked. That way, air is taken in the front
of the case, passes over the radiator, and is exausted via the rear and top fans.&lt;/p&gt;

&lt;p&gt;This cooler goes on just like a normal air cooler, but it also attaches at a fan
mount point. When you install the chip, just toss the intel fan cooler and use
this one’s water block instead.&lt;/p&gt;

&lt;p&gt;Coolers like these are more efficient and much much quieter too, even under
load.&lt;/p&gt;

&lt;h3 id=&quot;graphics-card-230&quot;&gt;Graphics Card $230&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;http://amzn.to/2ej9W6k&quot;&gt;Sapphire NITRO+ Radeon™ RX 480 4GB&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The new RX 480 line from AMD is an amazing value. You can drop any card into
this system and it will probably be fine, and if I offered every graphics option
this post would be huge.&lt;/p&gt;

&lt;p&gt;I use the RX 480 in my home desktop on linux and the compatibility is excellent.&lt;/p&gt;

&lt;p&gt;I also play games on it at 2560x1600. It can play Overwatch completely maxxed
out at 60fps.&lt;/p&gt;

&lt;p&gt;Also, the motherboard we’re using can fit 3 graphics cards on it (but usually
there are diminishing returns after 2). So you can buy a second one in a year
or two at a nice discount and double up your graphics power.&lt;/p&gt;

&lt;h2 id=&quot;totally-maxxed-out&quot;&gt;Totally Maxxed Out&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Totally Maxxed Out Total: $1444&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;(This includes a second pair of RAM, liquid cooler, graphics, and 512GB SSD).&lt;/p&gt;

&lt;h1 id=&quot;bonus-section-peripherals&quot;&gt;Bonus Section: Peripherals&lt;/h1&gt;

&lt;p&gt;I really like the &lt;a href=&quot;http://amzn.to/2frbLjX&quot;&gt;Dell P2715Q 27” 4K monitor&lt;/a&gt;, a
&lt;a href=&quot;http://amzn.to/2e9RnxQ&quot;&gt;Das Keyboard&lt;/a&gt;, a
&lt;a href=&quot;http://amzn.to/2f9a3QF&quot;&gt;SteelSeries Sensei&lt;/a&gt;, and a
&lt;a href=&quot;http://amzn.to/2ejiolO&quot;&gt;Logitech C922x webcam&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;On linux, a quick &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;xset m 1 1&lt;/code&gt; will kill your mouse acceleration, making you
very accurate.&lt;/p&gt;

&lt;p&gt;If you want a 144hz gaming monitor with freesync, the &lt;a href=&quot;http://amzn.to/2ejgQsd&quot;&gt;Pixio PX277&lt;/a&gt;
looks like a great deal. Apparently the stand is flimsy so you may want to buy
a separate VESA stand.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Staying Motivated While Working Solo</title>
    <link href="http://ngauthier.com/2016/04/staying-motivated-solo.html"/>
    <updated>2016-04-25T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2016/04/staying-motivated-solo</id>
    <content type="html">&lt;p&gt;I recently started &lt;a href=&quot;http://www.meetspaceapp.com&quot;&gt;MeetSpace&lt;/a&gt;, a video conferencing app for distributed teams. It’s not the first time I’ve started a product company, nor is it the first time I’ve worked alone. But, it’s the first product I’ve worked on alone. In the past I had either partners or clients I’ve worked with on any project, but this is the first one where I’m the solely responsible person (insert irresponsible coworkers joke here :P ). In this post I’ll outline the ways that I keep myself motivated and working each day.&lt;/p&gt;

&lt;h2 id=&quot;accountable-person&quot;&gt;Accountable Person&lt;/h2&gt;

&lt;p&gt;One of the very first things I did was get someone to hold me accountable for my work. I’m very fortunate to have &lt;a href=&quot;https://twitter.com/bsierakowski&quot;&gt;Brian Sierakowski&lt;/a&gt; of &lt;a href=&quot;https://www.teampassword.com&quot;&gt;TeamPassword&lt;/a&gt; meeting with me weekly to hold me accountable. We also swap notes with what he’s doing over at TeamPassword.&lt;/p&gt;

&lt;p&gt;Each week I tell Brian what I got done this week and what I expect to get done next week, and we compare it to what I said I’d get done last week. We also talk at a high level about strategy or sometimes just bat ideas back and forth. Eventually we just end up talking about &lt;a href=&quot;http://us.battle.net/overwatch/en&quot;&gt;video games&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It really motivates me to think about our weekly meeting (it’s on Friday morning) during the week. I know I’ll have to tell Brian if I miss a deadline on a task, especially if it’s something that’s not particularly difficult but maybe a chore to do. Having it on Friday morning also makes sure I don’t leave it until the last minute, because I want to have everything done by Thursday, but I can finish it Friday if I have to.&lt;/p&gt;

&lt;p&gt;I would highly recommend getting an accountable person to help you out if you’re working solo. You should have a regular meeting with a specific agenda that covers what you did and what you will do. Even if you’re a freelancer and all you track is billable hours, you can simply text a family member and say “I billed 35/30 target hours this week”.&lt;/p&gt;

&lt;h2 id=&quot;working-contiguously-in-time-and-space&quot;&gt;Working Contiguously in Time and Space&lt;/h2&gt;

&lt;p&gt;It’s very important for my productivity to work contiguously, both in time and space. I need to go to a separate location that is solely a work location, and I need to be there for one long chunk of time. Context switching in and out of work mode doesn’t work at all for me. I have to go to work, work until I am done, and then go home and not work. I have a very binary work brain.&lt;/p&gt;

&lt;p&gt;I worked from home for a while when I first started freelancing, but after a few months I got a work space. My friends at &lt;a href=&quot;https://figure53.com&quot;&gt;Figure53&lt;/a&gt; were kind enough to lease me a desk at their office. Later on, I ended up working out of offices I leased or coworking spaces (I’m currently at &lt;a href=&quot;http://beyond-boston.workbar.com/neighborhood/arlington/#workbar-arlington&quot;&gt;Workbar Arlington&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;When I worked from home, I was billing hourly to clients, and that kept me very productive and honest with my time. I would work in 30 minute &lt;a href=&quot;http://pomodorotechnique.com/&quot;&gt;pomodoros&lt;/a&gt; modified to be 30 minutes working 5 minutes resting, and I would bill that as 30 minutes. That way, I couldn’t stop working inside a 30 minute chunk or I wouldn’t be able to bill it.&lt;/p&gt;

&lt;p&gt;But, once my time was my own, this didn’t work. It was too easy to &lt;a href=&quot;https://www.youtube.com/watch?v=XYK_elq1xpk&quot;&gt;make stupid coffee videos&lt;/a&gt; when I was at home instead of working. So now, I go to an office.&lt;/p&gt;

&lt;h2 id=&quot;routine&quot;&gt;Routine&lt;/h2&gt;

&lt;p&gt;Having a regular routine and schedule is very helpful because it keeps my expectations set very consistently on how each day is going to go. Every weekday looks like this:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Wake up (6:30am)&lt;/li&gt;
  &lt;li&gt;Make breakfast (usually coffee and scrambled eggs)&lt;/li&gt;
  &lt;li&gt;Bike to work (drive if weather sucks)&lt;/li&gt;
  &lt;li&gt;Work 8am-12pm and drink 32oz water&lt;/li&gt;
  &lt;li&gt;Lunch 12pm-12:30pm&lt;/li&gt;
  &lt;li&gt;Work 12:30pm-4:30pm and drink 32oz water, second coffee if I want&lt;/li&gt;
  &lt;li&gt;Bike/drive home&lt;/li&gt;
  &lt;li&gt;Exercise&lt;/li&gt;
  &lt;li&gt;Hang out (video games, movies, reading, cooking) and drink 32oz water&lt;/li&gt;
  &lt;li&gt;Sleep&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I have two 4 hour work blocks with a lunch break in between. There’s not much to do at the office that isn’t working. Because my schedule is really consistent, I get very used to following the same schedule every day. This way there’s less of a nagging “hey let’s go to work late today / come home early” voice because those are the times I always work.&lt;/p&gt;

&lt;h2 id=&quot;task-driven&quot;&gt;Task-driven&lt;/h2&gt;

&lt;p&gt;I mentioned that I discuss my tasks with an accountable person, and in a &lt;a href=&quot;/2016/03/minimum-viable-project-management.html&quot;&gt;previous post on minimum viable project management&lt;/a&gt; I discuss how I manage the tasks on a project. What this really breaks down to is a todo-list (I use &lt;a href=&quot;https://www.wunderlist.com&quot;&gt;Wunderlist&lt;/a&gt;) with all of my tasks on it.&lt;/p&gt;

&lt;p&gt;Anything that I do goes into the list, and generally those items go onto the list at least the week before I work on them. Each week (after the Friday accountability meeting) I scrub my list. This involves going through every task and seeing if their due dates are all still reasonable.&lt;/p&gt;

&lt;p&gt;All tasks have a due date (almost always a Friday). This groups tasks into weeks. I can look at the tasks for a week and if it’s too much I bump some tasks to the next week, and cascade forwards until the roadmap looks good.&lt;/p&gt;

&lt;p&gt;I delete any tasks I don’t think are important any more. Sometimes I add something like “ooh, it would be neat if…” If on Friday I don’t think that task is really important, I delete it.&lt;/p&gt;

&lt;p&gt;At this point, I have one to two months of roadmap. Anything farther in the future is so poorly defined I just keep it as a thought. By the time I get low on tasks, my favorite thoughts for the product will be at the forefront.&lt;/p&gt;

&lt;p&gt;When I am working, I look at Wunderlist’s automatic “Week” list, which shows everything due within 7 days. This is my list for the week, and I work top to bottom, checking things off as I go.&lt;/p&gt;

&lt;p&gt;I also make use of recurring todos for marketing. That involves writing inbound content, publishing, republishing, tweeting, emailing, and also customer development type tasks. That way these come back around on a schedule.&lt;/p&gt;

&lt;p&gt;One really nice aspect of this system is that &lt;strong&gt;I can actually get to a done state&lt;/strong&gt;. When I finished everything for the week my list is blank. I am actually done. It’s wonderful. I usually will take a Friday afternoon off if I’m done. Life is short.&lt;/p&gt;

&lt;h2 id=&quot;varied-schedule&quot;&gt;Varied Schedule&lt;/h2&gt;

&lt;p&gt;I have a routine, tasks, and recurring tasks. This comes together to form a very regular day and week. But each day is a little different. I like to have different kinds of work scheduled throughout the week so that day-by-day I’m doing different things.&lt;/p&gt;

&lt;p&gt;Mondays are for marketing, creating content, following up on campaigns, and customer development in the morning. This is really motivating work because it reminds me of why I’m working on MeetSpace: all the people! Seeing a good piece of feedback or good reaction to a post is very rewarding. Then seeing a bad piece of feedback or bug report is really motivating to do a good job. I can’t sit on my butt if there’s a bug out there!&lt;/p&gt;

&lt;p&gt;Monday afternoons I work on bugs and then technical debt. This puts me on a “clean slate”. Tuesday and Wednesday I work on the “big feature” of the week. Thursday is another marketing and content morning. Thursday afternoon is wrapping up features, bugs, and technical debt.&lt;/p&gt;

&lt;p&gt;Friday is my accountability meeting, any remaining tasks, task planning for the next week, a product update for users, and any leftover bugs or debt.&lt;/p&gt;

&lt;h2 id=&quot;not-naturally-motivated&quot;&gt;Not Naturally Motivated&lt;/h2&gt;

&lt;p&gt;I’m writing this post to share that there’s really a lot that goes into getting myself to do work each day, week, and month. It’s not something that comes naturally to me. If I am at home I’ll play video games. At work I’ll surf random internet sites or social networks or talk to coworkers. If I don’t have a combination of a time and place to work, tasks due, someone who’s going to ask about them, people who are interested in them, and a regular but varied schedule, I don’t get much done at all.&lt;/p&gt;

&lt;p&gt;So if you don’t feel naturally inclined to get lots done every day, don’t worry, you’re not weird. You’re probably pretty normal. I needed a lot of structure before I could really get lots done on MeetSpace.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Minimum Viable Project Management</title>
    <link href="http://ngauthier.com/2016/03/minimum-viable-project-management.html"/>
    <updated>2016-03-25T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2016/03/minimum-viable-project-management</id>
    <content type="html">&lt;p&gt;I started my career in software at a consultancy, and over the years I’ve spent more than half my time as a consultant or freelancer. In all this time across many projects, I’ve experimented with many ways of doing software project management. From processes like waterfall, agile, and kanban to tools like pivotal tracker, trello, github issues, and basecamp.&lt;/p&gt;

&lt;p&gt;All these processes and tools have the same goal: turn thoughts into structured definition of work.&lt;/p&gt;

&lt;p&gt;As the tools have evolved, they have focused on improving that goal through increased specification. By capturing more information on what the work is, how it will be done, and who will do it, they have furthered their goal of creating order from chaos.&lt;/p&gt;

&lt;p&gt;My career is built upon my ability to turn creative thoughts into reality. My emotional attachment to each of my thoughts is strong and personal. I derive a lot of satisfaction in filling up a project management tool with all of my ideas.&lt;/p&gt;

&lt;p&gt;What starts as a distillation quickly turns into hoarding. It seemed like all the ideas were at the forefront of consciousness, but after a week or two, I don’t recognize some of my tasks any more. Did I even put this in the icebox? How do we have 80 stories in here already?&lt;/p&gt;

&lt;p&gt;It’s not long before the icebox becomes unmanageable and we declare bankruptcy. We call our work so far “done” and we make a new project, or we switch tools. And what a rush to start fresh! Now I can &lt;em&gt;really&lt;/em&gt; just write down what is important, and none of that other crap. Then a week passes, and then another, and here we are again, mr icebox, my how you’ve grown.&lt;/p&gt;

&lt;p&gt;Somehow I lost track of the fact that when I declare bankruptcy and start fresh, all the good ideas are still there. My best ideas are never forgotten. Like a commercial jingle they jump back into my head when I’m at the grocery store, or in the shower, or trying to fall asleep.&lt;/p&gt;

&lt;p&gt;Over time, the best ideas grow and evolve through a mental kneading and rising and kneading and rising, until their wispy beginnings gain a firm but supple quality. I don’t notice or miss the other thoughts that came and went, and if I have to, I can go looking and find them again.&lt;/p&gt;

&lt;p&gt;Simplify, simplify.&lt;/p&gt;

&lt;p&gt;Every piece of information, every fleeting thought and precious idea that is written down and stored becomes a strap tying down what we’re creating, limiting its shape and size within the scope of its bindings. As more and more tasks and stories and requirements are added, the straps pile on and tighten until what’s left isn’t so much our hopes and dreams, but the only remaining shape that can fit within the bounds we’ve created.&lt;/p&gt;

&lt;p&gt;I’m ditching my specification-oriented project management style for something more free-form and organic.&lt;/p&gt;

&lt;p&gt;I will constrain my ability to constrain.&lt;/p&gt;

&lt;p&gt;An entire use case, or feature, or flaw is one short sentence. Everything else is in my head, or in my words with my advisors, customers, and friends. Or on pages in my notebook I know I’ll never flip back to.&lt;/p&gt;

&lt;p&gt;What about all the productive discussions with all the people involved? Those sessions are not for “information extraction”, instead, they are explorative and extemporaneous expositions. I may not write everything down but I am certainly shaped by it.&lt;/p&gt;

&lt;p&gt;There is no icebox, there is no phase 2, there is no story landfill. Burn your trash, throw your ideas away. The good ones will never leave you.&lt;/p&gt;

&lt;p&gt;Everything I am going to do is scheduled and ordered or it is not recorded. When it’s time to get started, I revisit the discussion. A lot may have changed since we last explored the idea. Now we can visit it in the present and move forwards without the constraints of the past limiting our thoughts.&lt;/p&gt;

&lt;p&gt;There are 36 one-line tasks between now and the full paid release of &lt;a href=&quot;http://www.meetspaceapp.com&quot;&gt;MeetSpace&lt;/a&gt;, and that leaves me free to focus, work, and think.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Interview Notes</title>
    <link href="http://ngauthier.com/2016/03/interview-notes.html"/>
    <updated>2016-03-21T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2016/03/interview-notes</id>
    <content type="html">&lt;p&gt;I was asked recently to write up how I give interviews, and I realized that it could be very helpful to publish these publicly. As you will understand while reading, knowledge of my interview and its rubrick doesn’t give a potential candidate an edge. In fact, I think it would lead to a more accurate interview. Enjoy, and share your thoughts!&lt;/p&gt;

&lt;h2 id=&quot;general-format&quot;&gt;General Format&lt;/h2&gt;

&lt;h3 id=&quot;part-1-chat&quot;&gt;Part 1: Chat&lt;/h3&gt;

&lt;p&gt;30 minutes talking. We would talk about previous experience, current interests, what it’s like at the company they are interviewing for. No formal questions like “what vegetable are you?” only casual things. The goal of this phase is to establish our relationship and communication style so that we can speak easily when we get to the technical part. Candidates could be disqualified during this phase, though.&lt;/p&gt;

&lt;p&gt;Examples of negative experiences and qualities:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Superiority complex / elitism / asshole: “well, actually”, patronizing me, talking poorly of past experiences or coworkers, bragging and gloating without specific examples (i.e. “I’m pretty much the best developer I’ve ever known” is bad but “I’ve done some really incredible things with postgresql on past projects” is good).&lt;/li&gt;
  &lt;li&gt;Inability to explain: if I ask about a past project or a language or anything, and the candidate can’t tell me about it at all, or explains very tersely and stops.&lt;/li&gt;
  &lt;li&gt;Lack of interest: it’s odd but sometimes you get someone who just doesn’t seem to even care about the interview or working for the company or anything.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Examples of positive experiences and qualities:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;If I ask about something pretty simple, like “What did you work on at X corp” and they explode into enthusiasm and talk about it on their own with only minimal “ah”, “ok”, “cool!” from me for a while. This person really loves what they do.&lt;/li&gt;
  &lt;li&gt;Mutual feeling of at-ease when we speak. We’re having an honest conversation, there’s no positioning, choosing words carefully. We are just talking about stuff and establish a connection quickly. It can take until the end of the 30 minutes for this, but that’s ok. As an interviewer, you should set the example of speaking honestly and openly.&lt;/li&gt;
  &lt;li&gt;Opinions and willingness to share them. Doesn’t really matter if we agree or not, but I want to hear that the candidate has their own opinions on relevant subjects and is excited to discuss them.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;part-2-code&quot;&gt;Part 2: Code&lt;/h3&gt;

&lt;p&gt;One hour of coding. I’ve done two projects during this part since 2009. At first, it was always “build a rails blog” since I was only interviewing for Rails (although I had someone do it in Django because that’s what they knew, and they got the job!). Later on, it became “work with some json” because it was more of a general position but web background was part of it.&lt;/p&gt;

&lt;p&gt;Here is how the JSON project would go:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;I give them some JSON data. I would use some Codeship API data. It had a root object, and one of the values was an array with some computable properties.&lt;/li&gt;
  &lt;li&gt;I would ask them to give me one of the top level key’s values. At this point the person says “um, how do you want me to code that?” and I will say “you could do a script, or a binary, or a library, it all works for me!”. At this point I also mention that “there are no rules” for this interview.&lt;/li&gt;
  &lt;li&gt;“OK, before we do the next thing, anything you want to clean up?”&lt;/li&gt;
  &lt;li&gt;I ask for the number of items in the array value of the object (just count)&lt;/li&gt;
  &lt;li&gt;“OK, anything you want to clean up or refactor here?”&lt;/li&gt;
  &lt;li&gt;I ask to compute something on the array values (percentage where some bool is true, for example)&lt;/li&gt;
  &lt;li&gt;refactor again&lt;/li&gt;
  &lt;li&gt;I ask to compute something else, but more complicated (often this one is avg(timestamp-timestamp) to get average duration of an event).&lt;/li&gt;
  &lt;li&gt;refactor again&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That usually takes the hour. If not, I will have a couple of harder and harder questions. The point is not how far we get, but how we do it.&lt;/p&gt;

&lt;p&gt;At this point, you’re probably thinking “wow that is really easy, how is this effective?”. On the one hand, I am evaluating their ability to do the assignment. I have passed candidates who only were able to do the first task. But usually it’s because the language they were comfortable with had poor json support so we spent the whole time figuring that out. But that’s OK! That’s totally something programmers do all the time, and your ability to do that well is just as important as slamming out easy code.&lt;/p&gt;

&lt;p&gt;Here is what I am really looking for when we do this part of the interview:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;How is working with this person? I am acting as a “novice pair” so I don’t really know how to do a lot of stuff, but I’m still contributing a little bit. Do I enjoy coding with this person? Would I ask them to pair with me if I was stuck?&lt;/li&gt;
  &lt;li&gt;What is their attention to detail? How often did they miss little things or leave loose ends lying around? Are they rushing sloppily to get through as much as possible in the interview, or are they really trying to get it right? (Spoiler alert: this is how they will attack projects when they’re on the job too!)&lt;/li&gt;
  &lt;li&gt;Where is their balance point between productivity and perfection? More specifically, how much do they refactor when prompted? I have had people who just say “It’s great the way it is I wouldn’t change it” when there are obvious duplications. I’ve also had people who went full rabbit-hole on something really unimportant. I try to figure out their balance point. Generally, I will take people who are perfectionists, and in the middle, but not those who don’t see the possibility of improvement. (Spoiler alert: they are often “expert beginners” and they will not improve themselves while on the job. Why should they? They’re already perfect and they write perfect code the first time).&lt;/li&gt;
  &lt;li&gt;Do they ask for help? I really try to act like a pair, and hopefully from the chat section we are at ease. When they don’t receive enough clarification when I tell them the next part of the project, do they ask for clarification, or do they guess what I want? When they get stuck, will they ask me for help? It’s extremely important that the candidate ask for help during the exercise. &lt;em&gt;Especially&lt;/em&gt; if they are more senior. I want to work on a team of people who get the most out of each other to do their best work. I have even had candidates ask me directly for the solution to one of my questions. This is actually a huge point in their favor! I will then politely say that while I do know the answer unfortunately this is an interview and they will need to solve it themselves, but I will usually give them a tip.&lt;/li&gt;
  &lt;li&gt;Comfort with their tools. I always have the interviewee work in their most comfortable and familiar environment. The language of their choice, the editor of their choice. Always on a computer they brought with them. They should be quick at the keyboard, quick on their editor, quick on the browser searching for help, quick to evaluate which stack overflow post is the most relevant, etc. If you were hiring a carpenter and they struggled with hitting a nail, they don’t hit a lot of nails. Many interviews try to throw a fastball and see if the interviewee can hit it. I set up a T-ball and see how far they can hit.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Boiling it down, these are the qualities I am evaluating:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Communication ability: honesty, frankness, and ease.&lt;/li&gt;
  &lt;li&gt;Attention to detail, not sloppy, no “messy room syndrome”&lt;/li&gt;
  &lt;li&gt;Always looking for improvement. Never satisfied. Understanding that perfection is both unnattainable but worth attempting.&lt;/li&gt;
  &lt;li&gt;Open to assistance from anyone, not afraid to ask for help, open to the thoughts and opinions of others.&lt;/li&gt;
  &lt;li&gt;Programming is a natural skill for them. They are quick and comfortable and experienced with what they claim as their experience level.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;You may have noticed that the actual act of programming is a minority in the qualities I am assessing. That is because I truly believe it is a minority in the qualities of a great team member. You will be spending the majority of your week interacting with the people on your team. Those interactions have to be smooth and productive for you to be able to even get to the programming part of your job. The easier it is to talk to your teammates, debate, come to conclusions, get help, and solve problems, the more time you will spend implementing your solutions. It will also significantly affect your happiness and burnout.&lt;/p&gt;

</content>
  </entry>
  
  <entry>
    <title>Scraping the Web with Ruby</title>
    <link href="http://ngauthier.com/2014/06/scraping-the-web-with-ruby.html"/>
    <updated>2014-06-05T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2014/06/scraping-the-web-with-ruby</id>
    <content type="html">&lt;p&gt;When you run into a site that doesn’t have an API, but you’d like to use the site’s data, sometimes all you can do is scrape it! In this article, we’ll cover using Capybara and PhantomJS along with some standard libraries like CSV, GDBM, and OpenStruct to turn a website’s content into CSV data.&lt;/p&gt;

&lt;p&gt;As an example, I’ll be scraping my own site. Keep in mind if you are planning to scrape a site, be aware of their Terms of Service. Many sites don’t allow scraping, so be a good web citizen and respect the wishes of the site’s owners.&lt;/p&gt;

&lt;p&gt;Our goal here is to dump out a CSV file of the blog articles here on ngauthier.com that contains the titles, dates, urls, summary, and full body text. Let’s get started!&lt;/p&gt;

&lt;h1 id=&quot;1-scraping-with-capybara&quot;&gt;1. Scraping with Capybara&lt;/h1&gt;

&lt;p&gt;The first thing we’re going to do is get Capybara running and just dump the fields from the front page out to the screen to make sure everything’s working.&lt;/p&gt;

&lt;p&gt;First, we’re going to load up capybara and poltergeist. Poltergeist is a ruby gem that wraps phantomjs so that we can run a real browser on the external pages.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/usr/bin/env ruby

require 'capybara'
require 'capybara/poltergeist'

include Capybara::DSL
Capybara.default_driver = :poltergeist
&lt;/pre&gt;

&lt;p&gt;Next up, we’re going to visit my site. Then we’ll iterate over every post and pull out the fields we want using css selectors and dump them to the screen.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
visit &quot;http://ngauthier.com/&quot;

all(&quot;.posts .post&quot;).each do |post|
  title = post.find(&quot;h3 a&quot;).text
  url   = post.find(&quot;h3 a&quot;)[&quot;href&quot;]
  date  = post.find(&quot;h3 small&quot;).text
  summary = post.find(&quot;p.preview&quot;).text

  puts title
  puts url
  puts date
  puts summary
  puts &quot;&quot;
end
&lt;/pre&gt;

&lt;p&gt;When we run it, we can see that our scraper is loading up the homepage and finding the info:&lt;/p&gt;

&lt;pre&gt;
Using Docker to Parallelize Rails Tests
/2013/10/using-docker-to-parallelize-rails-tests.html
2013-10-13
Docker is a new way to containerize services. The primary use so far has been for deploying services in a very thin container. I experimented with using it for Rails Continuous Integration so that I could run tests within a consistent environment, and then I realized that the containers provide excellent encapsulation to allow for parallelization of test suites. There are three things we'll have to do to run a Rails test suite in parallel in docker: Create a Dockerfile for a system that ca...

PostGIS and Rails: A Simple Approach
/2013/08/postgis-and-rails-a-simple-approach.html
2013-08-18
PostGIS is a geospatial extension library for PostgreSQL that allows you to perform a ton of geometric and geographic operations on your data at high speeds. For example: Compute the distance between two points Find all the points within X meters of point P Determine which points are enclosed in polygon P A million other things In Ruby land, there is a gem called RGeo that provides a ton of objects and methods for handling Geospatial objects. In Rails, there are a number of ActiveRecord ...

...
&lt;/pre&gt;

&lt;h1 id=&quot;exporting-csv&quot;&gt;Exporting CSV&lt;/h1&gt;

&lt;p&gt;Our next goal is to export some CSV. All we’ll do is load up the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;csv&lt;/code&gt; standard library and write csv to standard out.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/usr/bin/env ruby

require 'capybara'
require 'capybara/poltergeist'
require 'csv'

include Capybara::DSL
Capybara.default_driver = :poltergeist

visit &quot;http://ngauthier.com/&quot;

CSV do |csv|
  csv &amp;lt;&amp;lt; [&quot;Title&quot;, &quot;URL&quot;, &quot;Date&quot;, &quot;Summary&quot;]
  all(&quot;.posts .post&quot;).each do |post|
    title = post.find(&quot;h3 a&quot;).text
    url   = post.find(&quot;h3 a&quot;)[&quot;href&quot;]
    date  = post.find(&quot;h3 small&quot;).text
    summary = post.find(&quot;p.preview&quot;).text

    csv &amp;lt;&amp;lt; [title, url, date, summary]
  end
end
&lt;/pre&gt;

&lt;p&gt;Now, our program is unixy, so we would run it and redirect its output to a csv file of our choosing. Nice!&lt;/p&gt;

&lt;h1 id=&quot;full-articles-via-multi-pass&quot;&gt;Full Articles via Multi-Pass&lt;/h1&gt;

&lt;p&gt;So far, we’ve only pulled the summaries of the posts, but we want the whole content. For this, we’re going to need to do a two-pass scrape. First, we’ll scrape the summaries like we already are doing. Second, we’ll visit each post’s url and grab the post’s body.&lt;/p&gt;

&lt;p&gt;To do this, we’re going to keep track of an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;articles&lt;/code&gt; array, and store the articles temporarily as hashes.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/usr/bin/env ruby

require 'capybara'
require 'capybara/poltergeist'
require 'csv'

include Capybara::DSL
Capybara.default_driver = :poltergeist

visit &quot;http://ngauthier.com/&quot;

articles = []

# Pass 1: summaries and info
all(&quot;.posts .post&quot;).each do |post|
  title = post.find(&quot;h3 a&quot;).text
  url   = post.find(&quot;h3 a&quot;)[&quot;href&quot;]
  date  = post.find(&quot;h3 small&quot;).text
  summary = post.find(&quot;p.preview&quot;).text

  articles &amp;lt;&amp;lt; {
    title:   title,
    url:     url,
    date:    date,
    summary: summary
  }
end

# Pass 2: full body of article
articles.each do |article|
  visit &quot;http://ngauthier.com#{article[:url]}&quot;
  article[:body] = find(&quot;article&quot;).text
end

# Output CSV
CSV do |csv|
  csv &amp;lt;&amp;lt; [&quot;Title&quot;, &quot;URL&quot;, &quot;Date&quot;, &quot;Summary&quot;, &quot;Body&quot;]
  articles.each do |article|
    csv &amp;lt;&amp;lt; [
      article[:title],
      article[:url],
      article[:date],
      article[:summary],
      article[:body]
    ]
  end
end
&lt;/pre&gt;

&lt;p&gt;That wasn’t so bad! The main issue now is robustness. My blog is fast (static sites with jekyll woo!) and I only have a couple posts. But imagine the scrape took an hour. If anything crashed, took too long, or the site went down, we’d waste a ton of time.&lt;/p&gt;

&lt;h1 id=&quot;handling-interruptions-with-gdbm&quot;&gt;Handling Interruptions with GDBM&lt;/h1&gt;

&lt;p&gt;Enter GDBM. GDBM is a standard unix library that is a simple file-based key-value store. It’s like a hash, but you can only use strings as the values. What we’re going to do is replace our article array with a GDBM store. For the key we’ll use the url, and for the value we’ll dump the article to JSON.&lt;/p&gt;

&lt;p&gt;Now, if the program crashes, when we resume we want to skip over any articles we’ve already processed. Let’s take a look:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/usr/bin/env ruby

require 'capybara'
require 'capybara/poltergeist'
require 'csv'
require 'gdbm'

include Capybara::DSL
Capybara.default_driver = :poltergeist

visit &quot;http://ngauthier.com/&quot;

articles = GDBM.new(&quot;articles.db&quot;)
&lt;/pre&gt;

&lt;p&gt;We’ve required gdbm and now &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;articles&lt;/code&gt; is a GDBM store in a file in the current directory called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;articles.db&lt;/code&gt;. We can now use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;articles&lt;/code&gt; like a hash, and GDBM will sync it to the file system whenever we write to a key. Neat!&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
# Pass 1: summaries and info
all(&quot;.posts .post&quot;).each do |post|
  title = post.find(&quot;h3 a&quot;).text
  url   = post.find(&quot;h3 a&quot;)[&quot;href&quot;]
  date  = post.find(&quot;h3 small&quot;).text
  summary = post.find(&quot;p.preview&quot;).text

  next if articles[url]

  articles[url] = JSON.dump(
    title:   title,
    url:     url,
    date:    date,
    summary: summary
  )
end
&lt;/pre&gt;

&lt;p&gt;Now, we have a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;next if&lt;/code&gt; that checks to see if we already have the article. We don’t want to store it if we already have it, because that would overwrite the article (and we may have fetched the body).&lt;/p&gt;

&lt;p&gt;When we store it, we &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;JSON.dump&lt;/code&gt; our hash so that it’s a string.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
# Pass 2: full body of article
articles.each do |url, json|
  article = JSON.load(json)
  next if article[&quot;body&quot;]
  visit &quot;http://ngauthier.com#{url}&quot;
  has_content?(article[&quot;title&quot;]) or raise &quot;couldn't load #{url}&quot;
  article[&quot;body&quot;] = find(&quot;article&quot;).text
  articles[url] = JSON.dump(article)
end
&lt;/pre&gt;

&lt;p&gt;When we iterate a GDBM store it gives us a key-value pair, like a hash. So, we have to load up the article from JSON before we can work with it. Our keys also become strings instead of symbols, because it was loaded from JSON.&lt;/p&gt;

&lt;p&gt;We have another &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;next if&lt;/code&gt; that skips visiting the page if we have the body already. Additionally, we check the page for the title. This gives the page time to load, as opposed to accidentally scraping the last page’s content.&lt;/p&gt;

&lt;p&gt;Finally, we have to dump the article to JSON to store it again.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
# Output CSV
CSV do |csv|
  csv &amp;lt;&amp;lt; [&quot;Title&quot;, &quot;URL&quot;, &quot;Date&quot;, &quot;Summary&quot;, &quot;Body&quot;]
  articles.each do |url, json|
    article = JSON.load(json)
    csv &amp;lt;&amp;lt; [
      article[&quot;title&quot;],
      article[&quot;url&quot;],
      article[&quot;date&quot;],
      article[&quot;summary&quot;],
      article[&quot;body&quot;]
    ]
  end
end
&lt;/pre&gt;

&lt;p&gt;When we output to CSV, we have to load up the JSON to construct our CSV output.&lt;/p&gt;

&lt;p&gt;Now that GDBM is running, the first time I ran the scrape it took 7.3 seconds, and the second time, it took 1.7 seconds because it only hit the index and skipped scraping. I can also ctrl-c the program while it’s working, and re-run it and it will resume. Nice!&lt;/p&gt;

&lt;h1 id=&quot;object-oriented&quot;&gt;Object Oriented&lt;/h1&gt;

&lt;p&gt;OK at this point the code is pretty ugly and scripty, and some things are getting annoying. Let’s clean up this code.&lt;/p&gt;

&lt;h2 id=&quot;first-pass-base-class-instance-variables-and-method-splitting&quot;&gt;First Pass: Base Class, Instance Variables and Method Splitting&lt;/h2&gt;

&lt;p&gt;First off, we’re doing everything in the global scope, and Capybara complains every time we include &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Capybara::DSL&lt;/code&gt; in the global scope because it extends it with methods like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;find&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;visit&lt;/code&gt;. Convenient, but messy. Let’s create a base class called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NickBot&lt;/code&gt; and we’ll split up each phase into a method for readability.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/usr/bin/env ruby

require 'capybara'
require 'capybara/poltergeist'
require 'csv'
require 'gdbm'

class NickBot
  include Capybara::DSL

  def initialize(io = STDOUT)
    Capybara.default_driver = :poltergeist
    @articles = GDBM.new(&quot;ngauthier.db&quot;)
    @io = io
  end

  def scrape
    get_summaries
    get_bodies
    output_csv
  end

  def get_summaries
    visit &quot;http://ngauthier.com/&quot;
    all(&quot;.posts .post&quot;).each do |post|
      title = post.find(&quot;h3 a&quot;).text
      url   = post.find(&quot;h3 a&quot;)[&quot;href&quot;]
      date  = post.find(&quot;h3 small&quot;).text
      summary = post.find(&quot;p.preview&quot;).text

      next if @articles[url]

      @articles[url] = JSON.dump(
        title:   title,
        url:     url,
        date:    date,
        summary: summary
      )
    end
  end

  def get_bodies
    @articles.each do |url, json|
      article = JSON.load(json)
      next if article[&quot;body&quot;]
      visit &quot;http://ngauthier.com#{url}&quot;
      has_content?(article[&quot;title&quot;]) or raise &quot;couldn't load #{url}&quot;
      article[&quot;body&quot;] = find(&quot;article&quot;).text
      @articles[url] = JSON.dump(article)
    end
  end

  def output_csv
    CSV(@io) do |csv|
      csv &amp;lt;&amp;lt; [&quot;Title&quot;, &quot;URL&quot;, &quot;Date&quot;, &quot;Summary&quot;, &quot;Body&quot;]
      @articles.each do |url, json|
        article = JSON.load(json)
        csv &amp;lt;&amp;lt; [
          article[&quot;title&quot;],
          article[&quot;url&quot;],
          article[&quot;date&quot;],
          article[&quot;summary&quot;],
          article[&quot;body&quot;]
        ]
      end
    end
  end
end

NickBot.new(STDOUT).scrape
&lt;/pre&gt;

&lt;p&gt;OK, that’s better, but really all we did was push our veggies around our plate. We didn’t eat any of them.&lt;/p&gt;

&lt;h2 id=&quot;second-pass-article-class&quot;&gt;Second Pass: Article Class&lt;/h2&gt;

&lt;p&gt;Let’s start with an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Article&lt;/code&gt; that will wrap up parsing a Capybara node and dumping itself automatically. GDBM calls an object’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;to_str&lt;/code&gt; to dump it, so we can hook in there to dump ourselves to JSON:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/usr/bin/env ruby

require 'capybara'
require 'capybara/poltergeist'
require 'csv'
require 'gdbm'

class NickBot
  include Capybara::DSL

  def initialize(io = STDOUT)
    Capybara.default_driver = :poltergeist
    @articles = GDBM.new(&quot;ngauthier.db&quot;)
    @io = io
  end

  def scrape
    get_summaries
    get_bodies
    output_csv
  end

  def get_summaries
    visit &quot;http://ngauthier.com/&quot;
    all(&quot;.posts .post&quot;).each do |post|
      article = Article.from_summary(post)
      next if @articles[article.url]
      @articles[article.url] = article
    end
  end

  def get_bodies
    @articles.each do |url, json|
      article = Article.new(JSON.load(json))
      next if article.body
      visit &quot;http://ngauthier.com#{url}&quot;
      has_content?(article.title) or raise &quot;couldn't load #{url}&quot;
      article.body = find(&quot;article&quot;).text
      @articles[url] = article
    end
  end

  def output_csv
    CSV(@io) do |csv|
      csv &amp;lt;&amp;lt; [&quot;Title&quot;, &quot;URL&quot;, &quot;Date&quot;, &quot;Summary&quot;, &quot;Body&quot;]
      @articles.each do |url, json|
        article = Article.new(JSON.load(json))
        csv &amp;lt;&amp;lt; [
          article.title,
          article.url,
          article.date,
          article.summary,
          article.body
        ]
      end
    end
  end

  class Article &amp;lt; OpenStruct
    def self.from_summary(node)
      new(
        title:   node.find(&quot;h3 a&quot;).text,
        url:     node.find(&quot;h3 a&quot;)[&quot;href&quot;],
        date:    node.find(&quot;h3 small&quot;).text,
        summary: node.find(&quot;p.preview&quot;).text,
      )
    end

    def to_str
      to_h.to_json
    end
  end
end

NickBot.new(STDOUT).scrape
&lt;/pre&gt;

&lt;p&gt;We’re using OpenStruct here to cheaply get a hash-to-object conversion so we can use dot notation to access fields. This makes it feel way more like an object. It also means we could replace the accessors later transparently.&lt;/p&gt;

&lt;p&gt;This is better, but we still have a few issues with entanglement between NickBot and Article:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;NickBot has to remember to &lt;em&gt;load&lt;/em&gt; an Article from JSON&lt;/li&gt;
  &lt;li&gt;NickBot holds the database information where Articles are stored&lt;/li&gt;
  &lt;li&gt;NickBot has to know how GDBM works in order to iterate&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s clean this up next.&lt;/p&gt;

&lt;h2 id=&quot;third-pass-active-record-pattern&quot;&gt;Third Pass: Active Record Pattern&lt;/h2&gt;

&lt;p&gt;We’re going to implement the Active Record Pattern. No, I’m not going to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;require 'activerecord'&lt;/code&gt;, I’m talking about the classic &lt;a href=&quot;http://en.wikipedia.org/wiki/Active_record_pattern&quot;&gt;Active Record Pattern&lt;/a&gt; from &lt;em&gt;Patterns of Enterprise Application Architecture&lt;/em&gt;. The key here is to mix in the database behavior with the Article class so it can handle iteration, storage, and retrieval without NickBot having to understand how it works.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/usr/bin/env ruby

require 'capybara'
require 'capybara/poltergeist'
require 'csv'
require 'gdbm'

class NickBot
  include Capybara::DSL

  def initialize(io = STDOUT)
    Capybara.default_driver = :poltergeist
    @io = io
  end

  def scrape
    visit &quot;http://ngauthier.com/&quot;
    all(&quot;.posts .post&quot;).each do |post|
      article = Article.from_summary(post)
      next unless article.new_record?
      article.save
    end

    Article.each do |article|
      next if article.body
      visit &quot;http://ngauthier.com#{article.url}&quot;
      has_content?(article.title) or raise &quot;couldn't load #{url}&quot;
      article.body = find(&quot;article&quot;).text
      article.save
    end

    CSV(@io) do |csv|
      csv &amp;lt;&amp;lt; [&quot;Title&quot;, &quot;URL&quot;, &quot;Date&quot;, &quot;Summary&quot;, &quot;Body&quot;]
      Article.each do |article|
        csv &amp;lt;&amp;lt; [
          article.title,
          article.url,
          article.date,
          article.summary,
          article.body
        ]
      end
    end
  end
&lt;/pre&gt;

&lt;p&gt;Let’s start looking at the usage of Article above. We’ve added &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Article#new_record?&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Article#save&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Article.each&lt;/code&gt;. But also notice that NickBot no longer has an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@articles&lt;/code&gt; instance variable. Cool! Now NickBot doesn’t care at all how Articles are persisted.&lt;/p&gt;

&lt;p&gt;Let’s take a look at our new Article class.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
  class Article &amp;lt; OpenStruct
    DB = GDBM.new(&quot;articles.db&quot;)

    def self.from_summary(node)
      new(
        title:   node.find(&quot;h3 a&quot;).text,
        url:     node.find(&quot;h3 a&quot;)[&quot;href&quot;],
        date:    node.find(&quot;h3 small&quot;).text,
        summary: node.find(&quot;p.preview&quot;).text,
      )
    end

    def self.each
      DB.each do |url, json|
        yield Article.new(JSON.load(json))
      end
    end

    def save
      DB[url] = to_h.to_json
    end

    def new_record?
      DB[url].nil?
    end
  end
end
&lt;/pre&gt;

&lt;p&gt;It still inherits from OpenStruct, because that gives us our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;initialize(attributes)&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;to_h&lt;/code&gt; for cheap. But now we have a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DB&lt;/code&gt; constant that is set when the code loads up and connects to our GDBM file. This simple constant allows the Article class and also Article instances to access the GDBM database file.&lt;/p&gt;

&lt;p&gt;We can now write an easy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;each&lt;/code&gt; that iterates the database and does the JSON load. We can also write our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;save&lt;/code&gt; that dumps using JSON. The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;new_record?&lt;/code&gt; is simply a check for an existing key.&lt;/p&gt;

&lt;p&gt;The cool thing is, we could switch our GDBM implementation our for any other type of persistence. We could be using PostgreSQL if we needed more structure, or maybe Redis if we wanted to run it on Heroku with minimal changes.&lt;/p&gt;

&lt;h1 id=&quot;wrap-up&quot;&gt;Wrap-up&lt;/h1&gt;

&lt;p&gt;I’ve found GDBM to be a really useful little library, because when I am writing utility scripts I don’t want to maintain a PostgreSQL database, but I also need some persistence and reliability. It’s a great step up from writing to csv repeatedly (which is pretty slow and also error prone when the program crashes during a write!).&lt;/p&gt;

&lt;p&gt;I continue to find wonderful nuggets of awesome in Ruby’s standard library all the time!&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://gist.github.com/ngauthier/0f78598f2aaecab8f1bc&quot;&gt;Final source code available as a gist&lt;/a&gt;.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Using Docker to Parallelize Rails Tests</title>
    <link href="http://ngauthier.com/2013/10/using-docker-to-parallelize-rails-tests.html"/>
    <updated>2013-10-13T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2013/10/using-docker-to-parallelize-rails-tests</id>
    <content type="html">&lt;p&gt;Docker is a new way to containerize services. The primary use so far has been for deploying services in a very thin container. I experimented with using it for Rails Continuous Integration so that I could run tests within a consistent environment, and then I realized that the containers provide excellent encapsulation to allow for parallelization of test suites.&lt;/p&gt;

&lt;p&gt;There are three things we’ll have to do to run a Rails test suite in parallel in docker:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Create a Dockerfile for a system that can run our tests, and build the container&lt;/li&gt;
  &lt;li&gt;Create a script that breaks our tests across multiple containers&lt;/li&gt;
  &lt;li&gt;Create a script to run the tests within an individual container&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;dockerfile-and-container&quot;&gt;Dockerfile and Container&lt;/h2&gt;

&lt;p&gt;Dockerfiles are quite simple. The majority of the commands are usually RUN commands that run instructions on the container. Let’s take a look:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
from tianon/debian:sid
maintainer Nick Gauthier ngauthier@gmail.com

run apt-get update
run apt-get -qy dist-upgrade

run apt-get install -yq postgresql-9.3 libpq-dev nodejs ruby2.0 ruby2.0-dev build-essential
run gem install bundler --no-ri --no-rdoc --pre
&lt;/pre&gt;

&lt;p&gt;The FROM line bases our container off of debian unstable. I’m using this source because it has ruby 2.0 and postgresql 9.3 right in apt, so the installation is minimal and fast.&lt;/p&gt;

&lt;p&gt;Then, we update the system, install postgresql, node (for assets), ruby, and building libraries for gem extenions.&lt;/p&gt;

&lt;p&gt;Finally, we install bundler.&lt;/p&gt;

&lt;p&gt;Now, we can build our container via:&lt;/p&gt;

&lt;pre&gt;
docker build -t username/appname .
&lt;/pre&gt;

&lt;p&gt;That will build the current directory’s container and tag it with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;username/appname&lt;/code&gt; (so you should replace that with your name and your app’s name). I am not sure yet how to do this in a more portable and anonymous fashion.&lt;/p&gt;

&lt;h2 id=&quot;parallelization-script&quot;&gt;Parallelization Script&lt;/h2&gt;

&lt;p&gt;Next, we’re going to write &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bin/docker-ci&lt;/code&gt;. The goal of this script is to split our tests across multiple containers, and ultimately call &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bin/ci&lt;/code&gt; &lt;em&gt;within&lt;/em&gt; the containers.&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bin/docker-ci&lt;/code&gt;&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/usr/bin/env bash
set -e

# Make our tmp directory for gems
mkdir -p /tmp/docker

# Docker options:
# Mount the current directory to /data/code
# Mount the temp directory to /data/gems
# Set GEM_HOME to the data directory
# Set the working directory to the code directory
# Use our built container
opts=&quot;-v `readlink -f .`:/data/code
      -v /tmp/docker:/data/gems
      -e GEM_HOME=/data/gems
      -w /data/code
      username/appname&quot;

# Bundle the gems (once, serially)
docker run $opts bundle --quiet

# Spread test files in large groups, and pass them into the
# container's bin/ci method
ls test/**/*_test.rb | parallel -X docker run $opts /data/code/bin/ci
&lt;/pre&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-v&lt;/code&gt; options allow us to share the current machine’s code directory with the container. One issue here is that any file system operations within the code folder could conflict across containers.&lt;/p&gt;

&lt;p&gt;We’re using GNU parallel with the -X flag, which will spread the test files into larger chunks, as oposed to one job per test file. I don’t think this perfectly utilizes all the cores on my machine, so some more tweaking could be done here.&lt;/p&gt;

&lt;p&gt;At this point, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bin/ci&lt;/code&gt; is run with one or more test files as parameters.&lt;/p&gt;

&lt;h2 id=&quot;test-running-script&quot;&gt;Test running script&lt;/h2&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bin/ci&lt;/code&gt; script needs to run a set of test files, and it will also need to initialize the container so that the suite can run.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/usr/bin/env bash
set -e
# Start postgresql
service postgresql start
# Create the db
su -c &quot;createuser root -s&quot; postgres
# prep the db
bundle exec rake db:test:prepare
# require test files from the arguments given to this script
ruby -I.:test -e &quot;ARGV.each{|f| require f}&quot; $*
&lt;/pre&gt;

&lt;p&gt;We have to boot up and initialize postgresql because containers don’t preserve running services, they are simply file systems that can be booted up. We also want to do this each time because we’d rather load the db than build it into the container and have to rebuild the container when our schema changes.&lt;/p&gt;

&lt;p&gt;I’m using ruby with require, but here you could substitute any way that says “run the following test files”. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rspec&lt;/code&gt;’s binary would work well, and also the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;m&lt;/code&gt; binary. I just stuck a simple ruby script here that should be suite-agnostic.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;And that’s it! It’s actually fairly simple, but it took me a while to stick everything together. I think there are certainly some refinements to be made to generalize it a bit better. For example, you could use any container from the docker index that provides a good rails base for your app. That way you wouldn’t have to maintain a Dockerfile in the project.&lt;/p&gt;

&lt;p&gt;Also, I’m not currently seeing any performance improvements due to the parallelization, but that’s because it’s a very short suite, so the overhead of doing a bundle check and db initialization outweighs the savings of parallelism.&lt;/p&gt;

&lt;p&gt;Try it on your app, I’d love to hear the results.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>PostGIS and Rails: A Simple Approach</title>
    <link href="http://ngauthier.com/2013/08/postgis-and-rails-a-simple-approach.html"/>
    <updated>2013-08-18T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2013/08/postgis-and-rails-a-simple-approach</id>
    <content type="html">&lt;p&gt;PostGIS is a geospatial extension library for PostgreSQL that allows you to perform a ton of geometric and geographic operations on your data at high speeds. For example:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Compute the distance between two points&lt;/li&gt;
  &lt;li&gt;Find all the points within X meters of point P&lt;/li&gt;
  &lt;li&gt;Determine which points are enclosed in polygon P&lt;/li&gt;
  &lt;li&gt;A million other things&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In Ruby land, there is a gem called &lt;a href=&quot;http://rdoc.info/gems/rgeo/frames&quot;&gt;RGeo&lt;/a&gt; that provides a ton of objects and methods for handling Geospatial objects. In Rails, there are a number of ActiveRecord adapters for each database driver that serialize and deserialize these objects to and from their natural types in the database and RGeo types (for example, &lt;a href=&quot;http://rdoc.info/gems/activerecord-postgis-adapter/frames&quot;&gt;activerecord-postgis-adapter&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;They are both great and powerful gems that can handle the majority (if not all) of the kinds of things you’d like to do with a geospatial database.&lt;/p&gt;

&lt;p&gt;However, since Rails doesn’t have hooks in place to extend the existing drivers with new ways to handle new data types, the ActiveRecord drivers are a (well maintained) collection of subclasses with key methods copied and modified from the originals.&lt;/p&gt;

&lt;p&gt;This means that they are &lt;a href=&quot;https://github.com/dazuma/activerecord-postgis-adapter/blob/master/Documentation.rdoc&quot;&gt;difficult to setup and can be hard to use&lt;/a&gt;. However, it certainly can be done.&lt;/p&gt;

&lt;h2 id=&quot;a-simpler-approach&quot;&gt;A Simpler Approach&lt;/h2&gt;

&lt;p&gt;Despite the enormous power of these libraries, I tend to only need one or two features, and it’s usually the simple stuff. Like “Find all the bars near the current user”.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In this post, we’re going to explore how to use PostGIS with Rails with a few snippets of raw SQL and a couple of advanced PostgreSQL features.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-setup&quot;&gt;1. Setup&lt;/h2&gt;

&lt;p&gt;First off, you should have Ruby 2 and Rails 4 already installed. If not, go look for guides on that first.&lt;/p&gt;

&lt;p&gt;PostgreSQL ships with all the major linux distributions, and is available via homebrew on a Mac. However, &lt;strong&gt;that’s not how you want to install them&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;os-x&quot;&gt;OS X&lt;/h3&gt;

&lt;p&gt;On OS X, the best way to get PostgreSQL with PostGIS and other advanced features is with Heroku’s &lt;a href=&quot;http://postgresapp.com/&quot;&gt;PostgreSQL.app&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://github.com/PostgresApp/PostgresApp/issues/109&quot;&gt;Currently, the most recent build is having problems with PostGIS (issue #109)&lt;/a&gt;&lt;/strong&gt;. In the mean time, use this link to run a previous build of PostgreSQL.app:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://postgres-app.s3.amazonaws.com/PostgresApp-9-2-2-0.zip&quot;&gt;http://postgres-app.s3.amazonaws.com/PostgresApp-9-2-2-0.zip&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once issue #109 is resolved, the current build should work.&lt;/p&gt;

&lt;h3 id=&quot;linux&quot;&gt;Linux&lt;/h3&gt;

&lt;p&gt;On linux, most package managers are lagging a bit behind the current PostgreSQL version. PostgreSQL has setup repositories for BSD, the RedHat family, Debian/Ubuntu, SuSE, and more &lt;a href=&quot;http://www.postgresql.org/download/&quot;&gt;on their download page&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;On Debian and Ubuntu, you’ll want to use their apt repository. Edit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/etc/apt/sources.list.d/pgdg.list&lt;/code&gt; and paste:&lt;/p&gt;

&lt;pre&gt;
deb http://apt.postgresql.org/pub/repos/apt/ YOUR_UBUNTU_VERSION_HERE-pgdg main
&lt;/pre&gt;

&lt;p&gt;Then, import the repository key:&lt;/p&gt;

&lt;pre&gt;
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | \
  sudo apt-key add -
sudo apt-get update
&lt;/pre&gt;

&lt;p&gt;Finally, install PostgreSQL 9.2, the contrib package, and PostGIS 2.0 scripts:&lt;/p&gt;

&lt;pre&gt;
sudo apt-get install postgresql-9.2 postgresql-contrib-9.2 postgresql-server-dev-9.2 postgresql-9.2-postgis-2.0-scripts
&lt;/pre&gt;

&lt;p&gt;(Note that if you have a previous version of PostgreSQL installed side-by-side, PostgreSQL 9.2 may run on a non-standard port so as not to conflict with the old version)&lt;/p&gt;

&lt;h3 id=&quot;test-your-installation&quot;&gt;Test your installation&lt;/h3&gt;

&lt;p&gt;To test your installation, make a database and attempt to enable PostGIS:&lt;/p&gt;

&lt;pre&gt;
$ psql
psql (9.2.4)
Type &quot;help&quot; for help.

nick=# create database postgis_test;
CREATE DATABASE
nick=# \c postgis_test
You are now connected to database &quot;postgis_test&quot; as user &quot;nick&quot;.
postgis_test=# create extension postgis;
CREATE EXTENSION
postgis_test=# 
&lt;/pre&gt;

&lt;p&gt;If it doesn’t complain, it worked!&lt;/p&gt;

&lt;h2 id=&quot;2-refuelly&quot;&gt;2. Refuelly&lt;/h2&gt;

&lt;p&gt;In order to demonstrate the steps involved, we need a demo project. We’ll be writing an app called Refuelly that will help users find the nearest place to get coffee. We won’t build the whole app, just the models necessary to ask the following question: “What are the top 10 closest places to a given location?”&lt;/p&gt;

&lt;p&gt;Let’s make the app:&lt;/p&gt;

&lt;pre&gt;
$ rails new refuelly -d postgresql
      create  
      create  README.rdoc
      create  Rakefile
      create  config.ru
      ... etc ...
$ cd refuelly
$ bundle update
&lt;/pre&gt;

&lt;p&gt;At this point, I edited the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config/database.yml&lt;/code&gt; to suit my machine. I’m in linux, so I simply removed the username and password since I have myself setup as a superuser.&lt;/p&gt;

&lt;p&gt;Since we will be using some raw SQL, we need to switch from a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;schema.rb&lt;/code&gt; to a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;structure.sql&lt;/code&gt;. This means that in development, we’re going to save our database snapshot in raw SQL, not Rails’s Ruby representation.&lt;/p&gt;

&lt;p&gt;Edit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config/application.rb&lt;/code&gt; and add this line inside the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;class Application&lt;/code&gt; near the other commented out config statements:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
config.active_record.schema_format = :sql
&lt;/pre&gt;

&lt;p&gt;Now, create the database and a structure file should exist:&lt;/p&gt;

&lt;pre&gt;
$ rake db:create db:migrate
$ ls db/structure.sql 
db/structure.sql
&lt;/pre&gt;

&lt;p&gt;Great, now our app is setup with PostgreSQL. This is a good time to commit your code.&lt;/p&gt;

&lt;h2 id=&quot;2-cafe&quot;&gt;2. Cafe&lt;/h2&gt;

&lt;p&gt;We need a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cafe&lt;/code&gt; model to represent a coffee shop. It will have a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;name&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;latitude&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;longitude&lt;/code&gt;. Let’s create it:&lt;/p&gt;

&lt;pre&gt;
$ rails generate model cafe \
    name:string &quot;latitude:decimal{9,6}&quot; &quot;longitude:decimal{9,6}&quot; \
    --fixture false
      invoke  active_record
      create    db/migrate/20130818184035_create_caves.rb
      create    app/models/cafe.rb
      invoke    test_unit
      create      test/models/cafe_test.rb
&lt;/pre&gt;

&lt;p&gt;We’re going to store latitude and longitude as decimal types with precision 9 and scale 6. That means there will be a total of 6 digits right of the decimal, and 9 total digits. PostgreSQL will secretly store this as an integer with an order of magnitude (like scientific notation). That way, there are no floating point errors. This is what the PostgreSQL &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;money&lt;/code&gt; type is, under the hood. That way, it keeps the decimal point in the right place for us and doesn’t lose precision.&lt;/p&gt;

&lt;p&gt;Hilariously, Rails pluralizes cafe to caves, so real quick &lt;strong&gt;edit the migration and change it to cafes&lt;/strong&gt; (don’t forget to rename the file too). If you’re a stickler like me, you should also mark every column &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null: false&lt;/code&gt;. Also, edit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app/models/cafe.rb&lt;/code&gt; and add:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;self.table_name = &quot;cafes&quot;&lt;/pre&gt;

&lt;p&gt;Now, migrate:&lt;/p&gt;

&lt;pre&gt;
$ rake db:migrate
==  CreateCafes: migrating ====================================================
-- create_table(:cafes)
   -&amp;gt; 0.0141s
==  CreateCafes: migrated (0.0143s) ===========================================
&lt;/pre&gt;

&lt;p&gt;Now is another great time to commit.&lt;/p&gt;

&lt;h2 id=&quot;3-query-on-computed-points&quot;&gt;3. Query on computed points&lt;/h2&gt;

&lt;p&gt;Our next goal is to be able to create some cafes and then query to find the closest ones to a given point. So, let’s write a test to help us develop the code. Inside &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;test/models/cafe_test.rb&lt;/code&gt; add:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
test &quot;close cafes&quot; do
  far_cafe = Cafe.create!(
    name:      &quot;Far Cafe&quot;,
    latitude:   40.000000,
    longitude: -77.000000
  )

  close_cafe = Cafe.create!(
    name:      &quot;Close Cafe&quot;,
    latitude:   39.010000,
    longitude: -75.990000
  )

  close_cafes = Cafe.close_to(39.000000, -76.000000).load

  assert_equal 1,          close_cafes.size
  assert_equal close_cafe, close_cafes.first
end
&lt;/pre&gt;

&lt;p&gt;Here we’re creating two cafes and we expect the close cafe to be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;close_to&lt;/code&gt; the point, but not the far one.&lt;/p&gt;

&lt;p&gt;(p.s., we’re calling &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;load&lt;/code&gt; for prettier sql for later, normally this is &lt;em&gt;not&lt;/em&gt; a good idea)&lt;/p&gt;

&lt;p&gt;To solve this, we need to do two things. First, add PostGIS:&lt;/p&gt;

&lt;pre&gt;
$ rails generate migration enable_postgis
&lt;/pre&gt;

&lt;p&gt;Edit the migration, and write:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
class EnablePostgis &amp;lt; ActiveRecord::Migration
  def change
    enable_extension :postgis
  end
end
&lt;/pre&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;enable_extension&lt;/code&gt; is new in Rails 4, and it abstracts PostgreSQL’s extension commands for us. Nice!&lt;/p&gt;

&lt;p&gt;Next, we need to write our scope on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cafe&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
scope :close_to, -&amp;gt; (latitude, longitude, distance_in_meters = 2000) {
  where(%{
    ST_DWithin(
      ST_GeographyFromText(
        'SRID=4326;POINT(' || cafes.longitude || ' ' || cafes.latitude || ')'
      ),
      ST_GeographyFromText('SRID=4326;POINT(%f %f)'),
      %d
    )
  } % [longitude, latitude, distance_in_meters])
}
&lt;/pre&gt;

&lt;p&gt;This should pass our test. Let’s talk about what’s going on.&lt;/p&gt;

&lt;p&gt;We’re making a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;where&lt;/code&gt; scope on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cafe&lt;/code&gt; that uses the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ST_DWithin&lt;/code&gt; function to find all the cafes with a certain distance of a given point. The third parameter here is the distance in meters, and our default is 2km.&lt;/p&gt;

&lt;p&gt;Then, we’re providing two point objects via &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ST_GeographyFromText&lt;/code&gt;. This function converts some text in Well Known Text (WKT) format to the binary format used by PostGIS to represent points. An example of WKT would be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SRID=4326;POINT(-76.000000 39.000000)&lt;/code&gt;. The first parameter sets the SRID to 4326 (a projection representing the whole globe) and then builds a string for a point featuring the cafe’s longitude and latitude. This builds a point on the fly for each cafe in the cafes table.&lt;/p&gt;

&lt;p&gt;The second point object builds a point using the parameters passed in to the scope lambda, the lat and lon. We use Ruby’s built-in string interpolation to easily encode two floating point numbers. It’s safe and it let’s us avoid ActiveRecord’s quoting, which would mess up the SQL.&lt;/p&gt;

&lt;p&gt;As you can see, I’m computing everything on the fly. That means whenever this query is run, we’re converting all the cafes’ latitudes and longitudes into points and also converting our query point into a point, then scanning every cafe and manually computing distance. This is super slow.&lt;/p&gt;

&lt;p&gt;But it passes our test. Commit!&lt;/p&gt;

&lt;h2 id=&quot;4-at-scale&quot;&gt;4. At scale&lt;/h2&gt;

&lt;p&gt;OK, so it works, but it’s probably slow (we don’t really know yet how slow, do we?). So, let’s investigate!&lt;/p&gt;

&lt;p&gt;First, we need some test data. Open up a psql console and insert 1 million random cafes:&lt;/p&gt;

&lt;pre&gt;
$ rails dbconsole
psql (9.2.4)
Type &quot;help&quot; for help.

refuelly_development=#
insert into cafes (name, latitude, longitude) (
  select 'Cafe ' || i as name, 39 + x.lat as latitude, -76 - x.lon as longitude
  from (
    select i, random() * 10 as lat, random() * 10 as lon
    from generate_series(1,1000000) as i
  )                                                            
as x );
&lt;/pre&gt;

&lt;p&gt;For speed, we do this in PostgreSQL so that Rails doesn’t chug along making model objects. We’re making a million restaurants within 10 minutes of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;39, -76&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now, when we ran our test, you can look in the logs to find the query Rails puts together. It looks like this:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
SELECT &quot;cafes&quot;.* FROM &quot;cafes&quot; WHERE (
 ST_DWithin(
 ST_GeographyFromText(
 'SRID=4326;POINT(' || cafes.longitude || ' ' || cafes.latitude || ')'
 ),
 ST_GeographyFromText('SRID=4326;POINT(-76.000000 39.000000)'),
 2000
 )
 )
&lt;/pre&gt;

&lt;p&gt;Simply copy and paste that into your postgresql console (and a semicolon), and it should output the result. I happened to get 8 rows, and it took my computer around 3 seconds.&lt;/p&gt;

&lt;p&gt;Let’s use PostgreSQL’s built-in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;EXPLAIN&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ANALYZE&lt;/code&gt; tools:&lt;/p&gt;

&lt;pre&gt;
refuelly_development=# EXPLAIN ANALYZE SELECT &quot;cafes&quot;.* FROM &quot;cafes&quot; WHERE (
 ST_DWithin(
 ST_GeographyFromText(
 'SRID=4326;POINT(' || cafes.longitude || ' ' || cafes.latitude || ')'
 ),
 ST_GeographyFromText('SRID=4326;POINT(-76.000000 39.000000)'),
 2000
 )

 Seq Scan on cafes  (cost=0.00..355927.00 rows=37036 width=47) (actual time=612.698..3435.187 rows=8 loops=1)
   Filter: ((snipped))
   Rows Removed by Filter: 999992
 Total runtime: 3435.256 ms
&lt;/pre&gt;

&lt;p&gt;As you can see from the first line, we’re doing a Sequence Scan, which means we’re looking at &lt;em&gt;every single cafe&lt;/em&gt;. Then we have a filter (I removed it from the output) which is our distance query and checks each cafe. Finally, you can see the total runtime of ~3.4 seconds.&lt;/p&gt;

&lt;p&gt;Yup. It’s slow.&lt;/p&gt;

&lt;h2 id=&quot;5-indexing&quot;&gt;5. Indexing&lt;/h2&gt;

&lt;p&gt;So, now what? Normally, we’d store the cafe’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;location&lt;/code&gt; as a computed point field of the latitude and longitude. However, that’s going to be really annoying because rails will get really confused trying to treat that point field like a string. This is the pain that the activerecord-postgis-adapter family of gems help fix.&lt;/p&gt;

&lt;p&gt;But, we’re going to do something much more awesome and clever. We’re going to use PostgreSQL’s ability to index on expressions.&lt;/p&gt;

&lt;p&gt;Unlike MySQL, PostgreSQL allows you to build an index on any expression you want. The simplest expression would simply be a column name, like this:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
create index index_users_on_email on users (email)
&lt;/pre&gt;

&lt;p&gt;The chunk inside the parens is the expression. So, if you always searched users by their lowercased email, you could make an optimized index just for that function, like this:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
create index index_users_on_email on users (lower(email))
&lt;/pre&gt;

&lt;p&gt;Now, postgresql will keep an index filled with downcased email addresses that are ready to be queried without having to perform the lowering at runtime. Sweet.&lt;/p&gt;

&lt;p&gt;So, what we’re going to do is &lt;strong&gt;index on a point built from cafe’s longitude and latitude&lt;/strong&gt;. It’s pretty easy, we just copy our SQL fragment from our query and turn it into an index:&lt;/p&gt;

&lt;pre&gt;
$ rails generate migration add_point_index_to_cafes
&lt;/pre&gt;

&lt;p&gt;Edit the migration and write:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
class AddPointIndexToCafes &amp;lt; ActiveRecord::Migration
  def up
    execute %{
      create index index_on_cafes_location ON cafes using gist (
        ST_GeographyFromText(
          'SRID=4326;POINT(' || cafes.longitude || ' ' || cafes.latitude || ')'
        )
      )
    }
  end

  def down
    execute %{drop index index_on_cafes_location}
  end
end
&lt;/pre&gt;

&lt;p&gt;Our index’s expression will be a point built from the latitude and longitude. Now, when our distance query asks for this built point, our index will match the query and be usable for our distance calculation.&lt;/p&gt;

&lt;p&gt;Migrate your database (this will take a little bit because it has to index the million points already in the db, for me it took 18 seconds)&lt;/p&gt;

&lt;pre&gt;
$ rake db:migrate

==  AddPointIndexToCafes: migrating ===========================================
-- execute(&quot;\n      create index index_on_cafes_location ON cafes using gist (\n        ST_GeographyFromText(\n          'SRID=4326;POINT(' || cafes.longitude || ' ' || cafes.latitude || ')'\n        )\n      )\n    &quot;)
   -&amp;gt; 18.7678s
==  AddPointIndexToCafes: migrated (18.7680s) =================================
&lt;/pre&gt;

&lt;p&gt;Now, let’s re-run our explained distance query:&lt;/p&gt;

&lt;pre&gt;
refuelly_development=# explain analyze SELECT &quot;cafes&quot;.* FROM &quot;cafes&quot; WHERE (
 ST_DWithin(
 ST_GeographyFromText(
 'SRID=4326;POINT(' || cafes.longitude || ' ' || cafes.latitude || ')'
 ),
 ST_GeographyFromText('SRID=4326;POINT(-76.000000 39.000000)'),
 2000
 )
 )

 Bitmap Heap Scan on cafes  (cost=13665.84..133655.39 rows=37036 width=47) (actual time=0.543..1.054 rows=10 loops=1)
   Recheck Cond: (cafe within distance bounding box of point)
   Filter: (cafe within distance bounding box of point and within exact distance of point)
   Rows Removed by Filter: 4
   -&amp;gt;  Bitmap Index Scan on index_on_cafes_location  (cost=0.00..13656.58 rows=333330 width=0) (actual time=0.119..0.119 rows=14 loops=1)
         Index Cond: (cafe within distance bounding box of point)
 Total runtime: 1.155 ms
&lt;/pre&gt;

&lt;p&gt;Boom, 1ms for the query. If you look at the explain output, you’ll see we’re now doing (from the bottom up) a bitmap index scan using our index (it does a pass with just a bounding box for speed), then a filter with exact distance, then it rechecks with the bounding box.&lt;/p&gt;

&lt;h2 id=&quot;6-conclusion&quot;&gt;6. Conclusion&lt;/h2&gt;

&lt;p&gt;In conclusion, there are a number of pros and cons to this solution.&lt;/p&gt;

&lt;p&gt;It’s great that on our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cafe&lt;/code&gt; we simply use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;latitude&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;longitude&lt;/code&gt; attributes. No serializers, factories, or callbacks involved. Rails is perfectly happy.&lt;/p&gt;

&lt;p&gt;There are no extra gems needed, which means no extra dependencies, version lag, or compatibility issues with the driver.&lt;/p&gt;

&lt;p&gt;Indexing can be done and queries are very fast.&lt;/p&gt;

&lt;p&gt;However, we did have to hand-write a bunch of SQL, which is always less than optimal. In this case, I’m OK with it, because PostGIS is really the best tool for the job here. We also have to keep the SQL in our query synchronized with our index, but that’s the case with any index on an expression.&lt;/p&gt;

&lt;p&gt;All-in-all, I prefer this solution because it’s smaller, simpler, and lighter weight for accomplishing simple tasks with geospatial data on Rails.&lt;/p&gt;

&lt;h2 id=&quot;source-code&quot;&gt;Source Code&lt;/h2&gt;

&lt;p&gt;The source code resulting from this post is available at &lt;a href=&quot;http://github.com/ngauthier/postgis-on-rails-example&quot;&gt;github.com/ngauthier/postgis-on-rails-example&lt;/a&gt;.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Learning Angular on Rails</title>
    <link href="http://ngauthier.com/2013/04/learning-angular-on-rails.html"/>
    <updated>2013-04-29T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2013/04/learning-angular-on-rails</id>
    <content type="html">&lt;p&gt;Last night I had the best idea for a JavaScript framework. It was going to use the dom with data attributes in a totally unobtrusive way. It would have global repositories for remote data, do caching, and attach controllers to the dom automatically.&lt;/p&gt;

&lt;p&gt;This morning, I realized that’s pretty much how Angular.js rolls, so I decided to learn the basics.&lt;/p&gt;

&lt;h2 id=&quot;1-setup-rails&quot;&gt;1. Setup Rails&lt;/h2&gt;

&lt;p&gt;First, I setup a Rails app as the back-end. I used Rails 4.0.0.beta1. I also decided that since Angular does so much heavy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;data-attr&lt;/code&gt; (actually &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ng-attr&lt;/code&gt;) work in the view, I wanted something nicer than erb, so I added Slim for templating. Also, I like CoffeeScript, so I stuck with that.&lt;/p&gt;

&lt;p&gt;I setup a Post model and controller. Angular behaved a little differently, so the controller looks a little different:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
class PostsController &amp;lt; ApplicationController
  include AngularController

  def index
    @posts = Post.all
    respond_with @posts
  end

  def create
    respond_with Post.create!(params.permit(:title, :body))
  end

  def destroy
    Post.destroy(params[:id])
    head :ok
  end
end
&lt;/pre&gt;

&lt;p&gt;I’m using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;respond_with&lt;/code&gt; to send the html template on index or json for the index, depending on the request. I also use it in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;create&lt;/code&gt; action because that will send down json automatically, and I find it cleaner than &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;render json: post&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I created a Concern called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AngularController&lt;/code&gt; that abstracted the necessary json massaging that Angular needed:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
module AngularController
  extend ActiveSupport::Concern

  included do
    respond_to :html, :json
    around_action :without_root_in_json
  end

  def without_root_in_json
    ActiveRecord::Base.include_root_in_json = false
    yield
    ActiveRecord::Base.include_root_in_json = true
  end
end
&lt;/pre&gt;

&lt;p&gt;It adds the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;respond_to&lt;/code&gt; to work with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;respond_with&lt;/code&gt;. It also sets up an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;around_action&lt;/code&gt; to temporarily remove the root of json responses. I thought this was a cool way to do it, instead of doing it globally.&lt;/p&gt;

&lt;p&gt;Now the Rails app is setup. I actually set it up while learning angular, but I thought I’d present it here first for simplicity’s sake.&lt;/p&gt;

&lt;h1 id=&quot;2-angular-time&quot;&gt;2. Angular Time!&lt;/h1&gt;

&lt;p&gt;I grabbed &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;angular.js&lt;/code&gt; and also &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;angular-resource.js&lt;/code&gt; (RESTful requests) and dropped them into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vendor/assets/javascripts&lt;/code&gt;, as well as loading up Twitter Bootstrap to make it look Not Terrible™.&lt;/p&gt;

&lt;p&gt;In &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app/views/index.html.slim&lt;/code&gt; I added:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
- content_for :ng_app, &quot;blang&quot;

.container
  .hero-unit
    h1 Posts
    p Driven by Angular.js

  div ng-controller=&quot;PostCtrl&quot;
    .post ng-repeat=&quot;post in posts&quot;
      h2 
        | {{ post.title }}
        button.btn.btn-danger.btn-small.pull-right ng-click=&quot;delete($index)&quot; &amp;times;
      | {{ post.body }}

    form ng-submit=&quot;add()&quot; action=&quot;&quot;
      fieldset
        legend Create Post
        
        input    ng-model=&quot;post.title&quot; type=&quot;text&quot; id=&quot;post-title&quot; placeholder=&quot;Title&quot;
        br
        textarea ng-model=&quot;post.body&quot; placeholder=&quot;Content&quot; rows=&quot;4&quot; columns=&quot;40&quot;
        br

        input.btn.btn-primary type=&quot;submit&quot; value=&quot;Create&quot;
&lt;/pre&gt;

&lt;p&gt;I use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;content_for :ng_app&lt;/code&gt; in the layout to render Angular’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ng-app=&quot;blang&quot;&lt;/code&gt; so that it boots up. The page is driven by the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PostCtrl&lt;/code&gt; controller, and it loops over all the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;posts&lt;/code&gt; in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PostCtrl&lt;/code&gt;. It outputs their title and body, along with a delete button.&lt;/p&gt;

&lt;p&gt;Below, there’s a form that hits the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;add()&lt;/code&gt; method of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PostCtrl&lt;/code&gt; feeding it the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;title&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;body&lt;/code&gt; of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;post&lt;/code&gt; that we’re creating.&lt;/p&gt;

&lt;p&gt;Here’s my &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;posts.coffee&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
# Set up the module
window.Blang = angular.module(&quot;blang&quot;, [&quot;ngResource&quot;])

Blang.config [&quot;$httpProvider&quot;, ($httpProvider) -&amp;gt;
  # Inject the CSRF token
  $httpProvider.defaults.headers.common['X-CSRF-Token'] = document.getElementsByName(&quot;csrf-token&quot;)[0].content
  # By default, angular sends &quot;application/json, text/plain, */*&quot; which rails
  # sees and focuses on the */* and sends html :-(
  $httpProvider.defaults.headers.common['Accept'] = &quot;application/json&quot;
]


# Here's our Post resource for interacting with the server
Blang.factory &quot;Post&quot;, ($resource) -&amp;gt; $resource &quot;/posts/:id&quot;, id: &quot;@id&quot;

# Post Controller
Blang.controller &quot;PostCtrl&quot;, ($scope, Post) -&amp;gt;
  # This is the post we use for the form
  $scope.post = new Post()

  # Posts for the list
  $scope.posts = Post.query()

  # Add a new post
  $scope.add = -&amp;gt;
    # add to the local array and also save to the server
    $scope.posts.push Post.save title: $scope.post.title, body: $scope.post.body
    # reset the post for the form
    $scope.post = new Post()

  # Delete a post
  $scope.delete = ($index) -&amp;gt;
    # Yay, UX!
    if confirm(&quot;Are you sure you want to delete this post?&quot;)
      # Remove from the server
      $scope.posts[$index].$delete()
      # Remove from the local array
      $scope.posts.splice($index, 1)
&lt;/pre&gt;

&lt;p&gt;All in all, it wasn’t much code, but it was very difficult to figure out what I was supposed to be doing. But that’s all part of learning a new framework. Here are a bunch of gotchas I ran into:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Providing the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;id: &quot;@id&quot;&lt;/code&gt; mapping in the resource url. Without this, it doesn’t automatically fill in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;:id&lt;/code&gt; with the model’s id.&lt;/li&gt;
  &lt;li&gt;I had to keep the local array of posts in sync with the server, pushing to it and splicing from it as I added and removed items.&lt;/li&gt;
  &lt;li&gt;Using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;$scope&lt;/code&gt; everywhere to expose methods in the view took me a bit to realize&lt;/li&gt;
  &lt;li&gt;I couldn’t delete a post by calling a method on the instance, because it wouldn’t remove it from the main collection&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;All in all, I found Angular to be pretty comprehensive when it came to the view binding and automatic dom reflection of underlying state. However I found its server synchronizing abilities to be lacking. Why is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;angular-resource.js&lt;/code&gt; a separate library anyways?&lt;/p&gt;

&lt;p&gt;I think it would be really interesting to use Angular.js as a declarative templating and view language, but then maybe drop to backbone for models and controllers. I could expose &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;collection.models&lt;/code&gt; to the scope, and it could watch that array. Then it should properly add and remove models from a collection.&lt;/p&gt;

&lt;p&gt;I’m really curious to hear how experienced users of Angular communicate with a server and keep their data in sync.&lt;/p&gt;

&lt;p&gt;If you’d like to mess around with the code, &lt;a href=&quot;http://github.com/ngauthier/angular-on-rails&quot;&gt;I put the application on GitHub&lt;/a&gt;.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Rails Controller Accessors</title>
    <link href="http://ngauthier.com/2013/04/rails-controller-accessors.html"/>
    <updated>2013-04-15T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2013/04/rails-controller-accessors</id>
    <content type="html">&lt;p&gt;Recently, I’ve been reading &lt;a href=&quot;http://www.amazon.com/gp/product/0321721330?ie=UTF8&amp;amp;camp=213733&amp;amp;creative=393185&amp;amp;creativeASIN=0321721330&amp;amp;linkCode=shr&amp;amp;tag=nickga-20&amp;amp;qid=1366040757&amp;amp;sr=8-1&quot;&gt;Practical Object-Oriented Design in Ruby&lt;/a&gt; by &lt;a href=&quot;http://sandimetz.com/&quot;&gt;Sandi Metz&lt;/a&gt; (I highly recommend it!) and it got me thinking more about OO design in Rails. I realized that one of the patterns I’ve been using synced really well with the messages in the book, and I wanted to share it.&lt;/p&gt;

&lt;h2 id=&quot;model-loading-filters&quot;&gt;Model Loading Filters&lt;/h2&gt;

&lt;p&gt;One of the most common Rails controller patterns is the before filter that fetches the record being accessed during member route actions. It looks like this:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
class PostController &amp;lt; Application Controller
  before_filter :find_post, only: [:show, :edit, :update, :destroy]

  # actions redacted

  private

  def find_post
    @post = Post.find params[:id]
  rescue ActiveRecord::RecordNotFound
    flash[:error] = &quot;No Such Post&quot;
    redirect_to posts_path
    return false
  end
end
&lt;/pre&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;lt;h1&amp;gt;&amp;lt;%= @post.title %&amp;gt;&amp;lt;/h1&amp;gt;
&lt;/pre&gt;

&lt;p&gt;This makes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@post&lt;/code&gt; available in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;show&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;edit&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;update&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;destroy&lt;/code&gt; actions, as well as making them available in the views.&lt;/p&gt;

&lt;p&gt;However, there are a few problems with this implementation:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;In views, you access the post as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@post&lt;/code&gt; whereas in a partial, you have to either depend on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@post&lt;/code&gt; being available, or you reference a local called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;post&lt;/code&gt;, which is inconsistent with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@post&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;The before filter has two responsibilities: finding the post and handling when there is no such post. Ideally this would be extracted into two methods each with one responsibility.&lt;/li&gt;
  &lt;li&gt;Instance variable copying is The Rails Way, but it’s very different from The Ruby Way and Object Oriented best practices. In short, the view depends on the internals of the controller.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;controller-accessors&quot;&gt;Controller Accessors&lt;/h2&gt;

&lt;p&gt;Recently, I’ve been using Controller Accessors as an alternative. Here’s what a Controller Accessor looks like:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
class PostController &amp;lt; Application Controller
  before_filter :ensure_post, only: [:show, :edit, :update, :destroy]

  # actions redacted

  private

  def post
    @post ||= Post.find_by_id params[:id]
  end
  helper_method :post

  def ensure_post
    redirect_to posts_path, alert: &quot;No Such Post&quot; unless post
  end
end
&lt;/pre&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;lt;h1&amp;gt;&amp;lt;%= post.title %&amp;gt;&amp;lt;/h1&amp;gt;
&lt;/pre&gt;

&lt;p&gt;Here we’ve extracting the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;post&lt;/code&gt; finding to a separate accessor method with memoization. We also expose this accessor as a helper method, which is a great way to allow the view to access a controller’s properties.&lt;/p&gt;

&lt;p&gt;Note that in the view we access &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;post&lt;/code&gt; and not &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@post&lt;/code&gt;. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@post&lt;/code&gt; &lt;em&gt;is&lt;/em&gt; still available, but accessing it via &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;post&lt;/code&gt; is the polite way to do it, and it much more resilient.&lt;/p&gt;

&lt;p&gt;We’ve also separated loading the post and ensuring that it is available by moving our filter to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ensure_post&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Lastly, I’ve opted to use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;find_by_id&lt;/code&gt; instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;find&lt;/code&gt; because &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;find_by_id&lt;/code&gt; returns nil instead of raising &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ActiveRecord::RecordNotFound&lt;/code&gt;, and a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nil&lt;/code&gt; is easier to test for. Also, it wouldn’t make sense for the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;post&lt;/code&gt; accessor to throw an exception (or to rescue it!) we’d rather have a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nil&lt;/code&gt; to express that there is no such post.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>WebSockets in Rails 4</title>
    <link href="http://ngauthier.com/2013/03/websockets-in-rails-4.html"/>
    <updated>2013-03-12T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2013/03/websockets-in-rails-4</id>
    <content type="html">&lt;p&gt;I’ve been using Rails 4 (beta) a lot recently. In a previous post we looked at how ActionController::Live can be used with Server-Sent Events, but the problem with that is that there’s no way for the client to communicate back to the web server. Enter: WebSockets.&lt;/p&gt;

&lt;p&gt;The main issue with implementing WebSockets is that they have to keep their connections open for a long period of time, and when you’re only running a small cluster of Rails servers, it eats up potential connections fast. That’s why I was excited to hear about two important developments: concurrency in Rails 4 and Rack Hijack.&lt;/p&gt;

&lt;h2 id=&quot;concurrency-in-rails-4&quot;&gt;Concurrency in Rails 4&lt;/h2&gt;

&lt;p&gt;Rails 4 is now full concurrent, which means that there is no full-stack lock on a request. That means that if you use a concurrent server like Puma you can handle many requests at a time with a single process.&lt;/p&gt;

&lt;p&gt;Even better, you can use ruby Threads inside your Rails app. That’s how ActionController::Live works (for streaming).&lt;/p&gt;

&lt;p&gt;What this means for us is that we can use Threads to hold websocket connections open without bogging down our server.&lt;/p&gt;

&lt;p&gt;Also, this means that our solution does not use Eventmachine, nor does it implement a reactor in any way. It’s concurrent.&lt;/p&gt;

&lt;h2 id=&quot;rack-hijack&quot;&gt;Rack Hijack&lt;/h2&gt;

&lt;p&gt;Rack Hijack came with Rack 1.5.0 which was released this past January. Rack hijack allows you to access the underlying socket of a Rack connection in order to bidirectionally communicate with the client. Since Rails is built on Rack we can grab a handle to the client socket &lt;em&gt;right from a Rails controller&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;tubesock&quot;&gt;Tubesock&lt;/h2&gt;

&lt;p&gt;Tubesock is the gem that I made to encapsulate this functionality. It’s very small and new and untested so caveat emptor and all that. At its core it provides a module for Rails controllers and a wrapper method to hijack the rack connection. Then it wraps the ruby gem &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;websocket&lt;/code&gt; to handle WebSocket handshakes and frames. Here’s an example of using it in a controller:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
class ChatController &amp;lt; ApplicationController
  include Tubesock::Hijack

  def chat
    hijack do |tubesock|
      tubesock.onopen do
        tubesock.send_data &quot;Hello, friend&quot;
      end

      tubesock.onmessage do |data|
        tubesock.send_data message: &quot;You said: #{data}&quot;
      end
    end
  end
end
&lt;/pre&gt;

&lt;p&gt;Right inside the controller action we can hijack the connection and then use some blocks to send information.&lt;/p&gt;

&lt;p&gt;You can check out &lt;a href=&quot;http://github.com/ngauthier/tubesock&quot;&gt;the Tubesock gem on Github&lt;/a&gt; for more information.&lt;/p&gt;

&lt;p&gt;Also, there is an &lt;a href=&quot;http://github.com/ngauthier/sock-chat&quot;&gt;example chat application&lt;/a&gt; you can run and play with.&lt;/p&gt;

&lt;p&gt;Happy hacking!&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Rails 4 Server Sent Events with ActionController::Live and PostgreSQL NOTIFY/LISTEN</title>
    <link href="http://ngauthier.com/2013/02/rails-4-sse-notify-listen.html"/>
    <updated>2013-02-19T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2013/02/rails-4-sse-notify-listen</id>
    <content type="html">&lt;p&gt;I had a simple problem: one user takes an action, and I want it to be reflected immediately on another user’s screen.&lt;/p&gt;

&lt;p&gt;There are lots of potential ways to solve this: polling, long polling, websockets, etc. However I had a specific goal in mind: &lt;strong&gt;use the stack I already had&lt;/strong&gt; and keep complexity to a minimum. I didn’t want to use websockets because of the extra setup on the server. Nginx just got a websockets proxy patch, but I don’t feel like compiling nginx from source on my deployment machines. I wanted something evented, but I didn’t want to add another back-end service like Redis.&lt;/p&gt;

&lt;p&gt;I decided to use Rails 4’s ActionController::Live, HTML5 Server Sent Events, and PostgreSQL’s NOTIFY/LISTEN system. The best part is that all I had to do to my stack was swap thin for puma.&lt;/p&gt;

&lt;p&gt;Huge thanks to Aaron Patterson for his post &lt;a href=&quot;http://tenderlovemaking.com/2012/07/30/is-it-live.html&quot;&gt;Is it Live?&lt;/a&gt;. Go read that now, because that’s how I implemented ActionController::Live, SSEs, and the Javascript.&lt;/p&gt;

&lt;p&gt;One thing I did do, though, was refactor (or unprefactor) his SSE implementation. Instead of a model I just added a controller method, so my controller action looks like:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
def index
  response.headers['Content-Type'] = 'text/event-stream'
  deck.on_slide_change do |slide|
    response.stream.write(sse({slide: slide}, {event: 'slide'}))
  end
rescue IOError
  # Client Disconnected
ensure
  response.stream.close
end

private
def sse(object, options = {})
  (options.map{|k,v| &quot;#{k}: #{v}&quot; } &amp;lt;&amp;lt; &quot;data: #{JSON.dump object}&quot;).join(&quot;\n&quot;) + &quot;\n\n&quot;
end
&lt;/pre&gt;

&lt;p&gt;This application is broadcasting a slide change on a deck, and every time a change occurs, it will write an SSE. My client consumes the feed just like Aaron’s, and then I also have a “broadcaster” that sends plain old ajax PUT requests to update the deck slide.&lt;/p&gt;

&lt;p&gt;Aaron used rb-fsevent which is an evented file system watching gem for OS X. In my case, I wanted my events to come from the database, so I used PostgreSQL’s NOTIFY/LISTEN. It’s really simple pub/sub that just takes a channel and a payload, and it all operates in shared memory. So it wouldn’t be great for a resilient queue, but it’s great for messaging.&lt;/p&gt;

&lt;p&gt;Here’s how I added that in my ActiveRecord model:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
after_save :notify_slide_change
def notify_slide_change
  if current_slide_changed?
    connection.execute &quot;NOTIFY #{channel}, #{connection.quote current_slide.to_s}&quot;
  end
end

def on_slide_change
  connection.execute &quot;LISTEN #{channel}&quot;
  loop do
    connection.raw_connection.wait_for_notify do |event, pid, slide|
      yield slide
    end
  end
ensure
  connection.execute &quot;UNLISTEN #{channel}&quot;
end

private
def channel
  &quot;decks_#{id}&quot;
end
&lt;/pre&gt;

&lt;p&gt;Whenever it’s saved and the slide has changed, I send a notify on the channel with the current slide as a string payload. The channel is simply the table name and id stuck together.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;on_slide_change&lt;/code&gt; is where it starts to get interesting. I listen on the channel (with an &lt;code&gt;ensure&lt;/code&gt; to stop listening). Then I have to get the &lt;code&gt;pg&lt;/code&gt; gem’s raw connection so I can call &lt;code&gt;wait_for_notify&lt;/code&gt;, which is a blocking LISTEN. It will give me an event, a pid, and my payload, which in my case is the slide. In true Ruby style, I yield the slide.&lt;/p&gt;

&lt;p&gt;All in all, it was pretty simple, but also pretty difficult to setup. One thing that is particularly tricky is that you have to cache classes in development mode in order to multithread Rails on Puma, which means you have to reboot your server on code changes. Also, I had to make sure my DB connection pool in &lt;code&gt;database.yml&lt;/code&gt; was as high as my Puma thread pool so everyone could have a DB connection.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Backbone Screencast 02 - Mixins</title>
    <link href="http://ngauthier.com/2013/02/backbone-screencast-2-mixins.html"/>
    <updated>2013-02-06T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2013/02/backbone-screencast-2-mixins</id>
    <content type="html">&lt;div&gt;&lt;iframe class=&quot;youtube&quot; src=&quot;http://www.youtube.com/embed/4c6fyj1p4jA&quot; frameborder=&quot;0&quot; allowfullscreen=&quot;&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;

&lt;p&gt;In this screencast I cover how to extract reusable pieces of code from a Backbone.js application using Mixins. The style is similar to Ruby on Rails’s Concerns in that it encapsulates both instance and class methods.&lt;/p&gt;

&lt;p&gt;If you like this screencast, consider buying &lt;a href=&quot;http://mobilebbbook.com&quot;&gt;Mobile Web Patterns with Backbone.js&lt;/a&gt;.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Backbone Screencast 01 - Booting your Application</title>
    <link href="http://ngauthier.com/2013/02/backbone-screencast-1.html"/>
    <updated>2013-02-06T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2013/02/backbone-screencast-1</id>
    <content type="html">&lt;div&gt;&lt;iframe class=&quot;youtube&quot; src=&quot;http://www.youtube.com/embed/4nlpDOIVhJw&quot; frameborder=&quot;0&quot; allowfullscreen=&quot;&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;

&lt;p&gt;In this screencast we go over three different ways of booting your application:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;jQuery onReady in the JavaScript file&lt;/li&gt;
  &lt;li&gt;Application.boot method called from html&lt;/li&gt;
  &lt;li&gt;Unobtrusive boot based on a data attribute&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you like this screencast, consider buying &lt;a href=&quot;http://mobilebbbook.com&quot;&gt;Mobile Web Patterns with Backbone.js&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;All the code is in CoffeeScript, for more information, check out &lt;a href=&quot;http://coffeescript.org&quot;&gt;CoffeeScript’s web site&lt;/a&gt;.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Unsubscribe Links in Rails with ActiveSupport::MessageVerifier</title>
    <link href="http://ngauthier.com/2013/01/rails-unsubscribe-with-active-support-message-verifier.html"/>
    <updated>2013-01-08T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2013/01/rails-unsubscribe-with-active-support-message-verifier</id>
    <content type="html">&lt;p&gt;If you’re setting up an unsubscribe link for your emails in a Rails application, it’s important to make it secure and seamless. We want to have it function properly if the user is not logged in without having them log in first. We also want to make sure it’s not easy to forge. The url should be something like this:&lt;/p&gt;

&lt;p&gt;http://example.com/unsubscribe/0938745209387452093478530938742509384752&lt;/p&gt;

&lt;p&gt;So, we need some way to encode a user’s information securely and create a url, then we also need to decode it. Enter &lt;strong&gt;ActiveSupport::MessageVerifier&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;MessageVerifier is initialized with a secret, and can then encode and decode messages, like this:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
# make a verifier
verifier = ActiveSupport::MessageVerifier.new('secret')

# encode some data
token = verifier.generate('data')
# =&amp;gt; &quot;BAhJIglkYXRhBjoGRVQ=--7d0d0ec0f5572ac668afeabea7829064cc78223b&quot;

# note: it's not encrypted!
Base64.decode64(token.split(&quot;--&quot;)[0])
# =&amp;gt; &quot;\x04\bI\&quot;\tdata\x06:\x06ET&quot;

# Get the data back out
verifier.verify(token)
# =&amp;gt; &quot;data&quot;
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;NOTE&lt;/strong&gt;: the data is not encrypted, just verified with a digest using a secret. The original data is present in the token, so don’t put anything secret in there.&lt;/p&gt;

&lt;p&gt;Now, we can integrate this into our &lt;code&gt;User&lt;/code&gt; model pretty easily. We’ll make class methods for encoding and decoding, then an instance method to make it easier to use:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
class User &amp;lt; ActiveRecord::Base
  # Access token for a user
  def access_token
    User.create_access_token(self)
  end

  # Verifier based on our application secret
  def self.verifier
    ActiveSupport::MessageVerifier.new(MyRailsApp::Application.config.secret_token)
  end

  # Get a user from a token
  def self.read_access_token(signature)
    id = verifier.verify(signature)
    User.find_by_id id
  rescue ActiveSupport::MessageVerifier::InvalidSignature
    nil
  end

  # Class method for token generation
  def self.create_access_token(user)
    verifier.generate(user.id)
  end
end
&lt;/pre&gt;

&lt;p&gt;Now all we have to do is add a route:&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
match '/users/unsubscribe/:signature' =&amp;gt; 'users#unsubscribe', as: 'unsubscribe'
&lt;/pre&gt;

&lt;p&gt;Include the link in our email layout:&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;lt;%= link_to &quot;Unsubscribe&quot;, unsubscribe_url(@user.access_token) %&amp;gt;
&lt;/pre&gt;

&lt;p&gt;And setup a controller action:&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
class UsersController &amp;lt; ApplicationController
  def unsubscribe
    if user = User.read_access_token(params[:signature])
      user.update_attribute :email_opt_in, false
      render text: &quot;You have been unsubscribed&quot;
    else
      render text: &quot;Invalid Link&quot;
    end
  end
end
&lt;/pre&gt;

&lt;p&gt;This can be expanded to be used in any scenario where you need an authentication token, for example all email links could contain a token in the param, which is removed in an application-wide &lt;code&gt;before_filter&lt;/code&gt;. That way, a user never has to log in if they’re coming from an email you sent them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Warning&lt;/strong&gt;: The data is encoded but since it is not (entirely) hashed it will grow in length. Be careful using variable-length or user-generated data, as you could go beyond the 2048 character limit of urls. Much like delayed jobs and cookies, it’s a good idea to store only an identifier in the token, and then look up the associated data in your database. If you really need encryption, check out ActiveSupport::MessageEncryptor.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Ruby on Rails on the Nexus 7</title>
    <link href="http://ngauthier.com/2012/11/ruby-on-rails-on-nexus.html"/>
    <updated>2012-11-28T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/11/ruby-on-rails-on-nexus</id>
    <content type="html">&lt;p&gt;This evening I decided to put Ubuntu on my Nexus 7 to see how it performs and what packages are available on ARM. I’m happy to report that Ruby 1.9.3 (p194) and Rails 3.2.9 work perfectly (albeit slowly :-D).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/nexus-7-rails.jpg&quot; alt=&quot;Nexus 7 Running Rails&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;step-1-ubuntu&quot;&gt;Step 1: Ubuntu&lt;/h2&gt;

&lt;p&gt;I followed &lt;a href=&quot;https://wiki.ubuntu.com/Nexus7/Installation&quot;&gt;Ubuntu’s steps for installation&lt;/a&gt; and it worked fine. There was an odd issue connecting via ssh, but I think it was my router. I had to ssh out of the tablet to my desktop before the desktop could ssh to the tablet. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;iptables&lt;/code&gt; was empty on both. Dunno what was up.&lt;/p&gt;

&lt;h2 id=&quot;step-2-ruby&quot;&gt;Step 2: Ruby&lt;/h2&gt;

&lt;p&gt;I followed &lt;a href=&quot;/2012/01/simple-ruby-on-ubuntu.html&quot;&gt;my own ubuntu setup instructions&lt;/a&gt;, except I substituted &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;libsqlite3-dev&lt;/code&gt; for the postgresql packages.&lt;/p&gt;

&lt;h2 id=&quot;step-3-rails&quot;&gt;Step 3: Rails&lt;/h2&gt;

&lt;p&gt;I ran &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gem install bundler&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gem install rails&lt;/code&gt;, took a minute or two, but it worked.&lt;/p&gt;

&lt;h2 id=&quot;step-4-a-blog&quot;&gt;Step 4: A Blog!&lt;/h2&gt;

&lt;p&gt;Of course I had to make a blog, that’s the Hello World of Rails! I simply used &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rails g scaffold Post title:string body:text&lt;/code&gt; then &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rake db:migrate&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rails server&lt;/code&gt;, then wrote my post.&lt;/p&gt;

&lt;p&gt;Honestly I was very disappointed at how easy it all was. I was looking for a challenge :-D&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://twitter.com/ngauthier&quot;&gt;@ngauthier&lt;/a&gt;&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Intro to Backbone.js</title>
    <link href="http://ngauthier.com/2012/09/intro-to-backbone-js.html"/>
    <updated>2012-09-27T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/09/intro-to-backbone-js</id>
    <content type="html">&lt;p&gt;Here is a talk I gave at the Baltimore Javascript users group. It is an introduction to backbone.js, featuring about 25 minutes of slides and an hour of live coding an example application.&lt;/p&gt;

&lt;div&gt;&lt;iframe class=&quot;youtube&quot; src=&quot;http://www.youtube.com/embed/PqtYcHyyWJA?rel=0&quot; frameborder=&quot;0&quot; allowfullscreen=&quot;&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;

&lt;p&gt;Live coding starts at 27:47&lt;/p&gt;

&lt;p&gt;Check out my ebook, &lt;a href=&quot;http://recipeswithbackbone.com/&quot;&gt;Recipes with Backbone&lt;/a&gt;!&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>One Click Development</title>
    <link href="http://ngauthier.com/2012/08/one-click-development.html"/>
    <updated>2012-08-15T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/08/one-click-development</id>
    <content type="html">&lt;h2 id=&quot;the-problem&quot;&gt;The Problem&lt;/h2&gt;

&lt;p&gt;Non-technical teammates can’t run the app. You’ve got designers, project managers, qa, and more. Whenever developers add a dependency to the project, a lot of hand-holding needs to occur to get everyone setup.&lt;/p&gt;

&lt;p&gt;Not everyone is comfortable on the terminal, nor should they be.&lt;/p&gt;

&lt;h2 id=&quot;gosh&quot;&gt;go.sh&lt;/h2&gt;

&lt;p&gt;My first solution to this problem was to place &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;go.sh&lt;/code&gt; in the root of the project. This command installed bundler, bundled the project, and ran the server. This worked fine, until the first dependency shift: switching from sinatra to rails with postgresql.&lt;/p&gt;

&lt;p&gt;I’ve been doing rails for about five years now, and I got a mac a few months ago. I’m embarassed and frustrated at how long it took me to figure out xcode’s command line tools, homebrew, rbenv on OS X, starting and stopping processes, database permissions, etc. How can I ask that of someone who does not have a terminal on their dock?&lt;/p&gt;

&lt;p&gt;Many great minds are working on making Rails setup on OS X better, and that’s great. But it’s not enough. Developers will always be one step ahead, using the latest and greatest tools, and we don’t want to wait for others to setup one-click installs for the stack we want.&lt;/p&gt;

&lt;h2 id=&quot;vagrant&quot;&gt;Vagrant&lt;/h2&gt;

&lt;p&gt;So now, I turn to &lt;a href=&quot;http://vagrantup.com&quot;&gt;Vagrant&lt;/a&gt;. I’ve wanted to try it out, but I’ve had no real excuse, until now. So here’s my goal:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;go.sh should download, boot, provision, and run the rails app with minimal requirements&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;pre-requisites&quot;&gt;Pre-requisites&lt;/h2&gt;

&lt;p&gt;Thanks to those working on making OS X setup easier, the OS X specific pre-requisites are:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Download and install &lt;a href=&quot;http://railsinstaller.org/&quot;&gt;RailsInstaller&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Download and install &lt;a href=&quot;https://www.virtualbox.org/&quot;&gt;VirtualBox&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;On linux, it’s:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;apt-get install ruby virtualbox&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We need VirtualBox for vagrant, and we need railsinstaller to get ruby 1.9 for vagrant.&lt;/p&gt;

&lt;h2 id=&quot;running-the-project&quot;&gt;Running the project&lt;/h2&gt;

&lt;p&gt;Create a symlink to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;go.sh&lt;/code&gt; called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;go.command&lt;/code&gt; for mac, so those users can simply double click.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Double click go&lt;/strong&gt; is now the way to run the system. Then the user browses to localhost:5000&lt;/p&gt;

&lt;h2 id=&quot;ok-so-how&quot;&gt;OK, so, HOW???&lt;/h2&gt;

&lt;h3 id=&quot;gosh-1&quot;&gt;go.sh&lt;/h3&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/bin/sh

# Ensure we're in the project directory
cd `dirname $0`

# Setup gems to install to userspace
export GEM_HOME=$HOME/.gems
export PATH=$GEM_HOME/bin:$PATH

# Output debug info in case a developer needs to lend a hand
echo &quot;Working in `pwd`&quot;
echo &quot;Ruby `ruby -v`&quot;
echo &quot;Rubygems `gem -v`&quot;

# Install vagrant if it's not installed
vagrant -v 2&amp;gt;/dev/null || gem install vagrant --no-ri --no-rdoc

# Create, boot, provision vm (more later)
vagrant up

# On the vagrant box, run our custom server script
vagrant ssh -c &quot;cd /vagrant &amp;amp;&amp;amp; ./script/server&quot;
&lt;/pre&gt;

&lt;h3 id=&quot;scriptserver&quot;&gt;script/server&lt;/h3&gt;

&lt;p&gt;Hey, remember this from rails 2? I wrote a custom script/server that does all the things that &lt;em&gt;really&lt;/em&gt; need to be done to run a rails server:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/bin/sh

# Setup local paths
export GEM_HOME=$HOME/.gems
export PATH=$GEM_HOME/bin:$PATH

# Install bundler if not available
bundle -v 2&amp;gt;/dev/null || gem install bundler --no-rdoc --no-ri

# Install all gems (or update, after pulling new code)
bundle install

# Create db if it doesn't exist, migrate if we need to
bundle exec rake db:create db:migrate

# Start services
bundle exec foreman start
&lt;/pre&gt;

&lt;p&gt;Also, savvy devs would be expected to provision their own system, then run script/server locally (not in a vm) for extra performance. Or, for better consistency, they could run vagrant too.&lt;/p&gt;

&lt;h3 id=&quot;stopsh&quot;&gt;stop.sh&lt;/h3&gt;

&lt;p&gt;Lastly, there is a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stop.sh&lt;/code&gt;. You can ctrl+c and/or close the terminal created by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;go.sh&lt;/code&gt; but that won’t halt the vm.&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/bin/sh
cd `dirname $0`
export GEM_HOME=$HOME/.gems
export PATH=$GEM_HOME/bin:$PATH

vagrant halt
&lt;/pre&gt;

&lt;h2 id=&quot;provisioning&quot;&gt;Provisioning&lt;/h2&gt;

&lt;p&gt;Now the only remaining question is how to setup vagrant for a nice rails environment. Here is my &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Vagrantfile&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
Vagrant::Config.run do |config|
  # Use ubuntu 12.04 32 bit
  config.vm.box = &quot;precise32&quot;
  config.vm.box_url = &quot;http://files.vagrantup.com/precise32.box&quot;

  # Forward port 5000 to localhost:5000
  config.vm.forward_port 5000, 5000

  # Use chef-solo to provision
  config.vm.provision :chef_solo do |chef|
    # Use our custom recipe
    chef.cookbooks_path = &quot;cookbooks&quot;
    chef.add_recipe &quot;my_application&quot;
  end
end
&lt;/pre&gt;

&lt;p&gt;Vagrant and Chef are entirely new to me (as of yesterday), so this is the area &lt;strong&gt;I’m not sure on&lt;/strong&gt;. I used &lt;a href=&quot;https://github.com/applicationsonline/librarian&quot;&gt;librarian&lt;/a&gt; initially, but found that I needed more control over the recipes and box setup, and that I could use a much simpler recipe and only target ubuntu. &lt;a href=&quot;http://smartic.us/&quot;&gt;Bryan Liles&lt;/a&gt; pointed me at chef’s &lt;a href=&quot;http://wiki.opscode.com/display/chef/Resources#Resources-Package&quot;&gt;packages&lt;/a&gt; and &lt;a href=&quot;http://wiki.opscode.com/display/chef/Resources#Resources-Script&quot;&gt;scripts&lt;/a&gt;, and so I wrote my own simple cookbook called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;my_application&lt;/code&gt; (I actually named it the same as the Rails app).&lt;/p&gt;

&lt;p&gt;Now, vagrant just grabs an ubuntu 12.04 base image, forwards port 5000, and runs my cookbook. The cookbook only needed two files, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cookbooks/my_application/metadata.rb&lt;/code&gt; which was just my name and info, and then &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cookbooks/my_application/default.rb&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
# Update repository and install any upgrades
execute &quot;update apt&quot; do
  command &quot;apt-get update &amp;amp;&amp;amp; apt-get upgrade -y&quot;
end

# Install ruby and postgresql and dependencies for gems and rails
package 'libxslt1-dev'
package 'libxml2-dev'
package 'build-essential'
package 'g++'
package 'ruby1.9.1-dev'
package 'postgresql'
package 'libpq-dev'
package 'git'
package 'nodejs'

# Create a directory for us to put some lock files in so scripts run once
execute &quot;application directory&quot; do
  command &quot;mkdir /var/my_application&quot;
  creates &quot;/var/my_application&quot;
end

# Setup vagrant as a psql user
execute &quot;vagrant psql role&quot; do
  command %{sudo -u postgres createuser -s vagrant         &amp;amp;&amp;amp; \
            sudo -u postgres createdb   -O vagrant vagrant &amp;amp;&amp;amp; \
            touch /var/my_application/psql-vagrant.done}
  creates        &quot;/var/my_application/psql-vagrant.done&quot;
end
&lt;/pre&gt;

&lt;p&gt;I’m used to a pretty minimal ubuntu setup like this. Much faster and easier than using rvm or rbenv. System ruby is 1.9.3p194 on ubuntu 12.04, which is rvm’s default ruby 1.9 as well. And you don’t have to compile it!&lt;/p&gt;

&lt;h2 id=&quot;team-workflow&quot;&gt;Team workflow&lt;/h2&gt;

&lt;p&gt;So now, non-technical team members have a running app on their system. Developers can add dependencies to the cookbook, and when a non-technical team member syncs their code (with Github’s apps, right?) they can just click &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;go&lt;/code&gt; and vagrant will update the box based on the new provisions, and the server script will update the system’s gems and database. Sweet!&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>RSpec with Domino</title>
    <link href="http://ngauthier.com/2012/05/rspec-with-domino.html"/>
    <updated>2012-05-08T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/05/rspec-with-domino</id>
    <content type="html">&lt;p&gt;Using &lt;a href=&quot;http://rubydoc.info/gems/domino/frames&quot;&gt;Domino&lt;/a&gt; with &lt;a href=&quot;http://rubydoc.info/gems/rspec/frames&quot;&gt;RSpec&lt;/a&gt; is awesome. I’ll let the code speak for itself.&lt;/p&gt;

&lt;p&gt;We have an html page:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Domino Rspec&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Domino Rspec&amp;lt;/h1&amp;gt;
    &amp;lt;ul&amp;gt;
      &amp;lt;li&amp;gt;&amp;lt;span class='name'&amp;gt;John Doe&amp;lt;/span&amp;gt; Age &amp;lt;span class='age'&amp;gt;47&amp;lt;/span&amp;gt;&amp;lt;/li&amp;gt;
      &amp;lt;li&amp;gt;&amp;lt;span class='name'&amp;gt;Jane Doe&amp;lt;/span&amp;gt; Age &amp;lt;span class='age'&amp;gt;37&amp;lt;/span&amp;gt;&amp;lt;/li&amp;gt;
      &amp;lt;li&amp;gt;&amp;lt;span class='name'&amp;gt;Jim Doe&amp;lt;/span&amp;gt; Age &amp;lt;span class='age'&amp;gt;27&amp;lt;/span&amp;gt;&amp;lt;/li&amp;gt;
    &amp;lt;/ul&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;

&lt;p&gt;And here is an rspec request spec to test the data:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
describe :index_without_domino, :type =&amp;gt; :request do
  before do
    visit '/'
  end

  it 'should have three people' do
    page.all('ul li').count.should == 3
  end

  context 'John Doe' do
    subject do
      page.all('ul li').find do |node|
        node.find('.name').text == 'John Doe'
      end
    end

    it 'should have an age of 47' do
      subject.find('.age').text.should == '47'
    end
  end
end
&lt;/pre&gt;

&lt;p&gt;CSS selectors are brittle here, and it’s not very rubyish. It’s full of html! First, we’ll make a domino:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
module Dom
  class Person &amp;lt; Domino
    selector 'ul li'
    attribute :name
    attribute :age
  end
end
&lt;/pre&gt;

&lt;p&gt;And then update our test:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
describe :index, :type =&amp;gt; :request do
  before do
    visit '/'
  end

  it 'should have three people' do
    Dom::Person.count.should == 3
  end

  context 'John Doe' do
    subject { Dom::Person.find_by_name 'John Doe' }
    its(:age) { should == '47' }
  end
end
&lt;/pre&gt;

&lt;p&gt;Because dominos are enumerable ruby objects, we can count them easily. There’s also handy attribute finders and accessors. So, a domino can be an rspec subject. Much better!&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://github.com/ngauthier/domino_rspec&quot;&gt;Full project source code&lt;/a&gt;&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>var self = lame</title>
    <link href="http://ngauthier.com/2012/04/var-self-equals-lame.html"/>
    <updated>2012-04-11T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/04/var-self-equals-lame</id>
    <content type="html">&lt;script src=&quot;/javascripts/underscore-min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;var-self--this&quot;&gt;var self = this&lt;/h2&gt;

&lt;p&gt;I see this in a lot of javascript code. The first thing it makes me think of is &lt;a href=&quot;http://avdi.org&quot;&gt;Avdi Grimm&lt;/a&gt;’s excellent talk &lt;a href=&quot;http://avdi.org/talks/confident-code-railsconf-2011/&quot;&gt;Confident Code&lt;/a&gt;. I think that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var self = this&lt;/code&gt; is an example of “timid code” in javascript. Avdi explains how timid code suffers from a “Lack of certainty” and it “lives in fear … constantly second-guessing itself … [and] imposes cognitive load on the reader”. I highly recommend you read the slides or &lt;a href=&quot;http://www.confreaks.com/videos/614-cascadiaruby2011-confident-code&quot;&gt;watch the video&lt;/a&gt; even if you don’t code ruby.&lt;/p&gt;

&lt;h2 id=&quot;why&quot;&gt;Why?&lt;/h2&gt;

&lt;p&gt;Here’s why &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var self = this&lt;/code&gt; is helpful: callback scope. Consider this code from &lt;a href=&quot;http://www.javascriptkata.com/2007/05/14/how-to-use-the-self-with-object-oriented-javascript-and-closures/&quot;&gt;a JavascriptKata post&lt;/a&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
// Create a cat
function Cat() {
    this.theCatName = &quot;Mistigri&quot;;
}
 
// The cat will meow later
Cat.prototype.meowLater = function() {
    // I create the variable self that refers to the this (the current object)
    var self = this;
 
    // I create a timeout that calls the self.meow function within an anonymous function
    /*** NOTE : You don’t always have to create an anonymous function it’s just that in
        this case, it is required ***/
    window.setTimeout(
        function() {
            self.meow();
        }
        , 1000);
}
// The cat meows
Cat.prototype.meow = function() {
    // I can use the this expression!!!
    alert(this.theCatName + &quot; : meow!&quot;);
}
 
// I crate an object and call the meowLater() function
var theCat = new Cat();
theCat.meowLater();
&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;#meowlater&quot;&gt;Click here to run&lt;/a&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
// Create a cat
function Cat() {
    this.theCatName = &quot;Mistigri&quot;;
}&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;// The cat will meow later
Cat.prototype.meowLater = function() {
    // I create the variable self that refers to the this (the current object)
    var self = this;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// I create a timeout that calls the self.meow function within an anonymous function
/*** NOTE : You don’t always have to create an anonymous function it’s just that in
    this case, it is required ***/
window.setTimeout(
    function() {
        self.meow();
    }
    , 1000); } // The cat meows Cat.prototype.meow = function() {
// I can use the this expression!!!
alert(this.theCatName + &quot; : meow!&quot;); } $('a[href=&quot;#meowlater&quot;]').click(function() {   var cat = new Cat();   cat.meowLater(); }); &amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;fix-1-using-settimeouts-argument-passing&quot;&gt;Fix #1: Using setTimeout’s argument passing&lt;/h2&gt;

&lt;p&gt;The first way we can fix this use of timid scope passing is to use setTimeout’s ability to pass arguments:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
function ApplyCat() {
  this.name = &quot;Garbanzo&quot;
}

ApplyCat.prototype.meowLater = function() {
  window.setTimeout(
    function(cat) {
      cat.meow()
    }, 1000, this
  )
}

ApplyCat.prototype.meow = function() {
  alert(this.name + &quot; : meow!&quot;)
}
&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;#meowlatertimeout&quot;&gt;Click here to run&lt;/a&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
function TimeoutCat() {
  this.name = &quot;Garbanzo&quot;
}&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;TimeoutCat.prototype.meowLater = function() {
  window.setTimeout(
    function(cat) {
      cat.meow()
    }, 1000, this
  )
}&lt;/p&gt;

&lt;p&gt;TimeoutCat.prototype.meow = function() {
  alert(this.name + “ : meow!”)
}&lt;/p&gt;

&lt;p&gt;$(‘a[href=”#meowlatertimeout”]’).click(function() {
  var cat = new TimeoutCat()
  cat.meowLater()
})
&amp;lt;/script&amp;gt;&lt;/p&gt;

&lt;p&gt;I’m passing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this&lt;/code&gt; in as an argument for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;setTimeout&lt;/code&gt; to pass to the callback function, so that I have a reference to the cat.&lt;/p&gt;

&lt;p&gt;So, this is better because instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var self = this&lt;/code&gt; I’m passing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this&lt;/code&gt; in as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cat&lt;/code&gt;. This is equivalent to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var self = this&lt;/code&gt; as far as scoping is concerned, and doesn’t buy us too much. But, one thing it does to is that it’s more explicit about &lt;em&gt;why&lt;/em&gt; the scope is being passed, and &lt;em&gt;what&lt;/em&gt; the scope is. But there’s a better way.&lt;/p&gt;

&lt;h2 id=&quot;fix-2-use-underscorejs&quot;&gt;Fix #2: Use underscore.js&lt;/h2&gt;

&lt;p&gt;Why are we reinventing the wheel here? We’ve been binding scope since the dawn of time (or at least, the dawn of javascript). Why should we all repeat the same patterns over and over when smarter people have done it for us?&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
function BindCat() {
  this.name = &quot;Alfonso&quot;
}

BindCat.prototype.meowLater = function() {
  window.setTimeout(_.bind(this.meow, this), 1000)
}

BindCat.prototype.meow = function() {
  alert(this.name + &quot; : meow!&quot;)
}
&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;#meowlaterbind&quot;&gt;Click here to run&lt;/a&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
function BindCat() {
  this.name = &quot;Alfonso&quot;
}&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;BindCat.prototype.meowLater = function() {
  window.setTimeout(_.bind(this.meow, this), 1000)
}&lt;/p&gt;

&lt;p&gt;BindCat.prototype.meow = function() {
  alert(this.name + “ : meow!”)
}&lt;/p&gt;

&lt;p&gt;$(‘a[href=”#meowlaterbind”]’).click(function() {
  var cat = new BindCat()
  cat.meowLater()
})
&amp;lt;/script&amp;gt;&lt;/p&gt;

&lt;p&gt;This is the best solution. For four reasons:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;First&lt;/strong&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;_.bind(this.meow, this)&lt;/code&gt; very clearly states that the objective of this code is to bind the scope of the function to the current object. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var self = this&lt;/code&gt; says “I need to use this later” and then later on when you see &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self&lt;/code&gt; you remember that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self&lt;/code&gt; is a scope shortcut to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this&lt;/code&gt;. It’s a minor cognitive load, but it’s not worth dismissing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Second&lt;/strong&gt;, you’re leaning on a well tested library like underscore to not mess things up. Whenever you can use someone else’s shared library to do something, do it. Odds are they’re covering edge cases you’re not. For example, underscore’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bind&lt;/code&gt; will use ECMAScript 5’s native &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bind&lt;/code&gt; if it’s available. By the way, underscore has a ton of other awesome methods you should be using.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Third&lt;/strong&gt;, it’s a one-liner. It’s so succinct that I can put it right into the timeout call and it fits easily. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var self = this&lt;/code&gt; is one extra line, plus the inline function definition causes three extra lines. Less is more.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Fourth&lt;/strong&gt;, when you remove this line, it doesn’t leave any other dangling lines of code. I’ve seen plenty of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var self = this&lt;/code&gt; followed by a bunch of code that &lt;strong&gt;doesn’t have any callbacks in it&lt;/strong&gt;. There was no reason to declare &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self&lt;/code&gt;, yet it’s used in place of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this&lt;/code&gt; &lt;strong&gt;out of fear&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;alternate-use-of-underscore&quot;&gt;Alternate Use of underscore&lt;/h2&gt;

&lt;p&gt;Another way you can use underscore for function binding is with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;_.bindAll&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
function BindAllCat() {
  _.bindAll(this);
  this.name = &quot;Fred&quot;
}

BindAllCat.prototype.meowLater = function() {
  window.setTimeout(this.meow, 1000)
}

BindAllCat.prototype.meow = function() {
  alert(this.name + &quot; : meow!&quot;)
}
&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;#meowlaterbindall&quot;&gt;Click here to run&lt;/a&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
function BindAllCat() {
  _.bindAll(this);
  this.name = &quot;Fred&quot;
}&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;BindAllCat.prototype.meowLater = function() {
  window.setTimeout(this.meow, 1000)
}&lt;/p&gt;

&lt;p&gt;BindAllCat.prototype.meow = function() {
  alert(this.name + “ : meow!”)
}&lt;/p&gt;

&lt;p&gt;$(‘a[href=”#meowlaterbindall”]’).click(function() {
  var cat = new BindAllCat()
  cat.meowLater()
})
&amp;lt;/script&amp;gt;&lt;/p&gt;

&lt;p&gt;In the constructor, we use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;_.bindAll&lt;/code&gt;, which will bind every instance method to the instance. So no matter how you call the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;meow&lt;/code&gt; function, it will be bound to the cat. Now feel free to call your instance methods everywhere, and they will be scoped to the object, just like a real OO language.&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Please stop coding out of fear. Maybe you want to keep using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self&lt;/code&gt; anyways because you think it reads better, but at least understand that there are many ways to accomplish proper scoping in javascript, and consider all of them when you run into these kinds of issues.&lt;/p&gt;

&lt;p&gt;xoxo &lt;a href=&quot;http://twitter.com/ngauthier&quot;&gt;@ngauthier&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;pre-emptive-comment-responses&quot;&gt;Pre-emptive comment responses&lt;/h2&gt;

&lt;h3 id=&quot;its-less-efficient&quot;&gt;It’s less efficient&lt;/h3&gt;

&lt;p&gt;You’re right. And C is even faster. You know what’s the least efficient? Poorly readable and unmaintainable code.&lt;/p&gt;

&lt;h3 id=&quot;i-dont-have-underscore-and-i-dont-want-to-add-more-dependencies&quot;&gt;I don’t have underscore, and I don’t want to add more dependencies&lt;/h3&gt;

&lt;p&gt;It’s 4kb. Suck it up. That’s &amp;lt; 1ms on broadband. The collection extensions will change the way you enumerate, and underscore alone is worth it so you can write:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
var maxPrice = _(widgets).chain().map(function(widget) {
  return widget.price()
}).reduce(function(max, price) {
  return !max || price &amp;gt; max ? price : max
}).value();
&lt;/pre&gt;

&lt;p&gt;mmmm. map/reduce.&lt;/p&gt;

&lt;p&gt;Also, every collection method automatically takes a context as an optional final parameter. So you can do:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
_(this.widgets).each(function(widget) {
  this.enable(widget);
}, this)
&lt;/pre&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this&lt;/code&gt; on the first two lines refers to the same object, because &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this&lt;/code&gt; is passed to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;each&lt;/code&gt; as the final parameter. IMO, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jQuery.on&lt;/code&gt; should replace the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;data&lt;/code&gt; parameter with a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;context&lt;/code&gt; parameter. It would encourage more OO-style event coding. Backbone automatically binds all view event callbacks to the view, which is awesome.&lt;/p&gt;

&lt;h2 id=&quot;solicitation-for-comments&quot;&gt;Solicitation for comments&lt;/h2&gt;

&lt;p&gt;The main reason I wrote this post is that a number of smart programmers I respect disagree with me. I would love to have a &lt;strong&gt;constructive&lt;/strong&gt; and &lt;strong&gt;positive&lt;/strong&gt; discussion on this topic. I never remove comments, so you can still hate on me, but everyone will know how lame you are on the internet.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Deploy Ruby as a Gem</title>
    <link href="http://ngauthier.com/2012/04/deploy-ruby-as-a-gem.html"/>
    <updated>2012-04-09T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/04/deploy-ruby-as-a-gem</id>
    <content type="html">&lt;h2 id=&quot;background&quot;&gt;Background&lt;/h2&gt;

&lt;p&gt;I was looking at &lt;a href=&quot;https://github.com/mislav/git-deploy&quot;&gt;git-deploy&lt;/a&gt; and it looks really awesome. But it got me thinking: We have tools like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bundler&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rack&lt;/code&gt; that can handle gem versioning and dependencies, and creating clean interfaces for web applications. Why can’t we use those tools for deploying our own code?&lt;/p&gt;

&lt;p&gt;I think ruby gems are a great way of packaging code up, and that any code you write should become a gem if it needs to be re-used. Gems are pretty easy to write, and they automatically help you package and version your code.&lt;/p&gt;

&lt;p&gt;I also think we should be doing more version-based deploys of code. Even if it’s just a git tag. But it’s better if it’s actually an application version.&lt;/p&gt;

&lt;p&gt;So, I stumbled across &lt;a href=&quot;http://florianhanke.com/blog/2011/02/02/running-sinatra-inside-a-gem.html&quot;&gt;Running Sinatra inside a Ruby Gem&lt;/a&gt; by Florian Hanke, and I really liked it, but I wanted to take it one step further: deploying.&lt;/p&gt;

&lt;h2 id=&quot;application-setup&quot;&gt;Application Setup&lt;/h2&gt;

&lt;p&gt;The first thing we have to do is setup our application:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
bundle gem awesome_site
&lt;/pre&gt;

&lt;p&gt;That will make a gem scaffold inside the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;awesome_site&lt;/code&gt; folder for a gem called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AwesomeSite&lt;/code&gt;. Next, in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;awesome_site.gemspec&lt;/code&gt; add:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
gem.add_dependency 'sinatra', '1.3.2'
&lt;/pre&gt;

&lt;p&gt;Also, update the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gem.description&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gem.summary&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Next, we’re going to add a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config.ru&lt;/code&gt;, which will help us test our application in development:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
require 'rubygems'
require 'bundler'
Bundler.setup
require 'awesome_site'
run AwesomeSite::App
&lt;/pre&gt;

&lt;p&gt;So, we need to setup &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AwesomeSite::App&lt;/code&gt; as a rack app. Edit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lib/awesome_site.rb&lt;/code&gt; to autoload &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;App&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
module AwesomeSite
  autoload :App, 'awesome_site/app'
end
&lt;/pre&gt;

&lt;p&gt;Then put this in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lib/awesome_site/app.rb&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
require 'sinatra'
module AwesomeSite
  class App &amp;lt; Sinatra::Base
    get '/' do
      'hello world!'
    end
  end
end
&lt;/pre&gt;

&lt;p&gt;Note that I used &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autoload&lt;/code&gt; instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;require&lt;/code&gt; for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;App&lt;/code&gt; and I also didn’t &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;require&lt;/code&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Sinatra&lt;/code&gt; until the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app.rb&lt;/code&gt; file. This means that loading my gem will be fast, and that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sinatra&lt;/code&gt; won’t have its code loaded and run until the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;App&lt;/code&gt; is needed. This will keep boot times down (like when unit testing code that doesn’t need &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;App&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Now, you should be able to run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rackup&lt;/code&gt; and visit the app!&lt;/p&gt;

&lt;p&gt;The last thing we need to do is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rake install&lt;/code&gt; to build and install the gem on our local system.&lt;/p&gt;

&lt;h2 id=&quot;server-setup&quot;&gt;Server Setup&lt;/h2&gt;

&lt;p&gt;OK, so now that we have our great app as a gem (thanks Florian!) it’s time to setup the server. Make a new directory (to simulate the server’s application folder) outside of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;awesome_site&lt;/code&gt; folder. I just called mine &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;server&lt;/code&gt;. In this folder, make a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Gemfile&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
source :rubygems
source 'http://0.0.0.0:8808'
gem 'awesome_site'
&lt;/pre&gt;

&lt;p&gt;This &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Gemfile&lt;/code&gt; shows how I would install &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;awesome_site&lt;/code&gt; from a local gem server (by running &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gem server&lt;/code&gt;) and pull dependencies from rubygems.org. An alternative would be:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
source :rubygems
gem 'awesome_site', :git =&amp;gt; 'git://github.com/ngauthier/awesome_site.git'
&lt;/pre&gt;

&lt;p&gt;That could pull the gem from github, but that’s suboptimal because you would have to also send a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;:ref&lt;/code&gt; in order to set the version, which would be a pain in the next section.&lt;/p&gt;

&lt;p&gt;A third option would be to build the gem locally and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scp&lt;/code&gt; it to the server and install, but that doesn’t use all the fun bundler stuff!&lt;/p&gt;

&lt;p&gt;You can use &lt;a href=&quot;http://guides.rubygems.org/run-your-own-gem-server/&quot;&gt;geminabox&lt;/a&gt; to run your own gem server that you can push gems too.&lt;/p&gt;

&lt;p&gt;OK, now we need a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config.ru&lt;/code&gt; file for the server. It’s the same as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;awesome_site&lt;/code&gt;’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config.ru&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
require 'rubygems'
require 'bundler'
Bundler.setup
require 'awesome_site'
run AwesomeSite::App
&lt;/pre&gt;

&lt;p&gt;Now, we can run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bundle&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rackup&lt;/code&gt; and we’re running our server based off our gem!&lt;/p&gt;

&lt;h2 id=&quot;deployment&quot;&gt;Deployment&lt;/h2&gt;

&lt;p&gt;As mentioned previously, you need to push the gem to your own gem server. That means either your gem server can check out the latest code and install the gem, or simply use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;geminabox&lt;/code&gt; to let developers push a gem. So the deployment steps would be:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Update &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;awesome_site&lt;/code&gt; in some way, and set &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AwesomeSite::VERSION&lt;/code&gt; to an updated number.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rake build&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gem inabox ./pkg/awesome_site-1.0.0.gem&lt;/code&gt; (then enter the geminabox server url when prompted)&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ssh production &quot;bundle update awesome_site &amp;amp;&amp;amp; sudo restart awesome_site&quot;&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is assuming you use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;upstart&lt;/code&gt; to manage your server process (probably my next blog topic).&lt;/p&gt;

&lt;p&gt;Now, if you want more control, put the server code into git and manually set the version number in the gemfile. That way you can roll back to a version if you have a problem with a deploy. But, you could also reverse the commit, but bump the gem version and deploy as usual. This is a more honest representation of what happened and it means the HEAD of the code is accurate.&lt;/p&gt;

&lt;h2 id=&quot;disclaimer&quot;&gt;Disclaimer&lt;/h2&gt;

&lt;p&gt;This is theoretical. The code is available at &lt;a href=&quot;http://github.com/ngauthier/awesome_site&quot;&gt;ngauthier/awesome_site&lt;/a&gt; and it does work. However I have never done this on a production application, so take care if you decide to go for it. I was just curious about what the process would be like.&lt;/p&gt;

&lt;p&gt;Happy monday!&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Raphael.js + Backbone.js + Traer.js</title>
    <link href="http://ngauthier.com/2012/02/raphael-backbone-traer.html"/>
    <updated>2012-02-23T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/02/raphael-backbone-traer</id>
    <content type="html">&lt;p&gt;&lt;a href=&quot;http://raphaeljs.com/&quot;&gt;Raphael.js&lt;/a&gt; is a cool vector graphic drawing library for javascript. It uses SVG (VML on IE) to draw just about anything, and provides lots of easy helper methods. The coolest thing about SVG is that since it’s XML it can be inserted directly into the dom, so every element has its own dom node.&lt;/p&gt;

&lt;p&gt;One of my favorite things about &lt;a href=&quot;http://documentcloud.github.com/backbone/&quot;&gt;Backbone.js&lt;/a&gt; is that the only assumption it makes about Views is that they will have a dom element, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;el&lt;/code&gt;. So, I thought it would be really cool if you used a Backbone.js view to render Raphael objects.&lt;/p&gt;

&lt;p&gt;Now, to make this extra awesome, I wanted to use the physics engine &lt;a href=&quot;http://code.google.com/p/traer-js/&quot;&gt;Traer.js&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This was the result:&lt;/p&gt;

&lt;h2 id=&quot;video&quot;&gt;Video&lt;/h2&gt;

&lt;div&gt;&lt;iframe class=&quot;youtube&quot; src=&quot;http://www.youtube.com/embed/S8n8P5fk5YY&quot; frameborder=&quot;0&quot; allowfullscreen=&quot;&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;

&lt;h2 id=&quot;demo&quot;&gt;Demo&lt;/h2&gt;

&lt;iframe src=&quot;/demo/backbone-raphael-traer.html&quot; frameborder=&quot;0&quot; class=&quot;youtube&quot; scrolling=&quot;no&quot;&gt;&lt;/iframe&gt;

&lt;p&gt;&lt;a href=&quot;/demo/backbone-raphael-traer.html&quot;&gt;Visit demo page&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There are four levels here:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Particle: managed by Traer&lt;/li&gt;
  &lt;li&gt;Model: Backbone model wrapping the particle&lt;/li&gt;
  &lt;li&gt;Element: svg element managed by Raphael&lt;/li&gt;
  &lt;li&gt;View: Backbone view wrapping the model and the element&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;step-1-modding-the-physics-engine&quot;&gt;Step 1. Modding the physics engine&lt;/h2&gt;

&lt;p&gt;This first thing I had to do was make two small changes to Traer:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
function Particle(mass) {
  this.position = new Vector();
  this.velocity = new Vector();
  this.force = new Vector();
  this.mass = mass;
  this.fixed = false;
  this.age = 0;
  this.dead = false;
  /* Attach Backbone's events to particles */
  _.extend(this, Backbone.Events);
}
&lt;/pre&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
RungeKuttaIntegrator.prototype.step = function (deltaT) {
  /* lots of physics stuff redacted */

  /* Change the conditional for skipping fixed nodes so that the
   * following runs for all particles after they've been computed:
   */
  p.trigger('change'); // p is the particle
&lt;/pre&gt;

&lt;p&gt;Now, particles will fire a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;change&lt;/code&gt; event after a physics tick.&lt;/p&gt;

&lt;h2 id=&quot;step-2-backbone-model-based-on-traer&quot;&gt;Step 2. Backbone Model based on Traer&lt;/h2&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
Exobrain.Node = Backbone.Model.extend({
  // expects a particle and a size parameter
  initialize: function(attributes) {
    // when the particle changes, we fire a change
    this.get('particle').on('change', function() {
      this.trigger('change'); 
    }, this);
    // keep track of children
    this.children = new Exobrain.NodeList();
  },
  // proxy some particle attributes
  x:    function() { return this.get('particle').position.x; },
  y:    function() { return this.get('particle').position.y; },
  size: function() { return this.get('size');                },
  particle: function() { return this.get('particle'); },

  // Make a new node under this one
  createChild: function() {
    var mass = 0.4;
    // random x and y
    var x = this.x() + Math.random() * 50 - 25;
    var y = this.y() + Math.random() * 50 - 25;
    var z = 0;
  
    // make the physics particle
    var particle = Exobrain.makeParticle(mass, x, y, z);
    // make a model
    var node = new Exobrain.Node({particle: particle, size: 10});
    // add it to our child list
    this.children.add(node);

    // setup a spring between the new node and us
    var spring = 0.02;
    var damping = 0.10;
    var length = 120;
    Exobrain.makeSpring(this.particle(), node.particle(), spring, damping, length);

    // fire a child event for the node we created
    this.trigger('child', node);
    // when the node gets a child, make a link with this node
    node.on('child', this.link, this);
    // also, any child of our child is also our child, so all nodes link up the tree
    node.on('child', function(child) { this.trigger('child', child) }, this);

    return node;
  },
  // make a repulsive force with a node
  link: function(node, strength) {
    if (node === this) { return; }
    /* strength scales exponentially with distance, this keeps the system
     * from &quot;folding up&quot;
     */
    if (strength === undefined) {
      strength = -100.0;
    } else {
      strength = strength * 2.0;
    }
    var distanceMin = 5.0;
    Exobrain.makeAttraction(this.particle(), node.particle(), strength, distanceMin);
    this.children.each(function(child) { child.link(node, strength) }, this);
  }
});

/* Collection automatically links siblings */
Exobrain.NodeList = Backbone.Collection.extend({
  model: Node,
  initialize: function(models, options) {
    this.on('add', this.linkNodes, this);
  },
  linkNodes: function(node) {
    this.each(function(other) {
      other.link(node);
    }, this);
  }
})
&lt;/pre&gt;

&lt;h2 id=&quot;step-2-raphael-based-view&quot;&gt;Step 2. Raphael-based view&lt;/h2&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
Exobrain.NodeView = Backbone.View.extend({
  // make a child on click
  events: {
    'click': 'createChild'
  },
  initialize: function() {
    // draw a node, set &quot;element&quot; to the raphael node
    this.element = Exobrain.drawNode(
      this.model.x(), this.model.y(), this.model.size()
    );
    // set the dom element to the raphael element's dom node
    this.setElement(this.element.node);
    this.model.on('change', this.render, this);
  },
  // render will just move the node, not re-draw it
  render: function() {
    this.element.attr('cx', this.model.x());
    this.element.attr('cy', this.model.y());
  },
  // Create a new model and a view for it
  createChild: function() {
    new Exobrain.NodeView({model: this.model.createChild()})
  }
});

var Exobrain = {
  /* redacted */

  // draw a raphael node
  drawNode: function(x,y,size) {
    // make a circle on the Raphael &quot;paper&quot;
    var el = this.paper.circle(x,y,size);
    // fill it with red
    el.attr({fill: 'red'});
    return el;
  }

  /* redacted */
};
&lt;/pre&gt;

&lt;h2 id=&quot;notes&quot;&gt;Notes&lt;/h2&gt;

&lt;p&gt;This is a great example of my style of Backbone programming. Make a namespace and put class definitions in it. Then only create instances within an onReady closure. No instances on the global namespaces!&lt;/p&gt;

&lt;p&gt;The only exception was that I have a global physics engine set to the Exobrain object as well as a Raphael &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;paper&lt;/code&gt; for drawing objects. I should probably make Exobrain a class and instantiate it with a div id, and have it allocate its own engine and paper.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Playing with Ember.js</title>
    <link href="http://ngauthier.com/2012/02/playing-with-ember.html"/>
    <updated>2012-02-19T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/02/playing-with-ember</id>
    <content type="html">&lt;p&gt;Today I played around with &lt;a href=&quot;http://emberjs.com&quot;&gt;Ember.js&lt;/a&gt;. I wanted to make my own Pomodoro timer, and I figured it would be a good way to try it out.&lt;/p&gt;

&lt;p&gt;One of the reasons I’m really excited about Ember is that its goal is to &lt;strong&gt;cut down on boilerplate code&lt;/strong&gt; especially in regards to keeping views up to date.&lt;/p&gt;

&lt;p&gt;I’d like to mention that I have no idea whether or not I really did this right. Ember’s docs are in a state of flux as the framework has yet to hit 1.0 and so much is changing. Also, I was particularly confused by the source code, as it seems to be in packages that don’t always have a clear hierarchy. For example, the core &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Ember.Application&lt;/code&gt; class is under &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;packages/ember-views/lib/system/application.js&lt;/code&gt;. So, I did dig around a while and I hope I am pretty close to the mark.&lt;/p&gt;

&lt;p&gt;First up, &lt;strong&gt;Ember’s HTML&lt;/strong&gt;&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;lt;script type=&quot;text/x-handlebars&quot; data-template-name='timer'&amp;gt;
  &amp;lt;div class='timeleft'&amp;gt;{{timeLeft}}&amp;lt;/div&amp;gt;
  &amp;lt;a href=&quot;#&quot; class='btn btn-large btn-primary' {{action &quot;pomodoro&quot;}}   &amp;gt;Pomodoro&amp;lt;/a&amp;gt;
  &amp;lt;a href=&quot;#&quot; class='btn btn-large'             {{action &quot;shortBreak&quot;}} &amp;gt;Short Break&amp;lt;/a&amp;gt;
  &amp;lt;a href=&quot;#&quot; class='btn btn-large'             {{action &quot;longBreak&quot;}}  &amp;gt;Long Break&amp;lt;/a&amp;gt;
  &amp;lt;a href=&quot;#&quot; class='btn btn-large btn-danger'  {{action &quot;stop&quot;}}       &amp;gt;Stop&amp;lt;/a&amp;gt;
&amp;lt;/script&amp;gt;
&amp;lt;h1&amp;gt;Pomodoro&amp;lt;/h1&amp;gt;
&amp;lt;div id='timer'&amp;gt;&amp;lt;/div&amp;gt;
&lt;/pre&gt;

&lt;p&gt;We define a reusable template as a handlebars script tag and give it a name. Then lower down is a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;#timer&lt;/code&gt; div that we’ll bind to. This is not the standard Ember way of placing a template. In the examples, you’ll see:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;lt;h1&amp;gt;Pomodoro&amp;lt;/h1&amp;gt;
&amp;lt;script type=&quot;text/x-handlebars&quot;&amp;gt;
  {{view Todos.MainView}}
&amp;lt;/script&amp;gt;
&lt;/pre&gt;

&lt;p&gt;However this really rubbed me the wrong way because I hate global variables (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Todos.MainView&lt;/code&gt;). This template itself is kind of a global since it’s directly in the dom. I prefer to give the template a global variable name (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;data-template-name&lt;/code&gt;) and have the view reference it.&lt;/p&gt;

&lt;p&gt;My other alternative would be to define the template in the code, but that would take it farther from the html it’s being used in. I would like feedback and advice on this, please!&lt;/p&gt;

&lt;p&gt;Next, is &lt;strong&gt;Ember’s Timer&lt;/strong&gt; (note: all the JS is in a jQuery onReady closure, hence &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;var&lt;/code&gt; not &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;window.&lt;/code&gt;, because I hate globals):&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
var Pomodoro = Em.Application.create();

var timer = Ember.Object.create({
  timeLeft: &quot;25:00&quot;,
  totalTime: 25*60*1000,
  
  start: function(time) {
    var _this = this;
    this.reset(time);
    this._startedAt = new Date();
    this._intervalId = setInterval(function() { _this.updateTimeLeft.apply(_this); }, 100);
  },
  
  reset: function(time) {
    clearInterval(this._intervalId);
    if (time) {
      this.set('totalTime', time*60*1000);
    }
    this.set('timeLeft', msToString(this.get('totalTime')));
  },
  
  updateTimeLeft: function() {
    var now = new Date();
    var diff = now - this._startedAt;
    this.set('timeLeft', msToString(this.get('totalTime') - diff));
  }
});
&lt;/pre&gt;

&lt;p&gt;We’re using Ember’s Object base class, and we are making use of the getters and setters, which let us bind in the view. Here’s &lt;strong&gt;Ember’s View&lt;/strong&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
Ember.View.create({
  templateName: 'timer',
  timer: timer,
  timeLeftBinding: 'timer.timeLeft',

  pomodoro: function(){
    this.timer.start(25);
  },
  shortBreak: function() {
    this.timer.start(5);
  },
  longBreak: function() {
    this.timer.start(15);
  },
  stop: function() {
    this.timer.reset();
  }
}).appendTo('#timer');
&lt;/pre&gt;

&lt;p&gt;We’re binding the View to the template we created, we’re setting a local var &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timer&lt;/code&gt; to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timer&lt;/code&gt; var we instantiated when making our timer. Then we bind the view’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timeLeft&lt;/code&gt; attribute to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timer&lt;/code&gt;’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timeLeft&lt;/code&gt; attribute. This will automatically update the dom, when the model’s attribute changes. The special naming &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timeLeftBinding&lt;/code&gt; means that it’s a binding.&lt;/p&gt;

&lt;p&gt;The next four methods are triggered by clicking the template links with the actions of the same name. So if you look at the template, each link has an action, and that action is a function to call on the view.&lt;/p&gt;

&lt;p&gt;I looked for a controller to use, since the view is really being both a controller and a view here (actually, the model does some of the view work too, as it formats its timestamp). However, the only Ember controller I could find was an ArrayController, which is actually just an Array with some event bindings. So, I guess they don’t have the C of MVC yet.&lt;/p&gt;

&lt;p&gt;All in all, there is not a lot of boilerplate code here, so nice job guys!&lt;/p&gt;

&lt;p&gt;Now, I can’t leave it there, because I’ve done a ton of work with Backbone.js, and it seems like Ember is calling out Backbone and others like it “&lt;a href=&quot;http://emberjs.com&quot;&gt;obvious low-level event-driven abstractions&lt;/a&gt;.”&lt;/p&gt;

&lt;p&gt;So, I implemented the same timer in Backbone to see how much boilerplate I had to write:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Backbone’s HTML&lt;/strong&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;lt;h1&amp;gt;Pomodoro&amp;lt;/h1&amp;gt;
&amp;lt;div id='backbone-timer'&amp;gt;
  &amp;lt;div class='timeleft'&amp;gt;&amp;lt;/div&amp;gt;
  &amp;lt;a href=&quot;#&quot; class='btn btn-large btn-primary pomodoro'   &amp;gt;Pomodoro&amp;lt;/a&amp;gt;
  &amp;lt;a href=&quot;#&quot; class='btn btn-large             short-break'&amp;gt;Short Break&amp;lt;/a&amp;gt;
  &amp;lt;a href=&quot;#&quot; class='btn btn-large             long-break' &amp;gt;Long Break&amp;lt;/a&amp;gt;
  &amp;lt;a href=&quot;#&quot; class='btn btn-large btn-danger  stop'       &amp;gt;Stop&amp;lt;/a&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;

&lt;p&gt;Unlike Ember, this is direct html I am writing right in the dom, not script tags. If there’s a way to bind Ember to existing elements, let me know!&lt;/p&gt;

&lt;p&gt;Next, we have &lt;strong&gt;Backbone’s Timer&lt;/strong&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
var timer = new (Backbone.Model.extend({
  defaults: {
    timeLeft: &quot;25:00&quot;,
    totalTime: 25*60*1000
  },

  start: function(time) {
    this.reset(time);
    this._startedAt = new Date();
    this._intervalId = setInterval(_.bind(this.updateTimeLeft, this), 100);
  },

  reset: function(time) {
    clearInterval(this._intervalId);
    if (time) {
      this.set('totalTime', time*60*1000);
    }
    this.set('timeLeft', msToString(this.get('totalTime')));
  },
  
  updateTimeLeft: function() {
    var now = new Date();
    var diff = now - this._startedAt;
    this.set('timeLeft', msToString(this.get('totalTime') - diff));
  }
}))();
&lt;/pre&gt;

&lt;p&gt;The first difference is we don’t have to init an application, because Backbone is a library, not a framework. The second difference is that Backbone has a forced separation between get/set attributes and object attributes. Thus there is a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;defaults&lt;/code&gt; hash for the get/set attributes, as opposed to declaring them on the object. I find this to be more declarative than Ember’s syntax.&lt;/p&gt;

&lt;p&gt;The next difference is that since underscore is a dependency, I used &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;_.bind&lt;/code&gt; for the timer. But we could do this in Ember too, if we brought in underscore.&lt;/p&gt;

&lt;p&gt;Other than that, these objects are almost exactly the same.&lt;/p&gt;

&lt;p&gt;Let’s look at &lt;strong&gt;Backbone’s View&lt;/strong&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
new (Backbone.View.extend({
  events: {
    'click a.pomodoro'   : 'pomodoro',
    'click a.short-break': 'shortBreak',
    'click a.long-break' : 'longBreak',
    'click a.stop'       : 'stop'
  },

  initialize: function() {
    this.model.bind('change:timeLeft', this.updateTimeLeft, this);
  },

  render: function() {
    this.updateTimeLeft();
    return this;
  },

  updateTimeLeft: function() {
    this.$('.timeleft').text(this.model.get('timeLeft'));
  },

  pomodoro: function() {
    this.model.start(25);
  },

  shortBreak: function() {
    this.model.start(5);
  },

  longBreak: function() {
    this.model.start(15);
  },

  stop: function() {
    this.model.reset();
  }
}))({el: $('#backbone-timer'), model: timer}).render();
&lt;/pre&gt;

&lt;p&gt;Now we’re seeing some difference! In Backbone, we have to bind all the link actions ourselves on the view instead of on the template. This is definitely more legwork on the View’s part, but remember is means that template could drive different views with different behavior, because the behavior is defined in the view, not the template. Personally, I like to keep code out of my templates.&lt;/p&gt;

&lt;p&gt;Next, we have to manually bind the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;change&lt;/code&gt; event on the model to a method that updates the text of that dom element. Definitely boilerplate. Ember does this by automatically creating wrapper divs like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;div id=&quot;ember150&quot; class=&quot;ember-view&quot;&amp;gt;&lt;/code&gt; that wrap your templated attributes and auto-updates them.&lt;/p&gt;

&lt;p&gt;After that, the methods are the same. Then when we initialize we give it a dom element to bind to, and we have to manually tell it to render the first time.&lt;/p&gt;

&lt;p&gt;At this point, I’d like to pull out a refactoring from &lt;a href=&quot;http://recipeswithbackbone.com&quot;&gt;Recipes with Backbone&lt;/a&gt; from the Fill-In Views chapter. Check this out:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
/* EDIT: updated to use #constructor. Thanks Tim Branyen! */
Backbone.BoundView = Backbone.View.extend({
  constructor: function(options) {
    Backbone.View.apply(this, arguments);

    this.model.bind('change', this.updateBoundAttributes, this);
    this._oldRender = this.render;
    this.render = function() { this._oldRender(); this.updateBoundAttributes(); };
  },

  updateBoundAttributes: function() {
    _(this.bindings).each( function(value, key) {
      this.$(key).html(this.model.get(value))
    }, this);
  }
});
&lt;/pre&gt;

&lt;p&gt;This &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Backbone.BoundView&lt;/code&gt; is a subclass of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Backbone.View&lt;/code&gt; and it uses a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bindings&lt;/code&gt; object to automatically update model attributes on change. That means we can simplify our view to this:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
  new (Backbone.BoundView.extend({
    events: {
      'click a.pomodoro'   : 'pomodoro',
      'click a.short-break': 'shortBreak',
      'click a.long-break' : 'longBreak',
      'click a.stop'       : 'stop'
    },

    bindings: {
      '.timeleft': 'timeLeft'
    },

    pomodoro: function() {
      this.model.start(25);
    },

    shortBreak: function() {
      this.model.start(5);
    },

    longBreak: function() {
      this.model.start(15);
    },

    stop: function() {
      this.model.reset();
    }
  }))({el: $('#backbone-timer-2'), model: timer}).render();
});
&lt;/pre&gt;

&lt;p&gt;We still have the event bindings, but now all the model updating code has been reduced to a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bindings&lt;/code&gt; object that maps dom classes to model attributes. Much better!&lt;/p&gt;

&lt;p&gt;All-in-all, I have to say I’m not super impressed with Ember’s view and model bindings. But, I could certainly not be taking full advantage of them at this time. I did experiment with computed attributes, and those were neat. I do like the idea that functions can behave as properties as well. Also, we didn’t get into any of Ember’s other awesome features like states.&lt;/p&gt;

&lt;p&gt;I was planning on making my Pomodoro timer in Ember, but after having some issues with the docs and the source, and not finding many satisfactory examples, I’m going to stick with Backbone for now. But you can be sure when Ember hits 1.0 I’m going to check it out!&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Quick Ruby Tests with Bash</title>
    <link href="http://ngauthier.com/2012/02/quick-tests-with-bash.html"/>
    <updated>2012-02-16T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/02/quick-tests-with-bash</id>
    <content type="html">&lt;p&gt;In Ruby on Rails development, we have great gems like &lt;a href=&quot;https://github.com/guard/guard&quot;&gt;Guard&lt;/a&gt; that will re-run tests or other tasks based on changing files. I was interested in finding something more lightweight but less configurable and flexible that I could use on smaller projects.&lt;/p&gt;

&lt;p&gt;I ended up writing this quick bash script that I put on my path called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;live&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#/usr/bin/env sh
# Usage &quot;live command&quot;
clear
$*
while inotifywait -qr -e close_write *; do clear; $*; done
&lt;/pre&gt;

&lt;p&gt;This script takes a command as an argument and re-runs the command whenever any file in the current directory changes. So, you can simply re-run the tests of a project by running &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;live rake&lt;/code&gt;. Or, you could re-output a project directory with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;live tree&lt;/code&gt;. It’s like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;watch&lt;/code&gt; except evented on write changes.&lt;/p&gt;

&lt;p&gt;The next thing I noticed while using this on larger (rails) projects is that project boot is slow and the tests run in different groups that each boot the environment.&lt;/p&gt;

&lt;p&gt;Note the raw time it takes to run the project’s tests:&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
$ time rake
Loaded suite /home/nick/workspace/giftsmart/.bundle/gems/ruby/1.9.1/gems/rake-0.9.2.2/lib/rake/rake_test_loader
Started
....
Finished in 0.588015 seconds.

4 tests, 30 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 54473
Loaded suite /home/nick/workspace/giftsmart/.bundle/gems/ruby/1.9.1/gems/rake-0.9.2.2/lib/rake/rake_test_loader
Started
...............
Finished in 3.679384 seconds.

15 tests, 77 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 45532

real  0m41.495s
user  0m38.502s
sys   0m1.928s
&lt;/pre&gt;

&lt;p&gt;Seriously?! 41.5 seconds to run just over 4 seconds worth of tests? &lt;a href=&quot;https://www.destroyallsoftware.com/talks/wat&quot;&gt;WAT?&lt;/a&gt; And this is using ruby-1.9.3-falcon!&lt;/p&gt;

&lt;p&gt;So, my first step was to merge the environments and optionally skip &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;db:reset&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
# lib/tasks/testing.rake
namespace :test do
  desc 'Run tests quickly by merging all types and not resetting db'
  Rake::TestTask.new('fast') do |t|
    t.libs &amp;lt;&amp;lt; 'test'
    t.pattern = &quot;test/**/*_test.rb&quot;
  end

  namespace :fast do
    desc 'Run tests quickly, but also reset db'
    task :db =&amp;gt; ['db:test:prepare', 'test:fast']
  end
end
&lt;/pre&gt;

&lt;p&gt;This provides &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rake test:fast:db&lt;/code&gt; which reset the db and runs the tasks merged as one, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rake test:fast&lt;/code&gt; which merges the tasks and doesn’t reset the db. Here’s the result:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
$ time rake test:fast:db
Loaded suite /home/nick/workspace/giftsmart/.bundle/gems/ruby/1.9.1/gems/rake-0.9.2.2/lib/rake/rake_test_loader
Started
...................
Finished in 3.752755 seconds.

19 tests, 107 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 57655

real  0m28.430s
user  0m26.138s
sys   0m1.216s
&lt;/pre&gt;

&lt;p&gt;OK, that’s a 46% improvement. Now, without the db:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
$ time rake test:fast
Loaded suite /home/nick/workspace/giftsmart/.bundle/gems/ruby/1.9.1/gems/rake-0.9.2.2/lib/rake/rake_test_loader
Started
...................
Finished in 3.790390 seconds.

19 tests, 107 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 53405

real  0m21.623s
user  0m20.525s
sys   0m1.020s
&lt;/pre&gt;

&lt;p&gt;Better, a 92% improvement! But it’s still 3.8 seconds worth of test at 21.6 seconds. Lame.&lt;/p&gt;

&lt;p&gt;Now it’s time for drastic measures. When I’m running tests, I see this process:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
/usr/bin/ruby1.9.1 -Ilib:test /path/to/my/project/.bundle/gems/ruby/1.9.1/gems/rake-0.9.2.2/lib/rake/rake_test_loader.rb test/unit/**/*_test.rb
&lt;/pre&gt;

&lt;p&gt;This is because Rake::TestTask shells out to ruby to keep the environment clean. This works great for projects with minimal boot times. But in my case, I have a much larger Rails boot I have to worry about. This means I’m still booting Rails twice!&lt;/p&gt;

&lt;p&gt;So, I made a short ruby script that gives me direct access to the rake test loader for the current project:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
#!/usr/bin/env sh
ruby -Ilib:test `bundle list rake`/lib/rake/rake_test_loader.rb $*
&lt;/pre&gt;

&lt;p&gt;Now, here are my results:&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
$ time rtest test/**/*_test.rb
Run options:

# Running tests:

...................

Finished tests in 3.070074s, 6.1888 tests/s, 34.8526 assertions/s.

19 tests, 107 assertions, 0 failures, 0 errors, 0 skips

real  0m9.579s
user  0m9.089s
sys   0m0.324s
&lt;/pre&gt;

&lt;p&gt;There we go! That’s 333% faster! Now the total time to run my tests is 1xRails and 1xTest. This is probably the minimal boot time I could get without keeping the environment hot loaded. The best part is, I can combine my two scripts:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
$ live time rtest test/**/*_test.rb
&lt;/pre&gt;

&lt;p&gt;Now I have a very fast and minimal live-updating setup written in 4 lines of bash that is portable across projects.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Ruby and the Web</title>
    <link href="http://ngauthier.com/2012/02/ruby-and-the-web.html"/>
    <updated>2012-02-14T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/02/ruby-and-the-web</id>
    <content type="html">&lt;p&gt;Here's a talk I gave at Bmore on Rails (Baltimore's Rails user group). I talk about MVC vs Model 2 and how they apply to Rails. I talk about Frameworks vs Libraries and White Box vs Black box. Also I talk about a theoretical framework I experimented with to try to implement a more object oriented system for dealing with the web in Ruby (based on Rack).&lt;/p&gt;

&lt;p&gt;Enjoy.&lt;/p&gt;

&lt;div&gt;&lt;iframe class='youtube' src=&quot;http://www.youtube.com/embed/kEHtE93hcz8&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt;&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>Simple ruby setup on ubuntu</title>
    <link href="http://ngauthier.com/2012/01/simple-ruby-on-ubuntu.html"/>
    <updated>2012-01-30T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/01/simple-ruby-on-ubuntu</id>
    <content type="html">&lt;p&gt;Today I setup a new development machine. My preferred OS is &lt;a href=&quot;http://xubuntu.com&quot;&gt;Xubuntu&lt;/a&gt;, which is Ubuntu + XFCE (a light window manager). In the past I’ve used RVM and have been happy with it, except for one thing: compiling.&lt;/p&gt;

&lt;p&gt;I used to use Gentoo, which is a linux distribution in which all software is installed by downloading the source and compiling. This is a brutal and intense introduction to linux, and I learned a hell of a lot using Gentoo in college. However, I feel like I’ve paid my dues in linux boot camp and now I want to simply install binary packages and have a ruby setup lightning-quick.&lt;/p&gt;

&lt;p&gt;So, here were my steps to get ruby (and postgres) setup:&lt;/p&gt;

&lt;h2 id=&quot;ruby&quot;&gt;Ruby&lt;/h2&gt;

&lt;p&gt;Install ruby, rubygems, a few dependencies and postgres: &lt;a href=&quot;apt:libxslt1-dev,libxml2-dev,build-essential,g++,ruby1.9.1-dev,postgresql,libpq-dev&quot;&gt;libxslt1-dev libxml2-dev build-essential g++ ruby1.9.1-dev postgresql libpq-dev&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;bundler-and-gem-scoping&quot;&gt;Bundler and gem-scoping&lt;/h2&gt;

&lt;p&gt;The only remaining issue is how to manage sets of gems between projects. I chose to do something here which leverages one of bundler’s great features to achieve a halfway gemset solution. It is not exclusive of gems installed globally, but it gives priority to local binaries over global ones.&lt;/p&gt;

&lt;p&gt;In your .bashrc (or whatever shell init script):&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
alias bundle-bootstrap=&quot;bundle install --binstubs=.bundle/bin --path=.bundle/gems&quot;
export GEM_HOME=$HOME/.gems
export PATH=.bundle/bin:$GEM_HOME/bin:$PATH
&lt;/pre&gt;

&lt;p&gt;The bundler alias will put binstubs (shell scripts that run a gem’s binary) into the current directory’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.bundle/bin&lt;/code&gt;. It also says to store the gem sources in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.bundle/gems&lt;/code&gt;. This means that as soon as you leave this directory, it’s like those gems aren’t even installed!&lt;/p&gt;

&lt;p&gt;The second line puts the current directory’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.bundle/bin&lt;/code&gt; as the highest priority for finding binaries, followed by my home directory’s gems binary folder. This means that local gem binaries take precedent. That means &lt;strong&gt;no more bundle exec&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The third line sets up my gem home so if I just run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gem install&lt;/code&gt; they go to my home. This is where I put bundler, jekyll, heroku, etc.&lt;/p&gt;

&lt;h2 id=&quot;setting-up-a-project&quot;&gt;Setting up a project&lt;/h2&gt;

&lt;p&gt;So, when I setup a new project, it looks like:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
git clone git@github.com:user/repo.git
cd repo
bundle-bootstrap
&lt;/pre&gt;

&lt;p&gt;Now everything is installed and setup. Binaries are available but don’t contaminate any other projects.&lt;/p&gt;

&lt;p&gt;Hope this helps all my fellow linux rubyists on having a fast and clean ruby install!&lt;/p&gt;

&lt;p&gt;xoxo &lt;a href=&quot;http://twitter.com/ngauthier&quot;&gt;@ngauthier&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;P.S.: if you need ruby 1.8.7, check out rbenv, which is now in APT as of 12.04. You can install ruby 1.8 from APT then use rbenv to switch rubies. I haven’t used it myself but it seems to be what people prefer.&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Galaxy Nexus First Impressions</title>
    <link href="http://ngauthier.com/2012/01/galaxy-nexus-first-impressions.html"/>
    <updated>2012-01-04T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/01/galaxy-nexus-first-impressions</id>
    <content type="html">&lt;p&gt;I got a Samsung Galaxy Nexus yesterday and &lt;a href=&quot;https://twitter.com/#!/reillyhawk/status/154314709540159490&quot;&gt;@reillyhawk asked me to share a review&lt;/a&gt;. Disclaimer: I’ve had this device for 20 hours.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;It’s big, but it’s the same weight as my old HTC Incredible (135g vs 130g). It has an extra inch of screen space (4.65” vs 3.7”). The feeling in your hand is like a well balanced sword. Seriously.&lt;/li&gt;
  &lt;li&gt;It’s so big my thumb can’t reach the opposite corner with the phone in the crook of my palm. The opposite corner is a common place for non-standard menus. Dear apps: use ICS menus! (bottom right instead of top right).&lt;/li&gt;
  &lt;li&gt;It’s really fast. The screen is very responsive. The throw-weight of scrolling is increased (meaning it doesn’t coast as far for small throws) and it feels good.&lt;/li&gt;
  &lt;li&gt;Swype isn’t available yet, even though I’m in the beta.&lt;/li&gt;
  &lt;li&gt;The keyboard is easy to type on because of the extra screen size.&lt;/li&gt;
  &lt;li&gt;ICS’s app folders are nice.&lt;/li&gt;
  &lt;li&gt;Calendar widget is sweet.&lt;/li&gt;
  &lt;li&gt;32G on-device memory means no sd card needed, which is nice.&lt;/li&gt;
  &lt;li&gt;I haven’t found a single piece of crapware yet.&lt;/li&gt;
  &lt;li&gt;I’ve only used wifi (at home) so I can’t comment on 4G speeds.&lt;/li&gt;
  &lt;li&gt;Browser is snappier, the zoom is much quicker. I love android’s text reflow.&lt;/li&gt;
  &lt;li&gt;I miss Cyanogen’s tethering and ability to change the number of home screens (I like having one immovable screen). I haven’t looked into root options yet, and won’t for a couple weeks to make sure I’m keeping the phone and there are no problems.&lt;/li&gt;
  &lt;li&gt;At minimum brightness when looking at solid colors or gradients, AMOLED banding is visible. I’m not too annoyed though. Really only happens and night and I should put the phone down and pick up the kindle :-)&lt;/li&gt;
  &lt;li&gt;It comes with an earbud and mic combo. I haven’t tried them out yet.&lt;/li&gt;
  &lt;li&gt;Headphone jack on the bottom is perfect, because you always put your phone into your pocket face-down, so the cables should come out the bottom.&lt;/li&gt;
  &lt;li&gt;The lock button is opposite the volume button, so when you push lock you have to be careful not to brace against the volume keys. I can’t believe how many devices do this. My timex watch has the same issue. Put buttons opposite spaces in the frame!&lt;/li&gt;
  &lt;li&gt;No hardware buttons is not a problem for me at all. I love the fact that it’s just a big hunk of screen. Looks awesome. Netflix is beautiful.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That’s it for now!&lt;/p&gt;
</content>
  </entry>
  
  <entry>
    <title>Open for Business</title>
    <link href="http://ngauthier.com/2012/01/open-for-business.html"/>
    <updated>2012-01-02T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2012/01/open-for-business</id>
    <content type="html">&lt;p&gt;I’m excited to announce that I’m now open for business!&lt;/p&gt;

&lt;p&gt;If you don’t already know me, let me introduce myself: my name is Nick Gauthier and I am a &lt;strong&gt;Ruby and Javascript&lt;/strong&gt; coder and I specialize in web development with the &lt;strong&gt;Rails&lt;/strong&gt; framework. I particularly enjoy &lt;strong&gt;performance-tweaking&lt;/strong&gt; applications, designing application &lt;strong&gt;architecture&lt;/strong&gt;, and writing &lt;strong&gt;clean&lt;/strong&gt;, &lt;strong&gt;object-oriented&lt;/strong&gt;, and &lt;strong&gt;test-driven&lt;/strong&gt; code. I’ve &lt;a href=&quot;http://lanyrd.com/profile/ngauthier/&quot;&gt;spoken at a couple of conferences including RailsConf 2011&lt;/a&gt;, and I recently wrote an e-book called &lt;a href=&quot;http://recipeswithbackbone.com&quot;&gt;Recipes with Backbone&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In 2012 I’m starting a new chapter in my life by striking out on my own. I plan to focus on three things:&lt;/p&gt;

&lt;h2 id=&quot;1-consulting-and-freelance-development&quot;&gt;1. Consulting and Freelance Development&lt;/h2&gt;

&lt;p&gt;Does your team need a boost? I can help out with planning, brainstorming, and kickstarting your project. Or maybe it’s getting a little clunky and needs a tune-up?&lt;/p&gt;

&lt;p&gt;Or, do you need someone to build your prototype or MVP? Someone that can work quickly and produce high quality code that will make the next developer smile?&lt;/p&gt;

&lt;h2 id=&quot;2-technical-training&quot;&gt;2. Technical Training&lt;/h2&gt;

&lt;p&gt;I’m going to be teaching a variety of courses as an instructor at &lt;a href=&quot;http://jumpstartlab.com&quot;&gt;Jumpstart Lab&lt;/a&gt;. I’m also available for private training in Ruby on Rails and Backbone.js. I’m also considering some unorthodox methods like holding open office hours, pair programming, or maybe an apprenticeship program.&lt;/p&gt;

&lt;h2 id=&quot;3-new-projects&quot;&gt;3. New Projects&lt;/h2&gt;

&lt;p&gt;Last, but not least, I’m leaving some time open for new projects. I’ll be exploring some ideas of my own but would welcome collaboration. I’m especially interested in working with designers in the Baltimore area.&lt;/p&gt;

&lt;h2 id=&quot;get-in-touch&quot;&gt;Get in touch&lt;/h2&gt;

&lt;p&gt;Let’s get in touch. I’m &lt;strong&gt;ngauthier&lt;/strong&gt; on Twitter, Github, and Gmail, so drop me a line!&lt;/p&gt;

&lt;h2 id=&quot;availability&quot;&gt;Availability&lt;/h2&gt;

&lt;iframe src=&quot;https://www.google.com/calendar/b/0/embed?showTitle=0&amp;amp;showPrint=0&amp;amp;showCalendars=0&amp;amp;height=570&amp;amp;wkst=1&amp;amp;bgcolor=%23FFFFFF&amp;amp;src=i2d4156i2c7rph1bcsg9rtpe8k%40group.calendar.google.com&amp;amp;color=%238C500B&amp;amp;ctz=America%2FNew_York&quot; style=&quot; border-width:0 &quot; width=&quot;100%&quot; height=&quot;570&quot; frameborder=&quot;0&quot; scrolling=&quot;no&quot;&gt;&lt;/iframe&gt;
</content>
  </entry>
  
  <entry>
    <title>Recipes with Backbone Released!</title>
    <link href="http://ngauthier.com/2011/12/recipes-with-backbone-released.html"/>
    <updated>2011-12-07T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2011/12/recipes-with-backbone-released</id>
    <content type="html">&lt;div class='post'&gt;
&lt;p&gt;Chris Strom and I have finished our e-book on Backbone JS: &quot;Recipes with Backbone&quot;. It is now available at &lt;a href=&quot;http://recipeswithbackbone.com&quot;&gt;http://recipeswithbackbone.com&lt;/a&gt; for $24.&lt;p&gt;&lt;p&gt;The book is targeted at the intermediate to advanced level backbone developer, but that's not to say beginners won't get anything out of it. To quote the site:&lt;/p&gt;&lt;ul&gt;  &lt;li&gt;This is &lt;em&gt;not the definitive guide&lt;/em&gt; to Backbone.js.&lt;/li&gt;  &lt;li&gt;This is &lt;em&gt;not an introduction&lt;/em&gt; to Backbone.js.&lt;/li&gt;  &lt;li&gt;This is the book you read &lt;em&gt;after you read the tutorial&lt;/em&gt;.&lt;/li&gt;  &lt;li&gt;This is the book that teaches you to &lt;em&gt;kick ass&lt;/em&gt; with the hottest Javascript MVC framework around.&lt;/li&gt;  &lt;li&gt;This is &lt;strong&gt;Recipes with Backbone&lt;/strong&gt;&lt;/li&gt;  &lt;li&gt;&lt;a href=&quot;http://recipeswithbackbone.com/toc.html&quot;&gt;Preview the table of contents&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;So if you want to learn more about backbone js, buy it!&lt;/p&gt;&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>Mocking on Rails</title>
    <link href="http://ngauthier.com/2011/11/mocking-on-rails.html"/>
    <updated>2011-11-03T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2011/11/mocking-on-rails</id>
    <content type="html">&lt;div class='post'&gt;
&lt;p&gt;Gregory Moeck's awesome post &lt;a href=&quot;http://gmoeck.github.com/2011/10/26/stubbing-is-not-enough.html&quot;&gt;Stubbing is Not Enough&lt;/a&gt; got my brain back on the subject of mocking. Readers of this blog may note that I had &lt;a href=&quot;http://www.ngauthier.com/2010/12/everything-that-is-wrong-with-mocking.html&quot;&gt;quite a rant against mocking&lt;/a&gt; almost a year ago and &lt;a href=&quot;http://gmoeck.github.com/2010/12/10/mocks-history-and-ruby.html&quot;&gt;Gregory posted a response&lt;/a&gt;. I think the result of that post and the discussion that ensued was not that mocking and/or stubbing were bad practices, but that when they are applied inappropriately they can quickly deteriorate the tests and the design of an application.&lt;/p&gt;&lt;p&gt;After reading Gregory's article, I wanted to revisit the state of mocking in Rails applications. One of the things I noticed in his article was that he was addressing some ruby classes and their interactions. He enforced the OO concepts of message passing and how mocks are better than stubs at testing very OO code. While I really like his solution, something was nagging at me: how can I do this &lt;em&gt;in Rails&lt;/em&gt;?&lt;p&gt;&lt;p&gt;For example, here is the stock rails scaffold controller and functional test:&lt;/p&gt;&lt;pre class='prettyprint'&gt;class PostsController &lt; ApplicationController&lt;br /&gt;  # GET /posts&lt;br /&gt;  # GET /posts.json&lt;br /&gt;  def index&lt;br /&gt;    @posts = Post.all&lt;br /&gt;&lt;br /&gt;    respond_to do |format|&lt;br /&gt;      format.html # index.html.erb&lt;br /&gt;      format.json { render :json =&gt; @posts }&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class PostsControllerTest &lt; ActionController::TestCase&lt;br /&gt;  setup do&lt;br /&gt;    @post = posts(:one)&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  test &quot;should get index&quot; do&lt;br /&gt;    get :index&lt;br /&gt;    assert_response :success&lt;br /&gt;    assert_not_nil assigns(:posts)&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;What can I mock? In Gregory Moeck's example, the ticket reservation object was passed in to the ticket machine interface (dependency injection) so we could easily mock the ticket reservation role and assert that the ticket machine interface interacted with it properly. He also intentionally doesn't touch the @current_display variable because it is internal to the system.&lt;/p&gt;&lt;p&gt;In our Rails controller and functional test, we can observe the following:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;The actions taken by the controller are internal, not based on roles it should interact with&lt;/li&gt;&lt;li&gt;The functional test is testing internal state (assigns) and not messages passed by the controller&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;My gut at this point says I'm on an integration boundary between the user and my internal system. So that means I would have an integration test on the controller. But still, the signature of a rails controller to call activerecord and render doesn't seem to lend itself to encapsulation and mocking.&lt;/p&gt;&lt;p&gt;At this point I attempted to write what I thought was a change to the way controllers work using dependency injection and object composition, but I failed at it. So I'm leaving this post with some open questions:&lt;/p&gt;&lt;ol&gt;&lt;li&gt;What is the proper way to test rails requests with mocking?&lt;/li&gt;&lt;li&gt;What is the proper way to do an integration test, and how deep should it go (i.e. beyond the point that you have covered with unit tests)?&lt;/li&gt;&lt;li&gt;Are there other web frameworks out there with great encapsulation as a best-practice?&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Super extra bonus points if you post links to open source projects that have a test suite that actually do these things well. Thanks.&lt;/p&gt;&lt;/div&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;div class='comments'&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Greg Moeck&lt;/div&gt;
&lt;div class='content'&gt;
A good number of people have asked me that question since I wrote the post. My general response is two fold. &lt;br /&gt;&lt;br /&gt;First, if I&amp;#39;m just doing CRUD reading and writing, I don&amp;#39;t really feel the need to have unit tests for the project, so long as I have end-to-end acceptance tests. The logic in Rails is simple enough that a computer could write it, so I don&amp;#39;t really feel a high degree of risk there.&lt;br /&gt;&lt;br /&gt;However if I&amp;#39;m dealing with a complex domain then I tend to separate out my domain layer from Rails, and treat my controllers as ports (from Alistair Cockburn&amp;#39;s ports and adapters architecture) into and out of the web. I will have them talk to an adapter within my domain, which is all well encapsulated and heavily unit tested. I generally don&amp;#39;t unit test the controller or the view layer , and just let my end-to-end acceptance tests ensure that everything is plugged together correctly. However if something is particularly hairy I will cover the rails part in an integration test.&lt;br /&gt;&lt;br /&gt;The basic approach is similar to what Eric Evans calls the &amp;quot;Anticorruption Layer&amp;quot; in Domain Driven Design (page. 366).&lt;br /&gt;&lt;br /&gt;I&amp;#39;m working on a sample application for an auction house which you can at see at https://github.com/gmoeck/auction_house. There isn&amp;#39;t much to see in the actual domain layer yet, but it will give you a general idea.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
awesome, thank you for chiming in. One thing I&amp;#39;ve been mulling over is how much of the variability in the controller&amp;#39;s form=&amp;gt;params=&amp;gt;domain model do you cover w/ acceptance tests?&lt;br /&gt;&lt;br /&gt;If a form has a bunch of params, some options (radio buttons) some non-required some required, you have to make sure the fields are wired up some how to get passed in to your domain model. Do you test all the paths?&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Greg Moeck&lt;/div&gt;
&lt;div class='content'&gt;
I personally tend to try and leave that stuff to the adapter to decide what to do with and think of the controller as more of just the way that I receive and send data. That&amp;#39;s why i don&amp;#39;t generally don&amp;#39;t feel the need to unit test them because the controller is just getting all the data relavent to the request and handing it off to the domain to decide what it means. My adapter object will generally then read the parameters and send messages into the domain in the domain&amp;#39;s language according to whatever the parameters mean. This isolates my actual domain objects from changes in the system and allows me to plug in the same domain into another delivery mechanism so long as I write an adapter for it. &lt;br /&gt;&lt;br /&gt;The more complex side is when the controller then queries the &amp;quot;view side&amp;quot; of the domain to get a response object, which then passes that data to the view, or renders an error or something. This is where my integration sort of tests will sometimes come in if I want to unit test that logic because it is getting complex. &lt;br /&gt;&lt;br /&gt;I certainly don&amp;#39;t feel like I have this all figured out, and I&amp;#39;m personally excited that people are starting to think more along these lines because I feel like the Rails side of the equation is going to clean up a bit in the immediate future. Sometimes I do feel like Rails is a bit of an overkill though since I can use Rack and accomplish most of what I&amp;#39;m wanting to do with the &amp;quot;web framework&amp;quot; part of my application.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
cool.&lt;br /&gt;&lt;br /&gt;So generally your domain objects play into the controller like:&lt;br /&gt;&lt;br /&gt;if obj.create(params); head :ok; else; render :json =&amp;gt; obj.errors&lt;br /&gt;&lt;br /&gt;I&amp;#39;ve been looking more into goliath and it seems to strike a nice balance of rack-like directness (no magic) and also basic HTTP API niceties like content encoding.&lt;br /&gt;&lt;br /&gt;Personally, I&amp;#39;ve been on an &amp;quot;acceptance test everything no unit tests&amp;quot; kick. It has proven to:&lt;br /&gt;&lt;br /&gt;1) make very reliable software&lt;br /&gt;2) make very slow test suites&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Sam Goldman&lt;/div&gt;
&lt;div class='content'&gt;
This is perhaps an unfairly literal response to a contrived example, but if you are writing controllers like that, another option would be to use a library like inherited_resources, which is already well-tested, and just test the happy path in an integration.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
well yeah if you&amp;#39;re using the stock scaffold you don&amp;#39;t need to test it either, since scaffolds are well tested.&lt;br /&gt;&lt;br /&gt;Mostly just interested because this is the standard way of writing a controller action.&lt;br /&gt;&lt;br /&gt;As an aside, I&amp;#39;m not a big fan of inherited resources. I prefer scaffolding. Tracking down bugs and determining behavior w/ inherited resources is a pain. I&amp;#39;d rather type it out.&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>Alpha of "Recipes with Backbone" Released</title>
    <link href="http://ngauthier.com/2011/10/alpha-of-recipes-with-backbone-released.html"/>
    <updated>2011-10-01T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2011/10/alpha-of-recipes-with-backbone-released</id>
    <content type="html">&lt;div class='post'&gt;
&lt;p&gt;Chris Strom and I have released the alpha of &lt;em&gt;Recipes with Backbone&lt;/em&gt;. It's an e-book containing intermediate to advanced design patterns and best practices for Backbone.js. Grab it now for 50% off the list price. You'll get future versions of the book for free when you buy the alpha.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;http://recipeswithbackbone.com&quot;&gt;http://recipeswithbackbone.com&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Thanks!&lt;/p&gt;&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>Using Exceptions to manage control flow in Rails Controllers</title>
    <link href="http://ngauthier.com/2011/09/using-exceptions-to-manage-control-flow.html"/>
    <updated>2011-09-26T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2011/09/using-exceptions-to-manage-control-flow</id>
    <content type="html">&lt;div class='post'&gt;
&lt;p&gt;Ah yes, the Rails Controller, a source of much contention among Rails developers. So many different ways to manage control flow, load objects, respond in standard and erroneous ways. My opinion up until recently was &quot;I'll just put a bunch of conditionals in there for different situations.&quot;&lt;/p&gt;&lt;p&gt;Recently, I've been working more on API endpoints and so responding with nice error messages has been more of a priority. I started using Exceptions more throughout my code thanks to &lt;a href=&quot;http://avdi.org/&quot;&gt;Avdi Grimm&lt;/a&gt;, and I recently wrote and action that I'm particularly proud of. Check it out:&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;# This controller's job is to exchange twitter credentials for Shortmail credentials&lt;br /&gt;class TwitterReverseAuthController &amp;lt; ApplicationController&lt;br /&gt;  # First, let's make our own subclass of RuntimeError&lt;br /&gt;  class Error &amp;lt; RuntimeError; end&lt;br /&gt;&lt;br /&gt;  def api_key_exchange&lt;br /&gt;    # Here are our required parameters. If any are missing we raise an error&lt;br /&gt;    screen_name = params.fetch(:screen_name) { raise Error.new('screen_name required')  }&lt;br /&gt;    token =       params.fetch(:oauth_token) { raise Error.new('oauth_token required')  }&lt;br /&gt;    secret =      params.fetch(:oauth_secret){ raise Error.new('oauth_secret required') }&lt;br /&gt;&lt;br /&gt;    # OK now let's authenticate that user. If we can't find a valid user, raise an error&lt;br /&gt;    @user = User.by_screen_name(screen_name).where(&lt;br /&gt;      :oauth_token =&amp;gt; token,&lt;br /&gt;      :oauth_secret =&amp;gt; secret&lt;br /&gt;    ).first or raise Error.new('user not found')&lt;br /&gt;&lt;br /&gt;    # Now we'll build a device. I'm not catching an exception on create! here because&lt;br /&gt;    # It should never fail. (I.e. a failure is actually a 500 because we don't expect it)&lt;br /&gt;    @device = Device.find_or_create_by_token!(&lt;br /&gt;      params.slice(:token, :description).merge(:user_id =&amp;gt; @user.id)&lt;br /&gt;    )&lt;br /&gt;&lt;br /&gt;    render :json =&amp;gt; { :api_key =&amp;gt; @device.api_key }&lt;br /&gt;&lt;br /&gt;  # Now I can simply catch any of my custom exceptions here&lt;br /&gt;  rescue Error =&amp;gt; e&lt;br /&gt;    # And render their message back to the user&lt;br /&gt;    render :json =&amp;gt; { :error =&amp;gt; e.message }, :status =&amp;gt; :unprocessable_entity&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Here are the things I really like about this solution:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;The happy path is really clear because there's no if/else branching&lt;/li&gt;&lt;li&gt;Errors are really obvious because I'm raising an exception (as opposed to &quot;else render json that complains&quot; which looks like a render which is not immediately apparent as a failure)&lt;/li&gt;&lt;li&gt;It's super easy to handle the errors in the same way. Instead of repeating the json render with a different message all throughout the method (i.e. it's DRY)&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;How's this look to you? How do you organize controller control flow?&lt;/p&gt;&lt;/div&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;div class='comments'&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Jim Gay&lt;/div&gt;
&lt;div class='content'&gt;
Interesting.&lt;br /&gt;But this will only catch one error at a time, so you&amp;#39;d return the result when the first raise is hit even if multiple parameters are missing.&lt;br /&gt;&lt;br /&gt;And Avdi points out that there is performance overhead with raising exceptions. Did you opt not to worry about that? Why not just collect an array of errors and test for their presence?&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
I think the performance overhead isn&amp;#39;t an issue here. I expect users only to get it wrong while they&amp;#39;re figuring it out. If this was on a form or something, then I&amp;#39;d raise an exception if the user is invalid, and I&amp;#39;d have all the params right there. But this is an API call, so it&amp;#39;s more of a &amp;quot;while I&amp;#39;m developing I get errors&amp;quot;.&lt;br /&gt;&lt;br /&gt;Also keep in mind it&amp;#39;s more performant the sooner I can bail out of processing the request :-)&lt;br /&gt;&lt;br /&gt;Collecting and returning all errors makes sense for fetching the params, but if I can&amp;#39;t find a user I can&amp;#39;t proceed with the rest of the call. So I have to stop execution anyways.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;codecraig&lt;/div&gt;
&lt;div class='content'&gt;
I&amp;#39;ve used a similar approach although I was a little bit more granular in the HTTP response codes. For example I&amp;#39;d send back a 404 if an entity was not found.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;james&lt;/div&gt;
&lt;div class='content'&gt;
- There&amp;#39;s too much going on this method.&lt;br /&gt;- From my limited reading of Avdi&amp;#39;s blog posts / presentation slides, I don&amp;#39;t feel that he would agree with using exceptions this way.&lt;br /&gt;- If you really want to subclass RuntimeError, I would choose a more descriptive name.&lt;br /&gt;&lt;br /&gt;An alternative: https://gist.github.com/1243758&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
@codecraig great point on the 404. Could be an additional subclass that has the status set.&lt;br /&gt;&lt;br /&gt;@james I&amp;#39;m looking up a user and creating a device. This is the minimum amount that can be done in a nested route on a create action. I disagree with your extraction because it will be only used in this single situation and obfuscates the method.&lt;br /&gt;&lt;br /&gt;I might make a User.authenticate_via_oauth(screen_name, token, secret) that returns nil or a user, but creating a separate class is overkill here IMO.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Avdi Grimm&lt;/div&gt;
&lt;div class='content'&gt;
Assorted thoughts...&lt;br /&gt;&lt;br /&gt;* So many wonderful fetches! My cup overflows.&lt;br /&gt;&lt;br /&gt;* Nice use of &amp;#39;or&amp;#39; as a statement modifier too, putting the error case last, where it belongs :-)&lt;br /&gt;&lt;br /&gt;* Maybe I&amp;#39;m missing something... why are you explicitly instantiating the exceptions? Why not &amp;#39;raise Error, &amp;quot;some message&amp;quot;&amp;#39;?&lt;br /&gt;&lt;br /&gt;* Because this is in an API endpoint, it makes sense to use exceptions liberally. We expect humans to make occasional mistakes. Conversely, we expect API clients to be fixed when they make mistakes, and then to never make that mistake again. We also generally don&amp;#39;t need to present &amp;quot;Here&amp;#39;s what you said, maybe you meant something else...&amp;quot; type feedback to robots, so we don&amp;#39;t need to worry about keeping context around that the exceptions might throw away.&lt;br /&gt;&lt;br /&gt;* As james pointed out, I do think there&amp;#39;s a lot going on in this method. E.g. I personally don&amp;#39;t think a #where() call has any business in a controller, and then you&amp;#39;ve got a #first on the end of that, which makes it a third-order digression into querying minutia.&lt;br /&gt;&lt;br /&gt;@Jim: Exception performance is not on the order to worry about in a case like this. It only becomes a worry inside tight loops. Here network latency is going to drown any latency the exceptions add.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
Forgot about &amp;quot;raise Error, &amp;quot;message&amp;quot;&amp;quot; :-)&lt;br /&gt;&lt;br /&gt;Yeah the &amp;quot;where&amp;quot; on user should be &amp;quot;User.authenticate_via_oauth(screen_name, token, secret) =&amp;gt; user or nil&amp;quot;&lt;br /&gt;&lt;br /&gt;Thanks for the feedback everyone. Glad to know the controller is still an interesting area to experiment with.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;bryanl&lt;/div&gt;
&lt;div class='content'&gt;
Why didn&amp;#39;t you just use a goto? It would be more explicit, and the exact same thing you are trying to accomplish here.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
Lack of self confidence.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Brian Cardarella&lt;/div&gt;
&lt;div class='content'&gt;
http://i.imgur.com/HDhaa.png&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Brian Cardarella&lt;/div&gt;
&lt;div class='content'&gt;
That was a reference to spaghetti code incase it was over anybody&amp;#39;s head.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
I made a gist:&lt;br /&gt;&lt;br /&gt;https://gist.github.com/1245259&lt;br /&gt;&lt;br /&gt;fork it!&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Brian Cardarella&lt;/div&gt;
&lt;div class='content'&gt;
Nick,&lt;br /&gt;&lt;br /&gt;https://gist.github.com/1245327&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
@Brian:&lt;br /&gt;&lt;br /&gt;https://gist.github.com/1245342&lt;br /&gt;&lt;br /&gt;your incorrect assumption is that every api call fails. When 1 per 1 million calls fail, exceptions are 3% slower, which is acceptable for readability purposed.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
I wanted to log this response post here for people reading the comments:&lt;br /&gt;&lt;br /&gt;http://www.enlightsolutions.com/articles/catch-all-exception-handling-is-not-flow-control/&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;rubiii&lt;/div&gt;
&lt;div class='content'&gt;
Nick, your solution is pretty interesting. Thanks for posting this.&lt;br /&gt;&lt;br /&gt;It feels like you&amp;#39;re using Exceptions for flow control. At least I don&amp;#39;t see missing parameters as an exceptional case. It&amp;#39;s possible and expected to happen. That&amp;#39;s why we test for it.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;rubiii&lt;/div&gt;
&lt;div class='content'&gt;
Ok, so now that I&amp;#39;ve actually read the title of your post ... ;) Using Exceptions for control flow feels like writing goto statements again?!&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Patrick&lt;/div&gt;
&lt;div class='content'&gt;
I just posted a &lt;a href=&quot;http://www.viget.com/extend/using-object-oriented-programming-to-manage-control-flow-in-rails-controlle/&quot; rel=&quot;nofollow&quot;&gt;deeper refactoring of this code&lt;/a&gt; and thought it might be of interest. I&amp;#39;m curious to get others&amp;#39; thoughts on this approach.&lt;br /&gt;&lt;br /&gt;Thanks.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
@Patrick thanks! You&amp;#39;re the third person to suggest a domain model as a solution. I like the idea of making the model encapsulate the multiple actions and have the controller simply perform the standard Create action on the domain model.&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>How I test EventMachine</title>
    <link href="http://ngauthier.com/2011/09/how-i-test-eventmachine.html"/>
    <updated>2011-09-20T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2011/09/how-i-test-eventmachine</id>
    <content type="html">&lt;div class='post'&gt;
&lt;p&gt;EventMachine's asynchronous and evented nature can be pretty tough to test. Here are some simple Test::Unit helpers I use along with a sample example:&lt;/p&gt;&lt;pre class='prettyprint'&gt;def eventmachine(timeout = 1)&lt;br /&gt;    Timeout::timeout(timeout) do&lt;br /&gt;      EM.run do&lt;br /&gt;        EM.epoll&lt;br /&gt;        yield&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;  rescue Timeout::Error&lt;br /&gt;    flunk 'Eventmachine was not stopped before the timeout expired'&lt;br /&gt;  end&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;This is a helper that runs eventmachine in a timeout so that if it hangs the test suite flunks out after a second. Very handy.&lt;/p&gt;&lt;pre class='prettyprint'&gt;def set_em_steps(*steps)&lt;br /&gt;    @@_em_steps = *steps&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def em_step_complete(step)&lt;br /&gt;    @@_em_steps.delete(step)&lt;br /&gt;    EM.stop if @@_em_steps.empty?&lt;br /&gt;  end&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;This is a flow-control helper to make sure I complete all the steps I expected. Sometimes you run two chunks of EM code and then make assertions in the callbacks. Generally, you call EM.stop in your last callback, but what if they don't chain one after another? Then you have to call stop after both have finished. These two helpers just make it so that I can define my steps, then mark each as completed. They stop EM once all the steps are completed.&lt;/p&gt;&lt;h3&gt;Example&lt;/h3&gt;&lt;p&gt;Here is an example test from Shortmail.com's test suite for iPhone push notifications:&lt;/p&gt;&lt;pre class='prettyprint'&gt;test 'send a push notification to the push daemon' do&lt;br /&gt;  token = Factory.next :iphone_device_token&lt;br /&gt;  message = 'hello world'&lt;br /&gt;  # define two steps that must be completed before stopping&lt;br /&gt;  set_em_steps :payload, :notification&lt;br /&gt;&lt;br /&gt;  # run the following code, but time out after 1 second&lt;br /&gt;  eventmachine do&lt;br /&gt;    # MockServer is a fake iphone push server (pretending to be apple) &lt;br /&gt;    # it yields responses back to the instantiator&lt;br /&gt;    Test::Helpers::PushD::MockServer.listen do |response|&lt;br /&gt;      # Unpack the push&lt;br /&gt;      id, exp, device, payload = PushD::Pusher.unpack(response)&lt;br /&gt;&lt;br /&gt;      # make sure that the payload has the right into in it&lt;br /&gt;      assert_equal token, device&lt;br /&gt;      assert_equal message, JSON.parse(payload)['aps']['alert']&lt;br /&gt;&lt;br /&gt;      # mark the payload step as complete, meaning we've received&lt;br /&gt;      # and verified it&lt;br /&gt;      em_step_complete :payload&lt;br /&gt;    end&lt;br /&gt;    PushD::WebServer.listen&lt;br /&gt;&lt;br /&gt;    # This is another part of code under test.&lt;br /&gt;    # This is how we send a push message&lt;br /&gt;    PushNotifier.notify(token, :message =&gt; message) do |success|&lt;br /&gt;      # When the push message is sent it runs the callback block with&lt;br /&gt;      # a boolean and we ensure it's ok&lt;br /&gt;      assert success&lt;br /&gt;      # now make sure that this step is marked as finished&lt;br /&gt;      em_step_complete :notification&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Now, we can be sure our assertions are run, or it will time out because it won't stop.&lt;/p&gt;&lt;p&gt;How do you test eventmachine?&lt;/p&gt;&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>Backbone JS: View signatures to prevent repaints</title>
    <link href="http://ngauthier.com/2011/03/backbone-js-view-signatures-to-prevent.html"/>
    <updated>2011-03-10T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2011/03/backbone-js-view-signatures-to-prevent</id>
    <content type="html">&lt;div class='post'&gt;
&lt;p&gt;A nice thing about backbone is being able to bind a view render to new data. But sometimes you get new data, but it's not actually new, it's the same data that has not been updated. This will still cause the view to repaint because the event will fire.&lt;/p&gt;&lt;p&gt;To combat this, I've started putting signatures on my views.&lt;/p&gt;&lt;p&gt;In the initializer for the view:&lt;/p&gt;&lt;pre class='prettyprint'&gt;this.signature = &quot;&quot;;&lt;/pre&gt;&lt;p&gt;Then in the render method, I do a reduction on the data that drives the view and compare signatures and decide to paint or not:&lt;/p&gt;&lt;pre class='prettyprint'&gt;&lt;br /&gt;// Create a signature from the &quot;Posts&quot; that this view renders&lt;br /&gt;var new_signature = _.reduce(posts, function(memo, post) {&lt;br /&gt;  // Store the id and number of comments. This represents what a&lt;br /&gt;  // &quot;changed&quot; post is for the view&lt;br /&gt;  memo.push([post.get('id'), post.get('num_comments')].join(','));&lt;br /&gt;  return memo;&lt;br /&gt;}, []).join('|'); // joined with pipes for each post&lt;br /&gt;&lt;br /&gt;// If the signature is the same, end the render&lt;br /&gt;if (new_signature === this.signature) {&lt;br /&gt;  this.signature = new_signature;&lt;br /&gt;  return;&lt;br /&gt;}&lt;br /&gt;// Otherwise store the signature&lt;br /&gt;this.signature = new_signature;&lt;br /&gt;// Your view code down here&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;This is essentially caching with a custom cache key. Except instead of retrieving a cached value, we leave the dom as-is. This cuts down on repaint &quot;flickering&quot;.&lt;/p&gt;&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>jQuery Deferred and Backbone JS</title>
    <link href="http://ngauthier.com/2011/03/jquery-deferred-and-backbone-js.html"/>
    <updated>2011-03-09T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2011/03/jquery-deferred-and-backbone-js</id>
    <content type="html">&lt;div class='post'&gt;
&lt;p&gt;Backbone is a really interesting framework, and my favorite part so far is the following idea:&lt;/p&gt;&lt;blockquote&gt;If you use a callback, you're Doing It Wrong&lt;/blockquote&gt;&lt;p&gt;This has held true for me for my development with Backbone so far. When you make &lt;b&gt;data&lt;/b&gt; calls to the server, you let the appropriate events notify interested parties when objects are changed or updated or refreshed.&lt;/p&gt;&lt;p&gt;However, with non-data operations, callbacks can be really useful. Today, I needed to animate an object, using jQuery's slideUp. I wanted the slideUp to go hand-in-hand with a deletion of an object. Because slideUp is asynchronous, and the deletion action is asynchronous, I needed a callback to synchronize them. The reason I couldn't do them simultaneously is that when an object is deleted, many view elements refresh themselves, and if the slideUp wasn't finish the dom refreshing would interrupt the slideUp and it looked gross.&lt;/p&gt;&lt;p&gt;So, I need a callback on slideUp to call remove. Here arose an &lt;a href=&quot;http://en.wikipedia.org/wiki/Single_responsibility_principle&quot;&gt;SRP&lt;/a&gt; problem: the view should not concern itself with the removal of the model from the collection. One solution is for the view's removal method to take a callback and pass it along to slideUp. But I wanted something more flexible. Enter jQuery Deferred.&lt;/p&gt;&lt;p&gt;Deferred objects let you &lt;i&gt;chain callbacks&lt;/i&gt; and &lt;i&gt;return promises as objects&lt;/i&gt;. For you Rails readers, &lt;b&gt;imagine AREL had a hot sister written in Javascript that was into AJAX&lt;/b&gt;.&lt;/p&gt;&lt;p&gt;So here is my view method that runs slideUp and returns a deferred object:&lt;/p&gt;&lt;pre class='prettyprint'&gt;&lt;br /&gt;return $(this.el).slideUp(200).promise().done(&lt;br /&gt;  _.bind(function() { this.remove(); }, this&lt;br /&gt;);&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Now when we archive and email, we want to remove the dom element by sliding, then we want to tell the email model to archive itself. Here is the archive method:&lt;/p&gt;&lt;pre class='prettyprint'&gt;&lt;br /&gt;this.remove().then(this.model.archive);&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Pretty straightforward. We call remove (the previous method) then we tell the model to archive itself. This method is bound to the click event on the archive button using Backbone's view event binding methods. When the model archives itself, Backbone events automatically fire, so other Views can listen for &quot;change&quot; and &quot;remove&quot; to update their elements.&lt;/p&gt;&lt;p&gt;EDIT: changed code reflecting Julian's comments.&lt;/p&gt;&lt;/div&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;div class='comments'&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Julian&lt;/div&gt;
&lt;div class='content'&gt;
Using jQuery 1.6, you can considerably simplify your method:&lt;br /&gt;&lt;br /&gt;remove: function() {&lt;br /&gt;return&lt;br /&gt;$(this.el)&lt;br /&gt;.slideUp(200)&lt;br /&gt;.promise()&lt;br /&gt;.done(function() { this.remove(); });&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;1.6 adds jQuery.fn.promise() that returns a Promise to observe when a collection has no more animation going on. It&amp;#39;s resolved with the collection is was called on as its context and first &amp;amp; only argument.&lt;br /&gt;&lt;br /&gt;(sorry for how the code is formatted, Blogger&amp;#39;s comments just plain suck :/)&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
Cool! Yeah I noticed slideUp didn&amp;#39;t return a promise, so I didn&amp;#39;t know what to do with it.&lt;br /&gt;&lt;br /&gt;I think I&amp;#39;d still need the _.bind within the done to bind to the object though, right?&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>Backbone and Rails Forgery Protection</title>
    <link href="http://ngauthier.com/2011/02/backbone-and-rails-forgery-protection.html"/>
    <updated>2011-02-21T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2011/02/backbone-and-rails-forgery-protection</id>
    <content type="html">&lt;div class='post'&gt;
&lt;p&gt;I just had a tough time getting Rails 3 to play nice with Backbone JS, and it turned out to be a simple problem with a simple solution. Backbone was not sending the csrf authenticity token embedded in the page when it sent create/update/delete requests, and Rails was destroying the session when it detected the invalid request.&lt;/p&gt;&lt;p&gt;Here is all the javascript it took to get Backbone to include the token with all requests:&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;br /&gt;/* alias away the sync method */&lt;br /&gt;Backbone._sync = Backbone.sync;&lt;br /&gt;&lt;br /&gt;/* define a new sync method */&lt;br /&gt;Backbone.sync = function(method, model, success, error) {&lt;br /&gt;  /* only need a token for non-get requests */&lt;br /&gt;  if (method == 'create' || method == 'update' || method == 'delete') {&lt;br /&gt;    /* grab the token from the meta tag rails embeds */&lt;br /&gt;    var auth_options = {};&lt;br /&gt;    auth_options[$(&quot;meta[name='csrf-param']&quot;).attr('content')] =&lt;br /&gt;                 $(&quot;meta[name='csrf-token']&quot;).attr('content');&lt;br /&gt;    /* set it as a model attribute without triggering events */&lt;br /&gt;    model.set(auth_options, {silent: true});&lt;br /&gt;  }&lt;br /&gt;  /* proxy the call to the old sync method */&lt;br /&gt;  return Backbone._sync(method, model, success, error);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Note that this depends on the meta tags being present, which require you to call the helper &quot;csrf_meta_tag&quot; in your rails view for the page (put it in the head).&lt;/p&gt;&lt;/div&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;div class='comments'&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;rubiii&lt;/div&gt;
&lt;div class='content'&gt;
i&amp;#39;d love to hear more about using backbone with rails. i really like backbone, but to me it still feels like i have to write &amp;quot;a lot&amp;quot; of additional code. routes, models and validations for example.&lt;br /&gt;&lt;br /&gt;i&amp;#39;m hacking on retrieving these things from rails, but maybe there&amp;#39;s a better way to do this?!&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
I&amp;#39;m going to put together something larger. It may fit in a blog post, but probably not. It may be a talk, I&amp;#39;m not sure yet.&lt;br /&gt;&lt;br /&gt;I don&amp;#39;t want to do a tutorial. For me, that&amp;#39;s not very interesting. I want to write about backbone &amp;quot;6 months in&amp;quot; because that&amp;#39;s where I think it will really shine.&lt;br /&gt;&lt;br /&gt;So far, my initial impressions are that the code you write on the front end is code that you don&amp;#39;t have to write on the back (especially crazy rails view code).&lt;br /&gt;&lt;br /&gt;The most amazing part so far has been that if you wire everything up right by embracing event-driven coding, changes cascade to all the right places automatically. That is *huge* for &amp;quot;6 months in&amp;quot; when you can&amp;#39;t afford to update an ajax call in 24 places when you change a template.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;rubiii&lt;/div&gt;
&lt;div class='content'&gt;
got it. i also love the evented part of backbone!&lt;br /&gt;&lt;br /&gt;so how do you do templating? do you load templates upfront (via something like jammit) and then request json data, do you load the templates and the json and rely on caching or do you have rails render the template and retrieve the complete template?&lt;br /&gt;&lt;br /&gt;also, did you run any metrics comparing the performance of your app with and without backbone?&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
jammit + underscore templates + json api.&lt;br /&gt;&lt;br /&gt;Benchmarks are tough because it depends heavily on many factors. However, I can tell you that a specifically heavy page went from 10s just for the Rails request, to 0.6s according to chrome&amp;#39;s load time. So, speed improvements are massive.&lt;br /&gt;&lt;br /&gt;Also, the user&amp;#39;s subjective speed is even higher, because we can manipulate elements on the front-end while doing an asynchronous call behind the scenes. So everything is instant :-)&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Maciej Adwent&lt;/div&gt;
&lt;div class='content'&gt;
Heya Nick,&lt;br /&gt;&lt;br /&gt;Thanks for this code, it really cleared up some initial confusion for me.&lt;br /&gt;&lt;br /&gt;I&amp;#39;ve wrapped your code up in a little github project:&lt;br /&gt;&lt;br /&gt;https://github.com/Maciek416/BackboneRailsAuthTokenAdapter&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
awesome! Thanks for packaging it up nicely!&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;vijaydev&lt;/div&gt;
&lt;div class='content'&gt;
Thanks a lot!&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>View Abstraction in Integration Tests</title>
    <link href="http://ngauthier.com/2011/02/view-abstraction-in-integration-tests_05.html"/>
    <updated>2011-02-05T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2011/02/view-abstraction-in-integration-tests_05</id>
    <content type="html">&lt;div class='post'&gt;
&lt;h5&gt;Goal: Make integration tests drier by adding a view abstraction layer&lt;/h5&gt;&lt;p&gt;Ruby on Rails has a bunch of popular of test frameworks, such as:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;RSpec&lt;/li&gt;&lt;li&gt;Cucumber&lt;/li&gt;&lt;li&gt;Test::Unit&lt;/li&gt;&lt;li&gt;Steak&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;But one common aspect to all of the frameworks, out of the box, is that they're very procedural. Cucumber is designed so that each scenario has a set of steps. There is a single, global, collection of steps. RSpec is global by nature, there are no test classes, just describe blocks.&lt;/p&gt;&lt;p&gt;There is no doubt in my mind that these frameworks have made testing easier by adding lots of common actions, and allowing you to define your own common actions.&lt;/p&gt;&lt;p&gt;However, there is one thing that I don't see much of in tests: &lt;b&gt;Object-Oriented Patterns&lt;/b&gt;. Most of us use the Factory pattern through a variety of gems. Internally, many frameworks use the Visitor pattern to execute the tests. But that's all I've ever seen (disclaimer: I am young, and have much to learn).&lt;/p&gt;&lt;p&gt;Here are some pain points I've felt while writing integration tests in the past:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Hard to reference objects throughout Cucumber scenarios. Often resulting in global variables used between steps&lt;/li&gt;&lt;li&gt;Cumbersome to check the view for expected output, often resulting in lots of css selectors&lt;/li&gt;&lt;li&gt;Brittleness introduced by coding html and css structure into test code that prevents refactoring the view&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;So, I recently had to write some integration tests from scratch, and I decided to do something different. I decided to implement the &lt;a href=&quot;http://en.wikipedia.org/wiki/Bridge_pattern&quot;&gt;Bridge Pattern&lt;/a&gt; in my integration tests. I was confident enough in the solution that I decided to just use Test::Unit and Capybara to write my test code.&lt;/p&gt;&lt;p&gt;One of the major goals of this implementation is to &lt;b&gt;make it easy to interact with the UI and objects within it&lt;/b&gt;. I think it's time I show some code.&lt;/p&gt;&lt;h5&gt;Post Test for a simple blog site&lt;/h5&gt;&lt;pre class=&quot;prettyprint&quot;&gt;# Given I am on the posts page&lt;br /&gt;visit posts_path&lt;br /&gt;# When I create a new post&lt;br /&gt;click_link 'New Post'&lt;br /&gt;View::Post.create(&lt;br /&gt;  :title =&gt; 'View abstraction in integration tests',&lt;br /&gt;  :body =&gt; 'We must go deeper'&lt;br /&gt;)&lt;br /&gt;# Then I should see a success message&lt;br /&gt;assert_see 'Successfully created post.'&lt;br /&gt;# When I visit the posts index&lt;br /&gt;visit posts_path&lt;br /&gt;# Then I should see one post&lt;br /&gt;assert_equal 1, View::Post.all.size&lt;br /&gt;# And it should have the correct title&lt;br /&gt;assert_equal 'View abstraction in integration tests',&lt;br /&gt;             View::Post.all.first.title&lt;br /&gt;# And it should have the correct body&lt;br /&gt;assert_equal 'We must go deeper', View::Post.all.first.body&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Let's take a look at a few interesting things:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;I'm directly using Capybara's dsl to navigate&lt;/li&gt;&lt;li&gt;When I create a post, I'm using a View module so that it won't use the ActiveRecord object&lt;/li&gt;&lt;li&gt;When I create a post, I pass in a hash of the fields I'd like to fill in&lt;/li&gt;&lt;li&gt;When I check to see if the post is created, I'm using methods on View::Post that return ruby objects, like an array, and that instances of View::Post have methods like &quot;title&quot; and &quot;body&quot;&lt;/li&gt;&lt;li&gt;There are no css selectors or html, but I do have button test present&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;OK, hopefully that piqued your interest. Let's look at some of the implementation. First, let's check out the base View module and a barebones implementation of View::Post:&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;module View&lt;br /&gt;  def self.body&lt;br /&gt;    Nokogiri::HTML(Capybara.current_session.body)&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  class Abstract&lt;br /&gt;    # Access capybara dsl in the view helper classes too&lt;br /&gt;    include Capybara&lt;br /&gt;    extend  Capybara&lt;br /&gt;&lt;br /&gt;    def initialize(node)&lt;br /&gt;      @id = node['id']&lt;br /&gt;    end&lt;br /&gt;    def self.all&lt;br /&gt;      nodes.map{|node| new(node) }&lt;br /&gt;    end&lt;br /&gt;    private&lt;br /&gt;    def id&lt;br /&gt;      %{##{@id}}&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;  class Post &lt; View::Abstract&lt;br /&gt;    attr_reader :title&lt;br /&gt;    attr_reader :body&lt;br /&gt;    def initialize(node)&lt;br /&gt;      super&lt;br /&gt;      @title = node.css('.title').first.text.strip&lt;br /&gt;      @body = node.css('.body').first.text.strip&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;    private&lt;br /&gt;    def self.nodes&lt;br /&gt;      View.body.css('.post')&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;OK what's going on here? Let me step you through it:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;When I call View::Post.all, that calls View::Abstract.all, which iterates over View::Post.nodes and builds instances of View::Post&lt;/li&gt;&lt;li&gt;View::Post.nodes runs Capybara's current page through Nokogiri, then selects all the HTML nodes with the class &quot;post&quot;&lt;/li&gt;&lt;li&gt;When a View::Post is initialized, it uses Nokogiri to set attributes on itself, from the view. Like title and body&lt;/li&gt;&lt;li&gt;View::Abstract always stores an object's dom id as @id so that it can be used internally, which we'll see next.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Now lets take a look at how View::Post.create works:&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;module View&lt;br /&gt;  class Post&lt;br /&gt;    def self.create(opts = Hash.new(''))&lt;br /&gt;      fill_form opts&lt;br /&gt;      click_button 'Create Post'&lt;br /&gt;    end&lt;br /&gt;    def self.fill_form(opts)&lt;br /&gt;      fill_in 'Title', :with =&gt; opts[:title]&lt;br /&gt;      fill_in 'Body', :with =&gt; opts[:body]&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Here we show how the class method uses capybara to take care of filling in the form for us. Now, if we change how our forms are rendered, we can change them in one place. Nice and DRY.&lt;/p&gt;&lt;p&gt;Let's look at one of the biggest pain points for me in cucumber: deleting an object in a list of objects. Why is this a pain point? I usually have to write a custom step like &quot;When I delete the Post 'My Post'&quot;, which will use dom_id to find the id of a Post object found in the DB with the title &quot;My Post&quot;. I find this really roundabout, because you don't need to look in the database for an object to figure out its dom id. It's right there in the view. Any competent internet user would be able to click on the &quot;Delete&quot; button for the post called &quot;My Post&quot; if you showed them the page in a browser. Here is the test code:&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;# Given I made two blog posts&lt;br /&gt;2.times do |i|&lt;br /&gt;  visit posts_path&lt;br /&gt;  click_link 'New Post'&lt;br /&gt;  View::Post.create(&lt;br /&gt;    :title =&gt; &quot;Post #{i}&quot;,&lt;br /&gt;    :body =&gt; &quot;Body for #{i}&quot;&lt;br /&gt;  )&lt;br /&gt;end&lt;br /&gt;# When I go to the posts path&lt;br /&gt;visit posts_path&lt;br /&gt;# Then I should see two posts&lt;br /&gt;assert_equal 2, View::Post.all.size&lt;br /&gt;# When I delete Post 0&lt;br /&gt;View::Post.find_by_title('Post 0').delete&lt;br /&gt;# Then I should see one post&lt;br /&gt;assert_equal 1, View::Post.all.size&lt;br /&gt;# And I should not see Post 0&lt;br /&gt;assert_nil View::Post.find_by_title('Post 0')&lt;br /&gt;# And I should see Post 1&lt;br /&gt;refute_nil View::Post.find_by_title('Post 1')&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Notice specifically the line where the post is deleted. I grabbed the instance of View::Post corresponding to the title I wanted and called .delete on it. Then I thoroughly check that the correct post was removed. Here is the implementation:&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;module View&lt;br /&gt;  class Post&lt;br /&gt;    def delete&lt;br /&gt;      within(id) { click_button 'Delete' }&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Expecting more? In View::Abstract we defined the method &quot;id&quot; which returns the dom id of the object which was stored when we initialized it. I simply told capybara to click &quot;Delete&quot; inside that node's div. This was the &quot;eureka moment&quot; for me. Something that is frustrating and difficult in other styles of testing is just plain simple with this pattern.&lt;/p&gt;&lt;p&gt;There is a &lt;i&gt;lot&lt;/i&gt; more than can be done here, and I'm just scratching the surface. If you'd like to try it out for yourself, I've created a Rails project with this environment setup on github: &lt;a href=&quot;https://github.com/ngauthier/view-abstraction-demo&quot;&gt;View Abstraction Demo&lt;/a&gt;. Here's how to use it:&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;git clone git://github.com/ngauthier/view-abstraction-demo.git&lt;br /&gt;cd view-abstraction-demo&lt;br /&gt;bundle&lt;br /&gt;rake&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Note: you must use ruby 1.9.2. Important files to look at are &quot;test/test_helper.rb&quot; and &quot;test/integration/post_test.rb&quot;.&lt;/p&gt;&lt;/div&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;div class='comments'&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Jakub&lt;/div&gt;
&lt;div class='content'&gt;
I am sure your idea is gonna turn into a gem. It just fits so well in a view testing pattern and adds performance to it also. I don&amp;#39;t fancy Cucumber, use Steak, but still I Repeat Myself with # and . so unql.&lt;br /&gt;&lt;br /&gt;Gem would be nice. Generating test/views/abstract.rb and test/views/abstract/model.rb - so nice to modify you know. I&amp;#39;m looking forward to help out with gem development. Wish you luck.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
Hey Jakub, glad you liked the post.&lt;br /&gt;&lt;br /&gt;I don&amp;#39;t think this would make a good gem, because only about 20 lines would be packaged. The generator would create very bare files because it would have no understanding of your css structure.&lt;br /&gt;&lt;br /&gt;Also, I&amp;#39;ve found that UI elements don&amp;#39;t always map 1:1 with database elements.&lt;br /&gt;&lt;br /&gt;Lastly, I find that the power of this pattern is simple and can be included directly in your code. Putting it in a gem would make it hard to change it on a project-by-project basis. I expect to add more helpful methods to abstract as I use this more.&lt;br /&gt;&lt;br /&gt;Thanks,&lt;br /&gt;Nick&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Jakub&lt;/div&gt;
&lt;div class='content'&gt;
Thanks for the answer Nick! You can be right, maybe it&amp;#39;s too much for a gem, however having that in a generator could be a trick. &lt;br /&gt;&lt;br /&gt;There is no need for the gem to understand css nor thoughtlessly map db - it can generate some conventional files that can be easily modified to fit the view. Actually, modifying those files would be a first step of a view specification!&lt;br /&gt;&lt;br /&gt;The thing about that pattern is, for me, that those methods should not be stuffed in helpers (or additional spec/test methods) which is usually done. And to not forget that, the gem hooked to a initializer would be nice.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
yeah, I think moving them to separate files is definitely a cleaner way of doing it. Feel free to make a gem / plugin with generators to make it easier for yourself.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Corey Haines&lt;/div&gt;
&lt;div class='content'&gt;
Hi, Nick,&lt;br /&gt;Good thoughts.&lt;br /&gt;This looks similar to the page object pattern that a lot of people are using these days in Watir and Selenium tests. Have you looked at that? It could help influence your stuff, hopefully guide you past any dark corners they&amp;#39;ve already dealt with.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
Thanks Corey, that&amp;#39;s exactly what I&amp;#39;m trying to do. I figured there was no way I could be the first person to think of this :-)&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
@Jakub&lt;br /&gt;&lt;br /&gt;I&amp;#39;ve been adding more functionality, and it seems like you&amp;#39;re right and it would make a nice gem. Mostly to make it easier to define selectors and attributes, and make a bunch of convenience methods (like the enumerable methods).&lt;br /&gt;&lt;br /&gt;Also, I am planning on bundling some assertions with the gem, which will take advantage of capybara&amp;#39;s automatic delay on failed assertions. I&amp;#39;ll post on this blog soon when it is released.&lt;br /&gt;&lt;br /&gt;-Nick&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
This has been released as a Gem, and the syntax is changed a bit:&lt;br /&gt;&lt;br /&gt;https://github.com/ngauthier/domino&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>My Workflow</title>
    <link href="http://ngauthier.com/2011/01/my-workflow.html"/>
    <updated>2011-01-07T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2011/01/my-workflow</id>
    <content type="html">&lt;div class='post'&gt;
&lt;p&gt;Stemming from a workflow discussion on twitter featuring &lt;a href=&quot;http://twitter.com/bryanl&quot;&gt;@bryanl&lt;/a&gt;, &lt;a href=&quot;http://twitter.com/eee_c&quot;&gt;@eee_c&lt;/a&gt;, &lt;a href=&quot;http://twitter.com/pjb3&quot;&gt;@pjb3&lt;/a&gt;, &lt;a href=&quot;http://twitter.com/stevenhaddox&quot;&gt;@stevenhaddox&lt;/a&gt;, and &lt;a href=&quot;http://twitter.com/webandy&quot;&gt;@webandy&lt;/a&gt;, I decided to share my workflow. Originally, we were talking about Mac Apps (specifically the paid ones), but that turned into &quot;how do you work&quot;. Here are my goals for a good workflow:&lt;/p&gt;&lt;h2&gt;Goals&lt;/h2&gt;&lt;ol&gt;&lt;li&gt;Easily navigate applications and contexts&lt;/li&gt;&lt;li&gt;Minimize distraction&lt;/li&gt;&lt;li&gt;Maximize focus&lt;/li&gt;&lt;li&gt;Get work done&lt;/li&gt;&lt;/ol&gt;&lt;h2&gt;Easily navigate applications and contexts&lt;/h2&gt;&lt;p&gt;I need to be able to quickly get to certain applications in order to maximize productivity. I want to be able to swap to a browser, terminal, editor, or other application in &lt;strong&gt;under a second&lt;/strong&gt;. The mouse won't cut it, I need keyboard shortcuts.&lt;/p&gt;&lt;p&gt;My solution here is &lt;strong&gt;Alt-Tab&lt;/strong&gt;. One of the oldest and most basic ways of switching apps. Alt-Tab is very fast for me because &lt;strong&gt;95% of the time I have 3 windows open&lt;/strong&gt; on any given workspace (OS X read: spaces). This means that Alt-Tab goes back to the previous window, and Alt-Tab-Tab goes to the alternative window.&lt;/p&gt;&lt;h2&gt;Minimize distraction&lt;/h2&gt;&lt;p&gt;I layout my workspaces in a 2x2 layout. Here is what I put on each window:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;[1,1] Chrome holding &quot;distracting&quot; sites like gmail, twitter, campfire, pivotal, etc&lt;/li&gt;&lt;li&gt;[1,2] one Vim, one Terminal, one Chrome with only development related websites open&lt;/li&gt;&lt;li&gt;[2,1] passive applications. Usually Xvfb and Rhythmbox. I don't go here often&lt;/li&gt;&lt;li&gt;[2,2] alternative dev context. Same as [1,2] but for a different project. This is only up occasionally. Sometimes I use it for transferring files to remote servers.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;I spend 99% of my work day in [1,1] and [1,2].&lt;/p&gt;&lt;p&gt;&lt;strong&gt;I disable all notifications&lt;/strong&gt;. Nothing pops up. Nothing makes noise. Nothing &quot;pulses&quot; in the taskbar. Nothing. My phone is on vibrate and no apps on it make notifications except calls and texts. No one ever needs your attention immediately in gmail or campfire or twitter or pivotal or basecamp. When I am at a solid stopping point in my real work (30m to 2h in between) I go check all my distraction tabs. If the server is really on fire, someone will call my phone.&lt;/p&gt;&lt;h2&gt;Maximize focus&lt;/h2&gt;&lt;p&gt;This is a combination of the previous two, plus &lt;strong&gt;I always maximize my windows&lt;/strong&gt; so I'm only looking at one thing at a time. No distractions so nothing gets in my face while I'm working. Many people like putting up a terminal next to their editor, but they usually end up alt-tabbing anyways. I prefer larger windows so I can have more vim splits (usually 3x3 on each tab) and more terminal output.&lt;/p&gt;&lt;h2&gt;Applications&lt;/h2&gt;&lt;p&gt;This last section is in response to our twitter debate about paid mac apps. I'm on linux, so I have no access to any of those apps. Let's start with the apps I spend the most time in:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Edit code: &lt;strong&gt;Vim&lt;/strong&gt;&lt;/li&gt;&lt;li&gt;Run tests, servers, and other commands: &lt;strong&gt;gnome-terminal&lt;/strong&gt;&lt;/li&gt;&lt;li&gt;Web browser: &lt;strong&gt;Google Chrome&lt;/strong&gt;&lt;/li&gt;&lt;li&gt;File browsing and remote FS management: &lt;strong&gt;nautilus w/ gvfs&lt;/strong&gt;&lt;/li&gt;&lt;li&gt;Administer databases: &lt;strong&gt;mysql&lt;/strong&gt; or &lt;strong&gt;psql&lt;/strong&gt; console&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;That is where I spend the majority of my day. There are very few alternatives to the above applications that aren't very similar. Everyone has a browser and a terminal. Editors is an entirely different can of worms, so I won't get into that here. Some people use GUIs for DBs, but I prefer the console. I learned SQL before I did web development, so it's more natural for me. And if it's too hard, I write a test :-).&lt;/p&gt;&lt;p&gt;There are many excellent command line applications at your fingertips that I use through my terminal. Apps like git, grep, find, screen, top, ps, kill, and thousands of others. Learning the command line root of the application is usually more productive than a gui that was built on top of the command line application. The only exception I've found is when I need something shown to me graphically, like a pdf. I like to avoid the mouse, so the terminal is my friend.&lt;/p&gt;&lt;p&gt;Here are a bunch of Mac Apps that a couple of people brought up during our twitter discussion:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;mailplane&lt;/li&gt;&lt;li&gt;echofon&lt;/li&gt;&lt;li&gt;divvy&lt;/li&gt;&lt;li&gt;propane&lt;/li&gt;&lt;li&gt;alfredapp&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;I think it's a nice small selection of apps that illustrate the differences in my workflow from many other developers. Mailplane, echofon, and propane are for Gmail, Twitter, and Campfire. I try to ignore those applications as much as possible. Ideally, I want to spend &lt;i&gt;less&lt;/i&gt; time in those apps in order to get more done.&lt;/p&gt;&lt;p&gt;Divvy and Alfredapp are all about launching and organizing applications. I have three applications in three windows. Vim manages its own splits and tabs. In my terminal, screen or tabs works. In the browser, I use tabs. Everything is maximized to improve focus.&lt;/p&gt;&lt;p&gt;What it really boils down to, though, is that I don't &lt;i&gt;do&lt;/i&gt; a lot of stuff during the work day. I write code. I avoid anything that is not essential to writing code. I &lt;i&gt;want&lt;/i&gt; less applications and I like having my life &quot;in the cloud&quot; so I don't have to install a lot of stuff on a new computer. My knee jerk reaction to new applications is not &quot;oooh shiny&quot;, it's &quot;I don't need that&quot;. Another really nice thing about this workflow is that it's scalable. I've worked from 1024x768 to 2560x1600, and it always makes optimal use of screen real estate. When I swap to my netbook, I don't feel cramped, I just open more tabs.&lt;/p&gt;&lt;h2&gt;Join the discussion&lt;/h2&gt;&lt;p&gt;Please post comments about the applications you use that I haven't addressed. I'll try to reply to everyone about how I handle different scenarios. Most of the time, my response will be &quot;I try to avoid that because I'm trying to write code here!&quot;&lt;/p&gt;&lt;/div&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;div class='comments'&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;pjb3&lt;/div&gt;
&lt;div class='content'&gt;
A couple of GUI tools I prefer over command line:&lt;br /&gt;&lt;br /&gt;* GitX&lt;br /&gt;&lt;br /&gt;I find it easier to review diffs in GitX than diff at the command line.  Also easy to unstage unwanted changes before commiting&lt;br /&gt;&lt;br /&gt;* Rubymine&lt;br /&gt;&lt;br /&gt;Hard to explain this.  I&amp;#39;m planning on doing a screencast soon to show how I work in Rubymine.  I find it more efficient than vim + command line or emacs.&lt;br /&gt;&lt;br /&gt;* Querious&lt;br /&gt;&lt;br /&gt;I&amp;#39;m fine with writing SQL on the command line, but viewing the results, esp. when you have large columns and/or large tables, sucks.  A GUI fits things in tabs, windows and grids nicely.&lt;br /&gt;&lt;br /&gt;I agree with you about the mouse.  As much as possible, I&amp;#39;m trying to have keyboard shortcuts for all common operations.&lt;br /&gt;&lt;br /&gt;As for distractions, depends on the project you are working on.  If you are working on a project by yourself, &amp;quot;leave me alone I&amp;#39;m coding&amp;quot; works really well.  If you have many devs working on the same code base, near real-time communication is important.  It&amp;#39;s a balance though.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Bill Mill&lt;/div&gt;
&lt;div class='content'&gt;
pjb, check out dbext for viewing the results of queries in Vim. If you&amp;#39;re a vimmer, it&amp;#39;s a godsend.&lt;br /&gt;&lt;br /&gt;Also, my workflow is nearly exactly the same as yours, but on OS X. iTerm2 is as good as Linux terminals.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;bryanl&lt;/div&gt;
&lt;div class='content'&gt;
Since it appears you are critiquing that apps that I posted earlier, I now feel the need to reply.&lt;br /&gt;&lt;br /&gt;Having unique apps which do their jobs really well is the key to helping me focus.  The web browser is a lot of things to many people, but it most definitely isn&amp;#39;t the end-all-be-all.  I actually prefer to have as few browser tabs open as possible.  There is nothing more frustrating to me than seeing all the wasted screen space wasted by tabs.  &lt;br /&gt;&lt;br /&gt;Workflows don&amp;#39;t have to be dead simple to be scalable.  I work on a 11.6&amp;quot; macbook air, a 15&amp;quot; macbook pro and a 27&amp;quot; imac, and I pretty much have the same configurations on all three workstations.  I don&amp;#39;t believe in external monitors, and as you know, the keyboard is most definitely the place to be.&lt;br /&gt;&lt;br /&gt;For instance: I use mailplane, so I can have easy access to multiple gmail accounts.  Sure the web browser works fine, but it doesn&amp;#39;t easily scale past one account if you would like to check multiple ones easily.&lt;br /&gt;&lt;br /&gt;You hack code 100% of the time.  What you describe is ample for a person in that situation.  My day is filled with much than just hacking on code, so tool sets will differ.  No problems with that.  There isn&amp;#39;t one true way.  The only thing you really need to work on is constant refinement on your path to happiness.&lt;br /&gt;&lt;br /&gt;My work here is done.  I&amp;#39;ve inspired yet another blog post ;-)  I&amp;#39;ll wait for you to troll me again another day.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
@pjb3&lt;br /&gt;&lt;br /&gt;I use git-gui from time to time to review a large commit.&lt;br /&gt;&lt;br /&gt;I&amp;#39;d like to see a rubymine screencast. The few times I&amp;#39;ve seen it I didn&amp;#39;t see any advanced features. The &amp;quot;mining&amp;quot; that I saw looked the same as ctags.&lt;br /&gt;&lt;br /&gt;As for the sql gui, I tend to write a test when stuff gets pretty complex. psql&amp;#39;s console automatically pipes output to &amp;quot;less&amp;quot; so it&amp;#39;s pretty easy to read.&lt;br /&gt;&lt;br /&gt;Some projects I pay more attention to campfire, but it&amp;#39;s never in realtime. If we really need a real time discussion, it&amp;#39;s time for a phone call or a face-to-face.&lt;br /&gt;&lt;br /&gt;@bryanl&lt;br /&gt;&lt;br /&gt;I didn&amp;#39;t mean for it to come off as a critique. I was trying to explain why I don&amp;#39;t buy those apps, not &amp;quot;these apps suck because you could just do it this way&amp;quot;.&lt;br /&gt;&lt;br /&gt;I am pretty OCD about keeping a tidy environment, and I close tabs a lot while I browse.&lt;br /&gt;&lt;br /&gt;I like the &amp;quot;single monitor&amp;quot; approach too. I was on a 24&amp;quot; for a long time, then I added a 20&amp;quot; that, but recently ditched both for a 30&amp;quot;@2560x1600.&lt;br /&gt;&lt;br /&gt;@mailplane I only have one account. I could see needing this if I had more than one.&lt;br /&gt;&lt;br /&gt;It&amp;#39;s definitely a 100% hacker setup. If I had to do any graphic design or PM, it would be very different. When I do have to do PM stuff, I use another workspace and a whole new set of applications.&lt;br /&gt;&lt;br /&gt;I don&amp;#39;t mean to troll you. I find it very interesting that you and I have very different perspectives and setups for doing very similar work. Also, I know you can take it :-)&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Elise&lt;/div&gt;
&lt;div class='content'&gt;
I use gitg as well for organizing commits, it&amp;#39;s nearly equivalent to gitx and beats the hell out of git log :)&lt;br /&gt;&lt;br /&gt;I also use Linux, and I found that for me tiled window managers do wonders for focus - though I understand that Compiz has that possibility now.&lt;br /&gt;I use the Awesome window manager (http://awesome.naquadah.org/), which has all manner of keyboard shortcuts and can be customized using Lua.  It&amp;#39;s also ideally suited to the kind of organization you&amp;#39;re talking about, naming tabs and allocating applications to it.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;straydogsw&lt;/div&gt;
&lt;div class='content'&gt;
Nice post Nick, I&amp;#39;ve been wanting to learn some more keyboard shortcuts for moving around the linux desktop and this has been very useful.&lt;br /&gt;&lt;br /&gt;Those windows look tight in your [1,2] screenshot. Do you have a window-placer util or something to get them so nice and even?&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;straydogsw&lt;/div&gt;
&lt;div class='content'&gt;
oops, nevermind. I see that they are vim-splits in a full size terminal.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
yup :-)&lt;br /&gt;&lt;br /&gt;There are a bunch of window managers and things for placing windows in linux, but I don&amp;#39;t know them.&lt;br /&gt;&lt;br /&gt;If you install the ubuntu package compizconfig-settings-manager and run it you&amp;#39;ll get the desktop effects settings, which have a keyboard shortcut for tons of stuff.&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>Everything that is wrong with mocking, bdd, and rspec</title>
    <link href="http://ngauthier.com/2010/12/everything-that-is-wrong-with-mocking.html"/>
    <updated>2010-12-02T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2010/12/everything-that-is-wrong-with-mocking</id>
    <content type="html">&lt;p&gt;Below is a public excerpt from the 
&lt;a href=&quot;http://www.pragprog.com/titles/achbd/the-rspec-book&quot;&gt;recently release RSpec book
&lt;/a&gt;:
&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
module Codebreaker
  describe Game do
    describe &quot;#start&quot; do
      it &quot;sends a welcome message&quot; do
        output = double('output')
        game = Game.new(output)
        output.should_receive(:puts).with('Welcome to Codebreaker!')
        game.start
      end
      it &quot;prompts for the first guess&quot;
    end
  end
end
&lt;/pre&gt;
&lt;p&gt;This example illustrates 
&lt;strong&gt;what is wrong with standard BDD as practiced today
&lt;/strong&gt;. Consider the following correct implementation of the spec above:
&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
module Codebreaker
  class Game
    def initialize(output)
      @output = output
    end
    def start
      @output.puts(&quot;Welcome to Codebreaker!&quot;)
    end
  end
end
&lt;/pre&gt;
&lt;p&gt;Now consider the following refactorings of the start method:
&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
@output.write(&quot;Welcome to Codebreaker!\n&quot;)
@output.print(&quot;Welcome to Codebreaker!\n&quot;)
&gt; &quot;Welcome to Codebreaker!&quot;.split.each{|c| output.write(c)}; output.write &quot;\n&quot;
@output 
&gt; &quot;Welcome to Codebreaker!\n&quot;
&lt;br /&gt;
&lt;/pre&gt;
&lt;p&gt;All of these produce the 
&lt;strong&gt;exact same
&lt;/strong&gt; result, which is sending the string to the output stream. However, all of these refactorings will fail the test suite.
&lt;/p&gt;
&lt;p&gt;Now consider the following implementation:
&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
@output.puts &quot;Welcome to Codebreaker!&quot;
@output 
&gt; &quot;You smell bad and are also ugly!&quot;
&lt;/pre&gt;
&lt;p&gt;That test 
&lt;strong&gt;passes
&lt;/strong&gt; the spec above, but it also insults our (paying?) users!
&lt;/p&gt;
&lt;p&gt;One of the primary reasons for having a test suite is so that 
&lt;strong&gt;I can refactor and have the tests validate my changes
&lt;/strong&gt;. If I have to change my tests and my code just to re-write the way I cause the same end result, then my test suite is useless for refactoring.
&lt;/p&gt;
&lt;p&gt;So now the obvious question is &quot;Well Nick, how would you test it?&quot;
&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;
require 'stringio'
output = StringIO.new
game = Game.new(output)
game.start
output.seek(0)
assert_equal &quot;Welcome to Codebreaker!\n&quot;, output.read
&lt;/pre&gt;
&lt;p&gt;This test passes for all the implementations listed initially, and will fail for the implementation in which we insult our users.
&lt;/p&gt;
&lt;p&gt;Think about the difference here. The original example is saying &quot;Make sure the game calls puts with the following argument&quot; whereas my test is saying &quot;Make sure the game outputs the following string to the output object&quot;. The second case is 
&lt;strong&gt;far
&lt;/strong&gt; more useful.
&lt;/p&gt;
&lt;p&gt;Mocking is a great tool for dealing with stable APIs. However, when introduced in areas of the codebase that have just a small amount of churn, they can cripple the test suite with their brittleness. How can we expect to embrace change when our codebase can't?
&lt;/p&gt;
&lt;p&gt;RSpec has become so intertwined with mocking and stubbing practices that many people are taking mocking to the extreme and stubbing out their own code.
&lt;/p&gt;
&lt;p&gt;I will close by deferring to the wisdom of a higher power:
&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;It is the high coupling between modules and tests that creates the need for a mocking framework. This high coupling is also the cause of the dreaded “Fragile Test” problem. How many tests break when you change a module? If the number is high, then the coupling between your modules and tests in high. Therefore, I conclude that those systems that make prolific use of mocking frameworks are likely to suffer from fragile tests.
  &lt;/p&gt;
  &lt;p&gt;...
  &lt;/p&gt;
  &lt;p&gt;Keeping middle-class test doubles (i.e. Mocks) to a minimum is another way of decoupling. Mocks, by their very nature, are coupled to mechanisms instead of outcomes. Mocks, or the setup code that builds them, have deep knowledge of the inner workings of several different classes. That knowledge is the very definition of high-coupling.
  &lt;/p&gt;- 
  &lt;a href=&quot;http://blog.objectmentor.com/articles/2010/01/23/mocking-mocking-and-testing-outcomes&quot;&gt;Uncle Bob Martin on Object Mentor
  &lt;/a&gt;
&lt;/blockquote&gt;
&lt;/div&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;div class='comments'&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;dchelimsky&lt;/div&gt;
  &lt;div class='content'&gt;
    The test you propose will fail as soon as an additional message (praising the user?) needs to be displayed in response to start(), so it, too, is brittle due to its constraints. It&amp;#39;s all trade-offs, my friend.&lt;br /&gt;&lt;br /&gt;But thanks for promoting the book!&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
  &lt;div class='content'&gt;
    Of course it will fail, because it is a spec on the start method, whose behavior has changed :-)&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;dchelimsky&lt;/div&gt;
  &lt;div class='content'&gt;
    It&amp;#39;s behavior has been _extended_. If the existing message changed, that would be one thing, but the fact that there is an additional side-effect of calling start() should not cause this expectation to fail.&lt;br /&gt;&lt;br /&gt;The issue here is that the behavior of the start() method is reflected in another object. Both examples inspect the collaborator to specify the outcome. Both have constraints that will cause future failures depending on how things change.&lt;br /&gt;&lt;br /&gt;You could probably make something more flexible by using assert_match instead of assert_equal, but that wouldn&amp;#39;t protect against a mean-spirited developer insulting users. Again, it&amp;#39;s all trade-offs. Pick your poison.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
  &lt;div class='content'&gt;
    Yeah I agree. It depends on how much you want to assert. I was considering doing it as a regex match. I decided that I wanted to asset that the method output the exact message, no more and no less. It could be a looser test, and allow for other tests to check other behaviors.&lt;br /&gt;&lt;br /&gt;I probably would do that in practice when I added more behavior to the method.&lt;br /&gt;&lt;br /&gt;Decisions that aren&amp;#39;t trade-offs never instigate an interesting debate.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;jyurek&lt;/div&gt;
  &lt;div class='content'&gt;
    Extended or replaced, the behavior *changed*, and that&amp;#39;s what tests are meant to detect, after all.&lt;br /&gt;&lt;br /&gt;I think Nick&amp;#39;s example highlights exactly why overmocking is a bad thing. IMO, I don&amp;#39;t think this is a failure (per se) of BDD, RSpec, or even Mocking as a concept, it&amp;#39;s just not the best test for the situation.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;jollyjerry&lt;/div&gt;
  &lt;div class='content'&gt;
    I definitely agree with your point that mocking and stubbing can easily be taken too far.  What I hate the most is when I see an entire chain of internal implementation stubbed out (foo.hidden.internal.method.baz).  It ends up coupling your tests to your implementation, and since tests are also code, you make your code spaghetti that much more tangled.  I&amp;#39;m just as guilty as the next guy when it comes to thinking abstractly about what the functionality should be, rather than reduplicating my code in test form.  Like dchelimsky said, it&amp;#39;s a hard problem!&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Evan Light&lt;/div&gt;
  &lt;div class='content'&gt;
    Agreed -- including that perhaps you should be using an &amp;quot;assert output.read =~ //.&lt;br /&gt;&lt;br /&gt;This is why, as a general rule, I have learned to largely avoid mocking and stubbing unless I am writing unit tests against an external system.&lt;br /&gt;&lt;br /&gt;Yes, test doubles are great for isolating the unit under test.  However, that isolation comes at a cost.  &lt;br /&gt;&lt;br /&gt;Should an external dependency change, your test doubled tests will lie to you!  The test double is blissfuly unaware that the interface it has doubled has changed.  Therefore, your test will inaccurately pass.  Under such circumstances, I want my tests to fail loudly!&lt;br /&gt;&lt;br /&gt;In my experience, this has resulted in significant time lost tracking down production application problems!&lt;br /&gt;&lt;br /&gt;TL;DR White-box testing coupled with test doubles is dangerous.  I strongly prefer an integration test that exercises the external dependency.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Evan Light&lt;/div&gt;
  &lt;div class='content'&gt;
    David: While Nick&amp;#39;s test may have been brittle, at least the test would have failed as expected.  Should the output string change, his test test fails.  Should the implementation use print, his test fails.&lt;br /&gt;&lt;br /&gt;The failure of the test is adequate to ensure that the test is revisited and updated.&lt;br /&gt;&lt;br /&gt;Honestly, I admire so much of what you have done for the Ruby community.  However, your tenacious adherence to mocking and stubbing as a routine TDD technique still utterly bewilders me.  The brittleness of the resulting test hardly seems worth the benefit in almost any case except the rare external dependency.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;myron.marston&lt;/div&gt;
  &lt;div class='content'&gt;
    Careless mocking can definitely make a test suite excessively brittle, but my overall experience with mocking has been the opposite.  I used to practice a more classical TDD approach, where I used little-to-no-mocking and I wound up with bloated, slow, brittle test suites.  After experimenting a bit and reading the RSpec book, I&amp;#39;ve started using mocking as a regular technique to achieve isolation in my unit tests and it&amp;#39;s helped me create far less brittle test suites (not to mention they are much, much faster!). &lt;br /&gt;&lt;br /&gt;It&amp;#39;s definitely easy to shoot yourself in the foot with mocking (just like it is with ruby, git, or any of our other standard, powerful tools we use daily), but that doesn&amp;#39;t mean it&amp;#39;s not a useful, worthwhile tool: you just have to be aware of the dangers of over-mocking and mock with care.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
  &lt;div class='content'&gt;
    Test suite speed is not a valid argument for mocking.&lt;br /&gt;&lt;br /&gt;http://grease-your-suite.heroku.com/&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Evan Light&lt;/div&gt;
  &lt;div class='content'&gt;
    @Myron: How were your tests more brittle before introducing test doubles?  &lt;br /&gt;&lt;br /&gt;If you&amp;#39;re test has clear preconditions, execution of the code under test, and clear expectations, I don&amp;#39;t see how that leads to brittleness.&lt;br /&gt;&lt;br /&gt;Can you give an example of one of your fragile pre-test double tests?&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Jim Gay&lt;/div&gt;
  &lt;div class='content'&gt;
    I agree. If you&amp;#39;re doing should_receive(:puts) then you&amp;#39;re saying that calling &amp;quot;puts&amp;quot; is important.&lt;br /&gt;&lt;br /&gt;All of this is behavior of the code, you just need to spec what behavior is important: the methods called, or the output. Sometimes it might be important that a method is called, but not in this situation.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick&lt;/div&gt;
  &lt;div class='content'&gt;
    I completely agree with Jim. It comes down to what behaviour is important, and thus needs to be tested.&lt;br /&gt;&lt;br /&gt;If Codebreaker only cares that @output begins with &amp;quot;Welcome to Codebreaker!&amp;quot;, then Nick Gauthier&amp;#39;s approach is ideal.&lt;br /&gt;&lt;br /&gt;If Codebreaker relies on #puts being called on @output , then the &amp;quot;bad test&amp;quot; is ideal.&lt;br /&gt;&lt;br /&gt;As always, everything&amp;#39;s contextual: what&amp;#39;s important to you?&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
  &lt;div class='content'&gt;
    @Jim @Nick&lt;br /&gt;&lt;br /&gt;I totally agree. What I dislike is the tendency for people to write a test against methods being called, when that is almost always not what is important in the test.&lt;br /&gt;&lt;br /&gt;Continuously asking &amp;quot;What am I testing and why am I testing it&amp;quot; is very important to writing good code and good tests.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick&lt;/div&gt;
  &lt;div class='content'&gt;
    &amp;gt; Continuously asking &amp;quot;What am I testing and why am I testing it&amp;quot; is very important to writing good code and good tests.&lt;br /&gt;&lt;br /&gt;Hear hear!&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;tooky&lt;/div&gt;
  &lt;div class='content'&gt;
    If you are using mocks and stubs in your unit tests then you need to have a good set of acceptance/integration tests as well.&lt;br /&gt;&lt;br /&gt;I like using mocks and stubs in my unit tests as they allow me to isolate the area of the code I&amp;#39;m working in, and I don&amp;#39;t have to worry about side-effects or complex set-up of other objects. I also use cucumber though, this gives me great black-box coverage of the system.&lt;br /&gt;&lt;br /&gt;So while changing the original example will make this spec break, it won&amp;#39;t make any other specs in the system break, because no other specs will depend on its behaviour. So long as the behaviour is preserved it won&amp;#39;t break the acceptance/integration tests either.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Pat Maddox&lt;/div&gt;
  &lt;div class='content'&gt;
    The mock-based example specifies the interaction with the collaborator.  It demonstrates that you can pass in any object that responds to #puts(str) and expect it to work.&lt;br /&gt;&lt;br /&gt;Your refactoring is valid -- when the output object responds to #puts, #write, #print, and #&amp;lt;&amp;lt;, and implements them all in basically the same way.&lt;br /&gt;&lt;br /&gt;You are free to change the internals of a method however you want, but remember that certain changes will have broader-reaching effects than others.  Changing how you build up the string to, say, an array of strings that then get joined, should certainly be encapsulated.  Changing how you call collaborators is a totally different thing -- you&amp;#39;re changing the contract, potentially in a way that&amp;#39;s incompatible with existing clients.&lt;br /&gt;&lt;br /&gt;Focused examples (or unit tests, or microtests, or whatever) help answer the question, &amp;quot;what do I need to know to use this code?&amp;quot;  When there is a collaborator involved, one of the key things to know is the protocol that the collaborator must adhere to.  An interaction-based example makes that protocol explicit.  Moreover, it establishes a checkpoint.  Should you decide to call #write instead of #puts, you have to consider the possible implications to existing code.&lt;br /&gt;&lt;br /&gt;I understand where you&amp;#39;re coming from.  When you run the program, there is no externally visible difference in behavior.  That is why we tend to separate the duties of checking program behavior into acceptance tests.  Your unit tests then become a place for you to check an object&amp;#39;s correctness, which includes its own logic and its interactions with other objects.  Don&amp;#39;t assume that because the external behavior of the program stays the same, that the behavior internal to objects has stayed the same as well.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;admin&lt;/div&gt;
  &lt;div class='content'&gt;
    tl;dr of Pat&amp;#39;s comment: I&amp;#39;mma let you finish, but the difference between unit tests and acceptance tests is one of the best differences of all time.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
  &lt;div class='content'&gt;
    haha thanks @admin.&lt;br /&gt;&lt;br /&gt;@Pat I understand that is the case when you are unit testing between collaborators where specific method invocation is important. However in the example I used, it was clear to me that the caller was not a collaborator but a higher level controller or supervisor. Actors at a higher level of abstraction should not be concerned with the implementation details but rather the results.&lt;br /&gt;&lt;br /&gt;To sum it up, I interpreted this as an acceptance test.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;dchelimsky&lt;/div&gt;
  &lt;div class='content'&gt;
    Evan - there is a chapter in The RSpec Book on Mock Objects that talks about when to use them and the potential pitfalls (including the one that Nick brings up here).&lt;br /&gt;&lt;br /&gt;Mocking external dependencies is actually considered to be a mocking no-no, because then you create a binding between your app and the external dependency&amp;#39;s API. Instead, write a thin wrapper around that dependency that speaks in the domain of your app, and mock that as a means of isolating your app&amp;#39;s code/specs from that dependency.&lt;br /&gt;&lt;br /&gt;But that is only the tip of the iceberg when it comes to use cases served well by mocks. Others include: non-deterministic collaborators (intentionally random behavior) of collaborators), polymorphic collaborators (no need to have 3 examples when 1 would do), protocol definitions (where which methods are called represent adherence to a contract), collaborators that don&amp;#39;t even exist yet, etc, etc.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
  &lt;div class='content'&gt;
    @dchelimsky&lt;br /&gt;&lt;br /&gt;I read your slides from rubyconf and I agree with your stance on mocking. However about 95% of people that copy rspec examples don&amp;#39;t understand the implications and often code themselves into mocking hell. They are my target audience :-)&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;dchelimsky&lt;/div&gt;
  &lt;div class='content'&gt;
    &amp;quot;To sum it up, I interpreted this as an acceptance test.&amp;quot;&lt;br /&gt;&lt;br /&gt;Part of the aim of the book is to make a distinction between application and object behavior: Cucumber is well suited to specify things at the application level (end to end tests/acceptance tests/customer tests, etc), and RSpec is well suited to specify things at the object level (unit tests, micro tests, developer tests, etc).&lt;br /&gt;&lt;br /&gt;The example you cite comes from a chapter on describing the behavior of objects with RSpec (i.e. unit tests), after a chapter on describing the behavior of applications with Cucumber (i.e. acceptance tests), and is not at all intended to be an acceptance test. Hope that clears at least that part of this up for you.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;dchelimsky&lt;/div&gt;
  &lt;div class='content'&gt;
    @nickgauthier - I appreciate wanting to help people understand the subtle waters of mocking. Unfortunately, the title of this post is not in any way nuanced or subtle. If your target audience is people who blindly copy examples without thinking about their implications or trying to learn to understand them, it&amp;#39;s likely that they won&amp;#39;t actually read this full post, much less the thoughtful discussion that follows.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
  &lt;div class='content'&gt;
    If I had to change the title, it would be expanded to &amp;quot;Everything that is wrong with how everyone uses mocks in rspec to do bdd&amp;quot;&lt;br /&gt;&lt;br /&gt;Every time I&amp;#39;ve encountered mocking in test code (aside from 3rd party calls) I&amp;#39;ve seen it fall under the category of the content of this post.&lt;br /&gt;&lt;br /&gt;While you describe a sound way to use mocks to test object behavior, I have never seen it executed properly. This is not to say it cannot be done, but that everyone is doing it wrong.&lt;br /&gt;&lt;br /&gt;And yeah, you can&amp;#39;t defeat the cargo-cult.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Evan Light&lt;/div&gt;
  &lt;div class='content'&gt;
    @David: I&amp;#39;m familiar with that practice RE: APIs.  You took me a little too literally.  I always abstract them a level.&lt;br /&gt;&lt;br /&gt;I&amp;#39;ll have to take another gander at the (finally ;-) ) completed RSpec book. I bought the beta a very long time ago and haven&amp;#39;t read it much since.  I&amp;#39;m curious about what you have to say about mocking.&lt;br /&gt;&lt;br /&gt;However, I&amp;#39;ve generally found white box testing to be too implementation specific.  Granted, I realize that there are almost &amp;quot;camps&amp;quot; among TDD&amp;#39;ers: the &amp;#39;behavioral statists&amp;#39; that I likely fall under, the &amp;#39;unit mockists&amp;#39; that you likely fall under, and others.  I tend to prefer writing acceptance/integration tests with only supporting unit tests as necessary to help me &amp;quot;fill in the gaps&amp;quot; where the feature is too complex to develop without unit tests to handle complex logic (see http://evan.tiggerpalace.com/articles/2010/12/02/stop-writing-code-you-dont-need/).&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;zenspider&lt;/div&gt;
  &lt;div class='content'&gt;
    @ngauthier:&lt;br /&gt;&lt;br /&gt;Via minitest (or test/unit in 1.9):&lt;br /&gt;&lt;br /&gt;    def test_start_output&lt;br /&gt;      assert_output &amp;quot;Welcome to Codebreaker!\n&amp;quot;, &amp;quot;&amp;quot; do&lt;br /&gt;        Game.new.start&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;(blogger.... you suck. no pre tag allowed? no formatting help? bite me)&lt;br /&gt;&lt;br /&gt;@dchelimsky: the rspec code would break too because EVERYONE uses .once. And remember, since we do test-first, it wouldn&amp;#39;t break because we changed the output, it&amp;#39;d break because we added additional assertions to the test that we then needed to make pass. That isn&amp;#39;t brittle. That&amp;#39;s process.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;myron.marston&lt;/div&gt;
  &lt;div class='content'&gt;
    @Evan:  Re: &amp;quot;Can you give an example of one of your fragile pre-test double tests?&amp;quot;&lt;br /&gt;&lt;br /&gt;The code base I&amp;#39;m thinking of was a rails app, and simple changes to models (i.e. adding a new required field or changing a validation) would cascade across the test suite and break lots of other tests because those tests depended on the existing behavior of the model when they shouldn&amp;#39;t have.  For example, a controller functional test that passed in valid attributes and would assert some result failed because the passed attributes were no longer valid.  You may argue that the breaking controller test was a good thing, but I don&amp;#39;t agree.  I like to have lots of fast, isolated unit tests (which do use mocking carefully), as well as some full-stack integration tests (which don&amp;#39;t use mocking).  In this case, a change to a model my break a unit test and an integration test, but it&amp;#39;s not going to cascade across my test suite.&lt;br /&gt;&lt;br /&gt;Having controller tests that depended on the knowledge of what constituted a valid record was a very brittle approach.  Mocking has worked well to help me unit test my controllers.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;dchelimsky&lt;/div&gt;
  &lt;div class='content'&gt;
    @zenspider - that works assuming you have a test named test_start_output and it&amp;#39;s the only test ever written that cares about the output of the start() method. As soon as additional context requires that start provide different output under different conditions, either this test would start to get unruly (too many states/assertions), or new tests would emerge that, in making them to pass, might cause this one to break.&lt;br /&gt;&lt;br /&gt;re: the rspec code and &amp;quot;once&amp;quot; - in fact, it breaks just 2 or 3 pages later in the book, and a wonderful learning opportunity emerges. Hooray for examples taken out of context!&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Sean DeNigris&lt;/div&gt;
  &lt;div class='content'&gt;
    Of course, none of these pitfalls have anything to do with BDD or RSpec.  Just saying...&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Pat Maddox&lt;/div&gt;
  &lt;div class='content'&gt;
    Can you please gist a file that demonstrates that the spec passes even when you include the insulting message to the user?  Here&amp;#39;s what I got: https://gist.github.com/730609&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
  &lt;div class='content'&gt;
    @Pat ah you&amp;#39;re right, since it&amp;#39;s a double it will complain about extra method calls. This is why mocking becomes annoying when your method does a few things with its input. Any test will need an elaborate mocking setup.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;dchelimsky&lt;/div&gt;
  &lt;div class='content'&gt;
    @Nick - a page or two later in the book we add &amp;quot;as_null_object&amp;quot; to the double, and the need for an elaborate mocking setup is eliminated.&lt;br /&gt;&lt;br /&gt;That said, we&amp;#39;ve all been missing the deeper problem here, which was recognized immediately by Nat Pryce and reflected in these two tweets:&lt;br /&gt;&lt;br /&gt;http://twitter.com/natpryce/status/12029918607048704&lt;br /&gt;&lt;br /&gt;http://twitter.com/natpryce/status/12030541293424641&lt;br /&gt;&lt;br /&gt;We&amp;#39;ve been talking about pain in the example, but none of us have &amp;quot;listened to the test&amp;quot;. The real problem here is that there is a missing abstraction. Change &amp;quot;output&amp;quot; to &amp;quot;reporter&amp;quot; (or similar) and change &amp;quot;puts&amp;quot; to &amp;quot;message&amp;quot; (or similar) and the refactoring concern you raised goes away, everything is &amp;quot;speaking&amp;quot; in the domain, and all is right with the world.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
  &lt;div class='content'&gt;
    @dchelimsky I think the underlying concept still stands.&lt;br /&gt;&lt;br /&gt;A mocking unit testing strategy encourages testing the implementation of a method because it&amp;#39;s easy. My argument is that it doesn&amp;#39;t get you very much in the way of code validation.&lt;br /&gt;&lt;br /&gt;When I write tests, I think about the effects of my code, and then I validate that the effects occurred.&lt;br /&gt;&lt;br /&gt;For example, consider testing user registration. Which of these scenarios below is most useful?&lt;br /&gt;&lt;br /&gt;When I register on the site&lt;br /&gt;&lt;br /&gt;=&amp;gt;&lt;br /&gt;&lt;br /&gt;1) Then the database should be asked to insert a user&lt;br /&gt;2) Then there should be 50 users&lt;br /&gt;3) Then there should be an additional user&lt;br /&gt;4) Then I can log in&lt;br /&gt;&lt;br /&gt;I like #4, because it focuses on the input and the ultimately desired result and goal of a feature. This user-acceptance, and not unit testing.&lt;br /&gt;&lt;br /&gt;But in unit testing I like to focus on the same goals and ask the same questions.&lt;br /&gt;&lt;br /&gt;For example, if I&amp;#39;m implementing a &amp;quot;users sorted by join date&amp;quot; method, I can see two ways of going about it:&lt;br /&gt;&lt;br /&gt;1) Mock the user model and ensure that the storage adapter is called with the appropriate method and parameters to return a sorted list of users.&lt;br /&gt;2) Create a couple of users, call the method, and see if the results are sorted.&lt;br /&gt;&lt;br /&gt;#1 is white-box and #2 is black box. I&amp;#39;ll pick black box every time because it focuses on my goals, and not my process.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Regarding the tweets:&lt;br /&gt;&lt;br /&gt;Yes, it&amp;#39;s easy to blame the tools, but what if a particular tool can be easily misused? In the best of hands, it is revolutionary and powerful, but in most people&amp;#39;s hands it&amp;#39;s destructive. For example, morphine.&lt;br /&gt;&lt;br /&gt;I think mocking is being abused and overused and is causing people pain in the long run. It&amp;#39;s enticing because its simple to implement, but I find the assertions it makes to be weak and brittle.&lt;br /&gt;&lt;br /&gt;I will agree, however, that in cases where you have a stable API that mocking can make your life easier (especially in large and complicated codebases). However, I&amp;#39;ve always found that it&amp;#39;s not that hard to create helper methods to setup elaborate scenarios in which to do a real goal-based test. There are great gems out there like cucumber and factory girl that allow you to encapsulate complicated functionality in simple steps.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;dchelimsky&lt;/div&gt;
  &lt;div class='content'&gt;
    @Nick - &amp;quot;but what if a particular tool can be easily misused? In the best of hands, it is revolutionary and powerful, but in most people&amp;#39;s hands it&amp;#39;s destructive. For example, morphine.&amp;quot;&lt;br /&gt;&lt;br /&gt;By that logic, we should all stop using Ruby :)&lt;br /&gt;&lt;br /&gt;re: the &amp;quot;sorted users&amp;quot; example, I agree that is likely better specified with a more black box approach.&lt;br /&gt;&lt;br /&gt;The distinction is that, in the sorted users example, the User class returns the object (a list of users) on which expected outcomes can be specified.&lt;br /&gt;&lt;br /&gt;In the output example, the outcome is specified _on a collaborator_. Whether we specify that as an interaction or post-action state-based verification, the example is still bound to the collaborator object, so there is little difference in terms of dependencies and brittleness.&lt;br /&gt;&lt;br /&gt;Using a test double for &amp;quot;reporter&amp;quot; gives us the freedom to introduce different &amp;quot;reporter&amp;quot; solutions (command line, text file, web page, etc) without these examples failing. In that context, the use of a test double and a message expectation is actually less brittle than the alternatives.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
  &lt;div class='content'&gt;
    @dchelimksy no, I&amp;#39;m not saying stop using ruby. I&amp;#39;m not saying stop using morphine in hospitals either.&lt;br /&gt;&lt;br /&gt;It&amp;#39;s more of an education perspective. I want to show people how they should and should not use tools so they don&amp;#39;t dig themselves into a hole.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I think we&amp;#39;re in agreement that when a collaborator&amp;#39;s interface is well defined and stable that mocking is a good solution.&lt;br /&gt;&lt;br /&gt;The problem is that whenever I see examples of mocking it&amp;#39;s always in (what I deem to be) inappropriate scenarios.&lt;br /&gt;&lt;br /&gt;If you showed a reporter class with a simple API of reporting messages, then showed the Codebreaker class working with a mocked Reporter, I&amp;#39;d be much happier with your example. I worry about a generation of rubyist who will mock their test suite to hell and then be stuck in a broken world.&lt;br /&gt;&lt;br /&gt;Of course, anyone can write bad code in any framework, but I want to teach people the appropriate uses with solid examples.&lt;br /&gt;&lt;br /&gt;I was very disappointed to see this example in the excerpts of the rspec book, because I&amp;#39;ve had to refactor and fix code like that and it&amp;#39;s not fun.&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
  &lt;div class='author'&gt;dchelimsky&lt;/div&gt;
  &lt;div class='content'&gt;
    Well you&amp;#39;ve got me there. This is clearly a bad excerpt and I&amp;#39;ll have it changed soon. I hope you&amp;#39;ll consider reading the rest of the tutorial in spite of the excerpt. I&amp;#39;d welcome your feedback.&lt;br /&gt;&lt;br /&gt;I think we have the same goals in terms of deepening the understanding of when/where to use different tools. I don&amp;#39;t think we agree on everything here (I don&amp;#39;t &amp;quot;always&amp;quot; prefer anything), but I think we probably agree on more than we disagree on.&lt;br /&gt;&lt;br /&gt;Cheers,&lt;br /&gt;David&lt;/div&gt;
&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>Microgem: JSLintRB-v8</title>
    <link href="http://ngauthier.com/2010/11/microgem-jslintrb-v8.html"/>
    <updated>2010-11-29T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2010/11/microgem-jslintrb-v8</id>
    <content type="html">&lt;div class='post'&gt;
GOAL: Provide a Ruby interface for running JSLint on javascript files using v8.&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;require 'jslintrb-v8'&lt;br /&gt;puts JSLint.new.check(&quot;var x = 5&quot;)&lt;/pre&gt;Will return the string:&lt;br /&gt;&lt;pre&gt;Error at line 1 character 1: Missing &quot;use strict&quot; statement.&lt;br /&gt;   var x = 5&lt;br /&gt; Error at line 1 character 10: Missing semicolon.&lt;br /&gt;   var x = 5&lt;/pre&gt;Also, all of jslint's configuration options are available in the constructor:&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;JSLint.new(:undef =&gt; false, :sub =&gt; true)&lt;/pre&gt;&lt;a href=&quot;https://github.com/ngauthier/jslintrb-v8&quot;&gt;JSLintRB-v8 on Github&lt;/a&gt;&lt;br /&gt;&lt;a href=&quot;http://rdoc.info/github/ngauthier/jslintrb-v8/master/JSLint&quot;&gt;JSLintRB-v8 on Rdoc.info&lt;/a&gt;&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>Using Rails's Object#to_json to create a clean JSON Presenter</title>
    <link href="http://ngauthier.com/2010/11/using-railss-objecttojson-to-create.html"/>
    <updated>2010-11-17T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2010/11/using-railss-objecttojson-to-create</id>
    <content type="html">&lt;div class='post'&gt;
The problem: You have an ActiveRecord model (or any object, really) and you want to output it to json, but you need some specific methods and maybe some processing of its attributes before you can call .to_json.&lt;br /&gt;&lt;br /&gt;Let's pretend we have the following object:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;class Widget&lt;br /&gt;  attr_accessor :id&lt;br /&gt;  attr_accessor :name&lt;br /&gt;  attr_accessor :gadgets&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class Gadget&lt;br /&gt;  attr_accessor :id&lt;br /&gt;  attr_accessor :name&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And we want this json from a widget:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;{&lt;br /&gt;  id : 'widget-47',&lt;br /&gt;  name: 'name of widget',&lt;br /&gt;  children: [&lt;br /&gt;    {&lt;br /&gt;      id : 'gadget-63',&lt;br /&gt;      name : 'name of gadget'&lt;br /&gt;    }&lt;br /&gt;  ]&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Note that ID has the class name on the front, the name is passed through directly. Also, the sub-objects (Gadget) have their id processed.&lt;br /&gt;&lt;br /&gt;First, let's make the Gadget presenter:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;class GadgetPresenter&lt;br /&gt;  attr_reader :id&lt;br /&gt;  attr_reader :name&lt;br /&gt;  def initialize(gadget)&lt;br /&gt;    @id = %{gadget-#{gadget.id}}&lt;br /&gt;    @name = gadget.name&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Rails provides Object extensions that give us a to_json method on every object. By default, this will call all of our attr_readers. So, all we have to do is provide attr_readers for the attributes we want in the json. Now, Gadget#to_json would give us:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;{&lt;br /&gt;  id: 'gadget-63',&lt;br /&gt;  name: 'name of gadget'&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now the Widget presenter:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;class WidgetPresenter&lt;br /&gt;  attr_reader :id&lt;br /&gt;  attr_reader :name&lt;br /&gt;  attr_reader :children&lt;br /&gt;  def initialize(widget)&lt;br /&gt;    @id = %{widget-#{widget.id}}&lt;br /&gt;    @name = widget.name&lt;br /&gt;    @children = widget.gadgets.collect{|g| GadgetPresenter.new(g)}&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Pretty much the same, except for the children. This lets us call the associate &quot;children&quot; instead of &quot;gadgets&quot;. And all we have to do is collect up a bunch of gadget presenters. When .to_json is called on the widget, it calls to_json on the attributes. Since children is an array, it collects .to_json from each entry in the array, which calls the GadgetPresenter's to_json.&lt;br /&gt;&lt;br /&gt;I really like this implementation because it's really just an adapter, and it only concerns itself with the data. It is also external to the Widget and Gadget class, allowing for multiple types of presenters easily.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Here is a running example: (requires rails 3) &lt;a href=&quot;https://gist.github.com/703747&quot;&gt;https://gist.github.com/703747&lt;/a&gt;&lt;/div&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;div class='comments'&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;mattsears&lt;/div&gt;
&lt;div class='content'&gt;
Nice article, thanks for posting this.  Quick question...where do you recommend storing the presenter classes in you Rails project?  I thought about &amp;#39;app/presenters&amp;#39;, but maybe that&amp;#39;s overkill?&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;bryanl&lt;/div&gt;
&lt;div class='content'&gt;
app/presenters works well.  Keeping everything in app/models makes little babies cry.&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>Minimal cucumber stack for testing a rich javascript application</title>
    <link href="http://ngauthier.com/2010/11/minimal-cucumber-stack-for-testing-rich.html"/>
    <updated>2010-11-11T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2010/11/minimal-cucumber-stack-for-testing-rich</id>
    <content type="html">&lt;div class='post'&gt;
These are instructions for setting up a very bare cucumber stack for testing a rich javascript application.&lt;br /&gt;&lt;br /&gt;All code available here: &lt;a href=&quot;https://github.com/ngauthier/cucumber-webapp-demo&quot;&gt;https://github.com/ngauthier/cucumber-webapp-demo&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The following stack is used:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;  &lt;li&gt;Cucumber&lt;/li&gt;  &lt;li&gt;Capybara&lt;/li&gt;  &lt;li&gt;Selenium&lt;/li&gt;  &lt;li&gt;WEBrick&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;First, we make our awesome javascript powered webapp:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;&amp;lt;html&amp;gt;&lt;br /&gt;  &amp;lt;head&amp;gt;&lt;br /&gt;    &amp;lt;script type='text/javascript' src='jquery-1.4.3.min.js'&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;    &amp;lt;script type='text/javascript'&amp;gt;&lt;br /&gt;      $(function() {&lt;br /&gt;        $('#special-link').click(function(event) {&lt;br /&gt;          $('#results').html(&quot;This is totally awesome&quot;);&lt;br /&gt;          event.preventDefault();&lt;br /&gt;        });&lt;br /&gt;      });&lt;br /&gt;    &amp;lt;/script&amp;gt;&lt;br /&gt;  &amp;lt;/head&amp;gt;&lt;br /&gt;  &amp;lt;body&amp;gt;&lt;br /&gt;    &amp;lt;h1&amp;gt;My Webapp&amp;lt;/h1&amp;gt;&lt;br /&gt;    &amp;lt;p&amp;gt;&lt;br /&gt;    &amp;lt;a href='#' id='special-link'&amp;gt;Click on this link to make cool stuff happen&amp;lt;/a&amp;gt;&lt;br /&gt;    &amp;lt;/p&amp;gt;&lt;br /&gt;    &amp;lt;div id=&quot;results&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;  &amp;lt;/body&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;All we're doing here is showing some text when we click a link. But we're using jquery's events to do it.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now here is our feature file:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;Feature: My Awesome Link&lt;br /&gt;  Scenario: Clicking the awesome link shows awesome text&lt;br /&gt;    Given I am on the home page&lt;br /&gt;    Then  I should see &quot;My Webapp&quot;&lt;br /&gt;    And   I should see &quot;Click on this link to make cool stuff happen&quot;&lt;br /&gt;    And   I should not see &quot;This is totally awesome&quot;&lt;br /&gt;    When  I click &quot;Click on this link to make cool stuff happen&quot;&lt;br /&gt;    Then  I should see &quot;This is totally awesome&quot;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And here are our simple step definitions:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;Given /^I am on the home page$/ do&lt;br /&gt;  visit 'index.html'&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;Then /^I should see &quot;([^&quot;]*)&quot;$/ do |content|&lt;br /&gt;  within('body') do&lt;br /&gt;    assert page.has_content?(content)&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;Then /^I should not see &quot;([^&quot;]*)&quot;$/ do |content|&lt;br /&gt;  within('body') do&lt;br /&gt;    refute page.has_content?(content)&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;When /^I click &quot;([^&quot;]*)&quot;$/ do |link_text|&lt;br /&gt;  click_link_or_button(link_text)&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And here is the cucumber environment file where all the magic happens. See comments for description:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;require 'rubygems'&lt;br /&gt;require 'cucumber'&lt;br /&gt;require 'capybara/cucumber'&lt;br /&gt;require 'webrick'&lt;br /&gt;&lt;br /&gt;# setup capybara on selenium&lt;br /&gt;Capybara.default_driver = :selenium&lt;br /&gt;&lt;br /&gt;# This maps to webrick below&lt;br /&gt;Capybara.app_host = 'http://127.0.0.1:3000'&lt;br /&gt;Capybara.default_selector = :css&lt;br /&gt;&lt;br /&gt;# Extend Cucumber's World with minitest assertions&lt;br /&gt;World(MiniTest::Assertions)&lt;br /&gt;&lt;br /&gt;# Launch a webrick server in a thread&lt;br /&gt;AfterConfiguration do&lt;br /&gt;  server_thread = Thread.new do&lt;br /&gt;    project_root = File.join(File.dirname(__FILE__), '..', '..')&lt;br /&gt;    WEBrick::HTTPServer.new(&lt;br /&gt;      :Port =&gt; 3000,&lt;br /&gt;      # TODO use the real application directory&lt;br /&gt;      # Using the prototype directory for now&lt;br /&gt;      :DocumentRoot =&gt; File.join(project_root, 'public'),&lt;br /&gt;      :Logger =&gt; WEBrick::Log.new(File.join(project_root, 'cucumber.log')),&lt;br /&gt;      :AccessLog =&gt; StringIO.new # to nowhere&lt;br /&gt;    ).start&lt;br /&gt;  end&lt;br /&gt;  # Kill the server when cucumber is done&lt;br /&gt;  at_exit do&lt;br /&gt;    server_thread.exit&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The idea here is to boot webrick in a thread to serve the public directory, then connect selenium up to it. Very simple and light.&lt;br /&gt;&lt;br /&gt;All code available here: &lt;a href=&quot;https://github.com/ngauthier/cucumber-webapp-demo&quot;&gt;https://github.com/ngauthier/cucumber-webapp-demo&lt;/a&gt;&lt;/div&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;div class='comments'&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Sharad Jain&lt;/div&gt;
&lt;div class='content'&gt;
Nice, thanks!&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>PRY - Please Repeat Yourself</title>
    <link href="http://ngauthier.com/2010/11/pry-please-repeat-yourself.html"/>
    <updated>2010-11-08T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2010/11/pry-please-repeat-yourself</id>
    <content type="html">&lt;div class='post'&gt;
It's the canonical ruby metaprogramming example. You have this:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;def large_image&lt;br /&gt;  image_base + '-large.png'&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def medium_image&lt;br /&gt;  image_base + '-medium.png'&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def small_image&lt;br /&gt;  image_base + '-small.png'&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And you do some dynamic programming to define the methods with similar content:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;%w(large medium small).each do |size|&lt;br /&gt;  class_eval %{&lt;br /&gt;    def #{size}_image&lt;br /&gt;      image_base + '-#{size}.png'&lt;br /&gt;    end&lt;br /&gt;  }&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I have two problems with this pattern:&lt;br /&gt;&lt;br /&gt;1) The dynamic code is far less readable and clear. It might even need a comment! The static code is very easy to read.&lt;br /&gt;&lt;br /&gt;2) The dynamic code gives terrible stack traces&lt;br /&gt;&lt;pre&gt;(eval):3:in `small_image': undefined local variable or method `image_base' for #&lt;Image:0x4333458&gt; (NameError)&lt;br /&gt;  from test.rb:28&lt;br /&gt;&lt;/pre&gt;Versus the static stack trace:&lt;br /&gt;&lt;pre&gt;test.rb:15:in `small_image': undefined local variable or method `image_base' for #&lt;Image:0x47f42a8&gt; (NameError)&lt;br /&gt;  from test.rb:28&lt;br /&gt;&lt;/pre&gt;Here, test.rb:15 is the line inside &quot;small_image&quot; that calls &quot;image_base&quot;. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The argument for metaprogramming is so that there is only one place to change the content. However this is easily accomplished with a helper. In fact I already had that helper in place, image_base. If you find yourself repeating the code *inside* the method, it's worth extracting into a helper.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Metaprogramming is for a dynamic system, not for enumerations. For example, Rails controllers use dynamic programming to allow you to define your own action methods. These methods are called dynamically by the router. This is a huge oversimplification, but the idea is that the Rails authors have no idea what method names could be used, so they can't type them all out. It's a fundamentally different problem.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;If you find repetition in coding to be a difficult task, consider investing some time in learning a powerful editor with a regular expression matching and replace function.&lt;br /&gt;&lt;br /&gt;So, please repeat yourself!&lt;/div&gt;
</content>
  </entry>
  
  <entry>
    <title>RESTful Many to Many Relationships in Rails</title>
    <link href="http://ngauthier.com/2010/11/restful-many-to-many-relationships-in-rails.html"/>
    <updated>2010-11-04T00:00:00+00:00</updated>
    <id>http://ngauthier.com/2010/11/restful-many-to-many-relationships-in-rails</id>
    <content type="html">&lt;div class='post'&gt;
&lt;pre&gt;GET    /people =&gt; List people&lt;br /&gt;POST   /people =&gt; Create person&lt;br /&gt;PUT    /people =&gt; Replace the collection&lt;br /&gt;DELETE /people =&gt; Delete the collection&lt;br /&gt;&lt;br /&gt;GET    /people/:id =&gt; List attribute of a person&lt;br /&gt;PUT    /people/:id =&gt; update the attributes of a person&lt;br /&gt;POST   /people/:id =&gt; create a new collection under a person&lt;br /&gt;DELETE /people/:id =&gt; Delete a person&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In rails, we use&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;index:   GET    /people     =&gt; List people&lt;br /&gt;create:  POST   /people     =&gt; Create person&lt;br /&gt;show:    GET    /people/:id =&gt; List attribute of a person&lt;br /&gt;update:  PUT    /people/:id =&gt; update the attributes of a person&lt;br /&gt;destroy: DELETE /people/:id =&gt; Delete a person&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now we may also have:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;index:   GET    /groups     =&gt; List groups&lt;br /&gt;create:  POST   /groups     =&gt; Create group&lt;br /&gt;show:    GET    /groups/:id =&gt; List attribute of a group&lt;br /&gt;update:  PUT    /groups/:id =&gt; update the attributes of a group&lt;br /&gt;destroy: DELETE /groups/:id =&gt; Delete a group&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Consider a relationship of Many To Many between users and groups.&lt;br /&gt;&lt;br /&gt;How do I express the following?&lt;br /&gt;&lt;br /&gt;&quot;Add user X to group Y&quot;&lt;br /&gt;&lt;br /&gt;First thought may be:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;POST /groups/Y/users?user_id=X&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;But technically, this means &quot;Create a user whose attributes are {user_id =&gt; X} under group Y&quot;. This is wrong in two ways, the first is that we don't want to create a user inside a group. The second is that the user attributes are wrong, it's {id =&gt; X}.&lt;br /&gt;&lt;br /&gt;The correct request would be:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;POST /groups_users?user_id=X&amp;group_id=Y&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This means &quot;Create a new GroupUser linking node whose attributes are {user_id =&gt; X, group_id =&gt; Y}&quot;.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;OK now how do I express the following?&lt;br /&gt;&lt;br /&gt;&quot;Put user X into a new group, whose attributes are {name =&gt; 'My Group'}&quot;&lt;br /&gt;&lt;br /&gt;This is *two* requests:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;POST /groups?name=&quot;My Group&quot; =&gt; returns ID Z&lt;br /&gt;POST /groups_users?user_id=X&amp;group_id=Z&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;However, we can actually combine the requests like this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;POST /users/X/groups?name=&quot;My Group&quot;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In a situation where a Group Belongs To a User, this would create a group under the user.&lt;br /&gt;&lt;br /&gt;You would get in trouble if Group Belongs To a User and Group Has and Belongs To Many Users. However, in that case, you should be using another name for one of the assets. For example, Group could belong to a Creator, and a User would have a created_groups association. So the routes would actually be different:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;POST /users/X/created_groups?name=&quot;My Group&quot;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Which would mean create a group, where User X is the creator of that group.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;So, how do we handle this with Rails routing and controllers?&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;resources :groups do&lt;br /&gt;  resources :users, :controller =&gt; 'GroupsUser', :only =&gt; [:index, :create, :destroy]&lt;br /&gt;end&lt;br /&gt;resources :users do&lt;br /&gt;  resources :groups, :controller =&gt; 'UserGroups', :only =&gt; [:index, :create, :destroy]&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now, for user and group resources, we would use a traditional controller. For the GroupsUser and UserGroups controller, it would be a bit different.&lt;br /&gt;&lt;br /&gt;UserGroups controller:&lt;br /&gt;&lt;br /&gt;index: return all the groups this user is in&lt;br /&gt;create: create a new group, and add this user to that group&lt;br /&gt;destroy: remove this group from the user's list of groups&lt;br /&gt;&lt;br /&gt;Note we don't have:&lt;br /&gt;&lt;br /&gt;show: this is redundant with groups/show.&lt;br /&gt;update: this would update the attributes on a membership. If it's just a join there are no attributes, however this may be useful if the join has attributes (for example, role)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The most interesting action here is create:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;@user = User.find(params[:id])&lt;br /&gt;@group = Group.new(params[:group])&lt;br /&gt;Group.transaction do&lt;br /&gt;  if @group.save&lt;br /&gt;    if GroupUser.create(params[:group_user].merge{:user =&gt; @user, :group =&gt; @group})&lt;br /&gt;      # success&lt;br /&gt;    else&lt;br /&gt;      # Could not add user to group&lt;br /&gt;    end&lt;br /&gt;  else&lt;br /&gt;    # Could not create group&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Note that this controller is getting a bit dangerous because there are three logic paths. Generally, controllers will only have two logic paths: success and failure.&lt;br /&gt;&lt;br /&gt;Note also that we are merging the params[:group_user] when creating it. This is because we may want to have attributes on the GroupUser. This would all have to be in the form for posting to this action.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Technically, we are creating a group under a user. While this makes perfect sense in a belongs_to relationship, it is a little mind-bending in a many-to-many situation where the relationship is reciprocal. So, I'll end with a question. Do you think that this &quot;double action&quot; is a violation of REST?&lt;/div&gt;
&lt;h2&gt;Comments&lt;/h2&gt;
&lt;div class='comments'&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;pjb3&lt;/div&gt;
&lt;div class='content'&gt;
First of all, let me say that I am honored to be the first commenter on ngauthier.com :)&lt;br /&gt;&lt;br /&gt;Second, what I would do is push the logic of creating a group down into the controller.  The nested attributes feature of Rails gives you this automatically.  Assuming your User model looks like this:&lt;br /&gt;&lt;br /&gt;    class User &amp;lt; ActiveRecord::Base&lt;br /&gt;      has_many :group_users&lt;br /&gt;      has_many :groups, :through =&amp;gt; :group_users&lt;br /&gt;  &lt;br /&gt;      accepts_nested_attributes_for :groups&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;Then the controller goes back to having just two paths, because user.save will take care of creating the group before creating the group_user.  So when you do:&lt;br /&gt;&lt;br /&gt;    PUT /users/X/?group_attributes[][name]=&amp;quot;My Group&amp;quot;&lt;br /&gt;&lt;br /&gt;this would happen:&lt;br /&gt;&lt;br /&gt;    user.update_attributes :groups_attributes =&amp;gt; [{:name =&amp;gt; &amp;quot;My Group&amp;quot;}]&lt;br /&gt;      # =&amp;gt; INSERT INTO &amp;quot;groups&amp;quot; (&amp;quot;name&amp;quot;) VALUES (&amp;#39;My Group&amp;#39;)&lt;br /&gt;      # =&amp;gt; INSERT INTO &amp;quot;group_memberships&amp;quot; (&amp;quot;group_id&amp;quot;, &amp;quot;user_id&amp;quot;) VALUES (1, 1)&lt;/div&gt;
&lt;/div&gt;
&lt;div class='comment'&gt;
&lt;div class='author'&gt;Nick Gauthier&lt;/div&gt;
&lt;div class='content'&gt;
You also get the honor of the first reply!&lt;br /&gt;&lt;br /&gt;While that is convenient, it is not RESTful. The route you described is designed to modify the user resource, not any groups resources.&lt;br /&gt;&lt;br /&gt;Also, you&amp;#39;re going to go through &amp;quot;error hell&amp;quot; if a bunch of those groups and user attributes are invalid.&lt;br /&gt;&lt;br /&gt;Doing nested attributes through a controller is trying to squeeze two entire controllers into one. For the sake of simplicity, testing, and maintainability, I&amp;#39;d avoid it.&lt;br /&gt;&lt;br /&gt;-Nick&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</content>
  </entry>
  
</feed>
