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

  <title><![CDATA[teohm.dev]]></title>
  <link href="http://teohm.github.com/atom.xml" rel="self"/>
  <link href="http://teohm.github.com/"/>
  <updated>2013-04-22T22:02:22+08:00</updated>
  <id>http://teohm.github.com/</id>
  <author>
    <name><![CDATA[Huiming Teo (teohm)]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Chef cookbooks for busy Ruby developers]]></title>
    <link href="http://teohm.github.com/blog/2013/04/17/chef-cookbooks-for-busy-ruby-developers/"/>
    <updated>2013-04-17T23:06:00+08:00</updated>
    <id>http://teohm.github.com/blog/2013/04/17/chef-cookbooks-for-busy-ruby-developers</id>
    <content type="html"><![CDATA[<p>Have you ever <strong>setup a Rails production environment from scratch, by
hand</strong>? If you had, I share your pain every time when a new project
started.</p>

<p>The process is often repetitive. To me, it seems to be a waste to do it
manually every time. It also consumes time and attention. It would be
great if I could spend them on tasks that bring more values to clients.</p>

<p>To minimize such waste, I have written two Chef cookbooks to <strong>automate
the process</strong>:</p>

<ul>
<li><a href="https://github.com/teohm/rackbox-cookbook"><strong>rackbox</strong></a>  - to provision <strong>rack-based web server</strong> (Nginx as front server, Unicorn and Passenger as upstream app servers, <code>rbenv</code> as ruby version manager).</li>
<li><a href="https://github.com/teohm/databox-cookbook"><strong>databox</strong></a> - to provision <strong>database server</strong> (supports MySQL and PostgreSQL).</li>
</ul>


<h2>Getting started</h2>

<p>In this post, I will show you a <strong>step-by-step guide</strong> on how to use the
cookbooks together with
<a href="https://github.com/matschaffer/knife-solo"><code>knife-solo</code></a> to provision a
remote server in 4 steps:</p>

<ol>
<li>setup Chef Solo environment</li>
<li>modify config file</li>
<li>provision remote server</li>
<li>tweak Capistrano <code>deploy.rb</code></li>
</ol>


<p>A working example in also available at
<a href="https://github.com/teohm/kitchen-example">teohm/kitchen-example</a>.</p>

<h2>1. Setup Chef Solo environment</h2>

<ul>
<li>Install Chef Solo tools on local machine.</li>
<li>Download Chef cookbooks to local machine.</li>
<li>Install <code>chef-solo</code> on remote server.</li>
</ul>


<h3>Install Chef Solo tools</h3>

<p>Let&#8217;s create a new directory,</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>mkdir chef-kitchen
</span><span class='line'>cd chef-kitchen</span></code></pre></td></tr></table></div></figure>


<p>and a <code>Gemfile</code>.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>source "https://rubygems.org"
</span><span class='line'>
</span><span class='line'>gem "knife-solo", "&gt;= 0.3.0pre3"
</span><span class='line'>gem "berkshelf"</span></code></pre></td></tr></table></div></figure>


<p>I recommend <code>knife-solo &gt;= 0.3</code> as it includes a few <a href="https://github.com/matschaffer/knife-solo/blob/master/CHANGELOG.md#changes-and-new-features">major fixes and
improvements</a>.</p>

<p>Now, install the ruby gems.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>bundle install</span></code></pre></td></tr></table></div></figure>


<p>Finally, setup a kitchen directory structure with <code>knife-solo</code>.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>bundle exec knife solo init .</span></code></pre></td></tr></table></div></figure>


<h3>Download Chef cookbooks</h3>

<p>I use <a href="http://berkshelf.com/">Berkshelf</a> to manage cookbooks. So we need a <code>Berksfile</code>,</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>site :opscode
</span><span class='line'>
</span><span class='line'>cookbook "runit", "&gt;= 1.1.2"  # HACK: force-use this version
</span><span class='line'>cookbook "databox"
</span><span class='line'>cookbook "rackbox"</span></code></pre></td></tr></table></div></figure>


<p>(I added a hack here to force <code>berkshelf</code> to use <code>runit 1.1.2</code> required
by <code>rackbox</code>. Still looking for a better solution.)</p>

<p>We can now download cookbooks with <code>berks install</code>.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>bundle exec berks install --path cookbooks/</span></code></pre></td></tr></table></div></figure>


<h3>Install <code>chef-solo</code> on remote server</h3>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>bundle exec knife solo prepare testbox</span></code></pre></td></tr></table></div></figure>


<p>In this example, <code>testbox</code> is a host I setup in my <code>~/.ssh/config</code>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>Host testbox
</span><span class='line'>  User ubuntu
</span><span class='line'>  Hostname ec2-51-221-13-121.ap-southeast-1.compute.amazonaws.com
</span><span class='line'>  IdentityFile ~/.ssh/testbox_ec2.pem</span></code></pre></td></tr></table></div></figure>


<h2>2. Customize config file</h2>

<ul>
<li>Download config example</li>
<li>Customize config file</li>
</ul>


<h3>Download config example</h3>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>curl https://raw.github.com/teohm/kitchen-example/master/nodes/host.json.example --output nodes/testbox.json</span></code></pre></td></tr></table></div></figure>


<h3>Modify config file (JSON)</h3>

<p>The config file starts with a <code>run_list</code>. You specify a list of cookbook
recipes here. Chef will run them in the same order in this list.</p>

<p>It is followed by cookbook attributes. You can modify these attributes.
A full reference of attributes are described in each cookbook&#8217;s README
(see <a href="https://github.com/teohm/appbox-cookbook#attributes">appbox</a>,
<a href="https://github.com/teohm/databox-cookbook#attributes">databox</a>,
<a href="https://github.com/teohm/rackbox-cookbook#attributes">rackbox</a>).</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>{
</span><span class='line'>  "run_list": [
</span><span class='line'>    "databox",
</span><span class='line'>    "rackbox"
</span><span class='line'>  ],
</span><span class='line'>  "appbox": {
</span><span class='line'>    "deploy_keys": ["ssh-rsa 5bnmu23890fghghjk"],
</span><span class='line'>    "admin_keys": ["ssh-rsa 456789fghjkvbn567"]
</span><span class='line'>  },
</span><span class='line'>  "databox": {
</span><span class='line'>    "db_root_password": "welcome!",
</span><span class='line'>    "databases": {
</span><span class='line'>      "mysql": [
</span><span class='line'>        { "username": "app1",
</span><span class='line'>          "password": "app1",
</span><span class='line'>          "database_name": "app1_production" }
</span><span class='line'>      ],
</span><span class='line'>      "postgresql": [
</span><span class='line'>        { "username": "app2",
</span><span class='line'>          "password": "app2",
</span><span class='line'>          "database_name": "app2_production" }
</span><span class='line'>      ]
</span><span class='line'>    }
</span><span class='line'>  },
</span><span class='line'>  "rackbox": {
</span><span class='line'>    "ruby": {
</span><span class='line'>      "versions": ["1.9.3-p385", "1.9.2-p320"],
</span><span class='line'>      "global_version": "1.9.3-p385"
</span><span class='line'>    },
</span><span class='line'>    "apps": {
</span><span class='line'>      "unicorn": [
</span><span class='line'>        { "appname": "app1",
</span><span class='line'>          "hostname": "app1.test.com" }
</span><span class='line'>      ],
</span><span class='line'>      "passenger": [
</span><span class='line'>        { "appname": "app2",
</span><span class='line'>          "hostname": "app2.test.com" }
</span><span class='line'>      ]
</span><span class='line'>    }
</span><span class='line'>  }
</span><span class='line'>}
</span></code></pre></td></tr></table></div></figure>


<h2>3. Provision remote server</h2>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>bundle exec knife solo cook testbox</span></code></pre></td></tr></table></div></figure>


<p>It uploads the kitchen directory and runs <code>chef-solo</code> on the remote
server. Chef-solo will then takeover and execute the run list to setup
everything.</p>

<h3>What do we get at this point?</h3>

<p>Basically, it&#8217;s done!</p>

<p>We have a <strong>full-stack, rack-based server</strong> with:</p>

<ul>
<li>3 user accounts (deploy, devops, apps)</li>
<li><code>rbenv</code> as ruby version manager</li>
<li><code>nginx</code> as front-server</li>
<li><code>unicorn</code>, <code>passenger-standalone</code> as upstream app servers, managed by <code>runit</code></li>
<li><code>postgresql</code>, <code>mysql</code> installed and databases created</li>
<li>all apps will be stored in <code>/home/apps/</code></li>
</ul>


<h2>4. Tweak Capistrano deploy.rb</h2>

<p>Now, it&#8217;s ready to deploy a Rack-based app to the remote server!</p>

<p>I have two example Rails apps available on Github:</p>

<ul>
<li><a href="https://github.com/teohm/sample-app1">teohm/sample-app1</a> runs on unicorn,</li>
<li><a href="https://github.com/teohm/sample-app2">teohm/sample-app2</a> runs on passenger-standalone.</li>
</ul>


<p>There are a few <strong>minor tweaks required in Capistrano <code>deploy.rb</code></strong>, as listed below.</p>

<p>I will explain the tweaks in details next time. Meanwhile, check out the complete working examples at: <a href="https://github.com/teohm/sample-app1/blob/master/config/deploy.rb">app1/config/deploy.rb</a> and <a href="https://github.com/teohm/sample-app2/blob/master/config/deploy.rb">app2/config/deploy.rb</a></p>

<h3>Login as <code>deploy</code> user</h3>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>set :user, "deploy"</span></code></pre></td></tr></table></div></figure>


<h3>Deploy to <code>/home/apps</code></h3>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>set :deploy_to, "/home/apps/#{application}"</span></code></pre></td></tr></table></div></figure>


<h3>Load <code>rbenv</code> in Capistrano</h3>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>default_run_options[:shell] = '/bin/bash --login'</span></code></pre></td></tr></table></div></figure>


<h3>Run bundler with <code>--binstubs</code></h3>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>require 'bundler/capistrano'
</span><span class='line'>set :bundle_flags, "--deployment --binstubs"
</span><span class='line'>set :bundle_without, [:test, :development, :deploy]</span></code></pre></td></tr></table></div></figure>


<h3>Restart app with <code>runit sv</code></h3>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>namespace :deploy do
</span><span class='line'>  task :start do
</span><span class='line'>    run "sudo sv up app1"
</span><span class='line'>  end
</span><span class='line'>  task :stop do
</span><span class='line'>    run "sudo sv down app1"
</span><span class='line'>  end
</span><span class='line'>  task :restart, :roles =&gt; :app, :except =&gt; { :no_release =&gt; true } do
</span><span class='line'>    run "sudo sv restart app1"
</span><span class='line'>  end
</span><span class='line'>end
</span></code></pre></td></tr></table></div></figure>


<h2>Feedback</h2>

<p>If you are interested on using the cookbooks, or have an idea/feedback/question about this topic, feel free to drop me (<a href="http://twitter.com/teohm">@teohm</a>) a message. Pull requests and issue reports are definitely welcomed!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Reload required files in Rails]]></title>
    <link href="http://teohm.github.com/blog/2013/01/10/reload-required-files-in-rails/"/>
    <updated>2013-01-10T12:34:00+08:00</updated>
    <id>http://teohm.github.com/blog/2013/01/10/reload-required-files-in-rails</id>
    <content type="html"><![CDATA[<p>When a Rails project grows, I often notice the need to <strong>refactor domain logic into a separate module, isolated from Rails framework</strong>.</p>

<p>The isolated module will still stay in the main Rails app codebase, but can be easily packaged as a Ruby gem, tested separately, and used in other related applications.</p>

<h2>Requirements</h2>

<p>During the refactoring, we want to:</p>

<ol>
<li><p><strong>Use <code>require</code> to load the module like a normal gem</strong>. If possible, no dependency on Rails autoload features such as<code>require_dependency</code> and <code>autoload_paths</code>.</p></li>
<li><p><strong>Edit the module without restarting server during development</strong>. In other words, we need to find a way to <strong>reload the module on every request</strong>.</p></li>
</ol>


<h2>Reload <code>require</code> files</h2>

<p>After some research, I found a <a href="http://timcardenas.com/automatically-reload-gems-in-rails-327-on-eve"><strong>working solution</strong></a> by Timothy Cardenas:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>ActionDispatch::Callbacks.to_prepare do
</span><span class='line'>  if Object.const_defined?("Module1")
</span><span class='line'>    Object.send(:remove_const, "Module1")
</span><span class='line'>  end
</span><span class='line'>  $".delete_if {|s| s.include?('module1') }
</span><span class='line'>  require 'module1'
</span><span class='line'>end</span></code></pre></td></tr></table></div></figure>


<p>What it does is, before each request,</p>

<ol>
<li>Unload the top-level module.</li>
<li>Un-require all required files from the module.</li>
<li>Re-require the top-level module.</li>
</ol>


<h2>An extra step in Rails 3.2</h2>

<p>In Rails 3.2, <code>ActionDispatch::Callbacks.to_prepare</code> has a slightly different behavior. It will run before a request <strong>only if a watchable file is modified</strong>.</p>

<p>You need to specify your own <a href="http://api.rubyonrails.org/classes/Rails/Railtie/Configuration.html#method-i-watchable_dirs">watchable files</a>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class=''><span class='line'># watch all .rb files recursively under modules/module1/ dir
</span><span class='line'>config.watchable_dirs['modules/module1'] = [:rb]</span></code></pre></td></tr></table></div></figure>


<h2>Introduce <code>require_reloader</code> gem</h2>

<p>Before bundling the solution into a gem, I did a search on RubyGems.org and found Colin Young&#8217;s <a href="https://github.com/colinyoung/gem_reloader">gem_reloader</a>. It&#8217;s based on Timy&#8217;s solution as well. I forked it and started playing around.</p>

<p>In the end, I made some major changes to include Rails 3.2 support, some fixes and new features.</p>

<p>So I decided to <strong>release it as a new Ruby gem: <a href="https://github.com/teohm/require_reloader">require_reloader</a></strong>.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class=''><span class='line'># config/environments/development.rb
</span><span class='line'>YourApp::Application.configure do
</span><span class='line'>  ...
</span><span class='line'>  RequireReloader.watch :module1,
</span><span class='line'>    path: 'modules/module1'
</span><span class='line'>end</span></code></pre></td></tr></table></div></figure>


<p>Currently it supports Rails 3, including 3.1 and 3.2.</p>

<p>If you are working on something similar, looking forward for your feedbacks and pull requests. It is not tested on Rails 2 yet, so pull requests are definitely welcomed!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Start Using Ruby % (Percent) Notation]]></title>
    <link href="http://teohm.github.com/blog/2012/10/15/start-using-ruby-percent-notation/"/>
    <updated>2012-10-15T18:04:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/10/15/start-using-ruby-percent-notation</id>
    <content type="html"><![CDATA[<p>If you seldom use Ruby percent (%) notation in daily work, here&#8217;s a
<strong>quick summary</strong> of what I picked up recently.</p>

<h2>Delimiter allows any non-alphanum</h2>

<p>You can use any <strong>non alpha-numeric character</strong> as delimiter:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="sx">%(any alpha-numeric)</span>
</span><span class='line'><span class="sx">%[char can be]</span>
</span><span class='line'><span class="sx">%%used as%</span>
</span><span class='line'><span class="sx">%!delimiter\!!</span> <span class="c1"># escape &#39;!&#39; literal</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Bracket pairs no need to escape</h2>

<p><strong>No need to escape bracket pairs</strong>, even when <strong>nested</strong>.
You can escape, but will need to escape both open and close bracket.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="sx">%( (pa(re(nt)he)sis) )</span> <span class="c1">#=&gt; &quot;(pa(re(nt)he)sis)&quot;</span>
</span><span class='line'><span class="sx">%[ [square bracket] ]</span>  <span class="c1">#=&gt; &quot;[square bracket]&quot;</span>
</span><span class='line'><span class="sx">%{ {curly bracket} }</span>   <span class="c1">#=&gt; &quot;{curly bracket}&quot;</span>
</span><span class='line'><span class="sx">%&lt; &lt;pointy bracket&gt; &gt;</span>  <span class="c1">#=&gt; &quot;&lt;pointy bracket&gt;&quot;</span>
</span><span class='line'><span class="sx">%&lt; \&lt;this works as well\&gt; &gt;</span>  <span class="c1">#=&gt; &quot;&lt;this works as well&gt;&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Modifiers for String, Regex, Array, Symbol, Shell command</h2>

<p>We often use % notation to <strong>create String and Array</strong> literals. But it
also supports <strong>Symbol, Regex and shell command</strong>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="sx">%(interpolated string (</span><span class="si">#{</span> <span class="s2">&quot;default&quot;</span> <span class="si">}</span><span class="sx">))</span>
</span><span class='line'>  <span class="c1">#=&gt; &quot;interpolated string (default)&quot;</span>
</span><span class='line'><span class="sx">%Q(interpolated string (</span><span class="si">#{</span> <span class="s2">&quot;default&quot;</span> <span class="si">}</span><span class="sx">))</span>
</span><span class='line'>  <span class="c1">#=&gt; &quot;interpolated string (default)&quot;</span>
</span><span class='line'><span class="sx">%q(non-interpolated string)</span>
</span><span class='line'>  <span class="c1">#=&gt; &quot;non-interpolated string&quot;</span>
</span><span class='line'><span class="sr">%r(</span><span class="si">#{</span> <span class="s2">&quot;interpolated&quot;</span> <span class="si">}</span><span class="sr"> regexp)i</span>
</span><span class='line'>  <span class="c1">#=&gt; /interpolated regexp/i</span>
</span><span class='line'><span class="sx">%w(non-interpolated\ string  separated\ by\ whitespaces)</span>
</span><span class='line'>  <span class="c1">#=&gt; [&#39;non-interpolated string&#39;, &#39;separated by whitespaces&#39;]</span>
</span><span class='line'><span class="sx">%W(interpolated\ string </span><span class="si">#{</span> <span class="s2">&quot;separated by whitespaces&quot;</span> <span class="si">}</span><span class="sx">)</span>
</span><span class='line'>  <span class="c1">#=&gt; [&#39;interpolated string&#39;, &#39;separated by whitespaces&#39;]</span>
</span><span class='line'><span class="sx">%s(non-interpolated symbol)</span>
</span><span class='line'>  <span class="c1">#=&gt; :&#39;non-interpolated symbol&#39;</span>
</span><span class='line'><span class="sx">%x(echo </span><span class="si">#{</span> <span class="s2">&quot;interpolated shell command&quot;</span> <span class="si">}</span><span class="sx">)</span>
</span><span class='line'>  <span class="c1">#=&gt; &quot;interpolated shell command\n&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here&#8217;s some <a href="https://github.com/teohm/a-dip-in-ruby/blob/master/spec/percent_notation_spec.rb">% notation examples written in minitest</a> in case you interested.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ruby idiom to ensure variable is Array]]></title>
    <link href="http://teohm.github.com/blog/2012/10/02/ruby-idiom-to-ensure-variable-is-array/"/>
    <updated>2012-10-02T23:27:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/10/02/ruby-idiom-to-ensure-variable-is-array</id>
    <content type="html"><![CDATA[<p><strong>Stop</strong> doing this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">arry</span> <span class="o">=</span> <span class="n">input</span> <span class="o">||</span> <span class="o">[]</span>  <span class="c1"># handle input == nil</span>
</span><span class='line'><span class="n">arry</span> <span class="o">=</span> <span class="o">[</span><span class="n">input</span><span class="o">]</span> <span class="k">unless</span> <span class="n">arry</span><span class="o">.</span><span class="n">kind_of?</span><span class="p">(</span><span class="nb">Array</span><span class="p">)</span>  <span class="c1"># handle single value object</span>
</span><span class='line'>
</span><span class='line'><span class="n">arry</span><span class="o">.</span><span class="n">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">item</span><span class="o">|</span>
</span><span class='line'>  <span class="c1">#process item</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>In Ruby, you should use
<a href="http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-Array">Kernel#Array</a>
to <strong>convert the variable into an array object</strong>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="nb">Array</span><span class="p">(</span><span class="n">input</span><span class="p">)</span><span class="o">.</span><span class="n">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">item</span><span class="o">|</span>
</span><span class='line'>  <span class="c1"># process item</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="c1"># Array(nil)     # =&gt; []</span>
</span><span class='line'><span class="c1"># Array(&quot;foo&quot;)   # =&gt; [&quot;foo&quot;]</span>
</span><span class='line'><span class="c1"># Array([1,2,3]) # =&gt; [1,2,3]</span>
</span></code></pre></td></tr></table></div></figure>


<p><a href="https://github.com/teohm/a-dip-in-ruby/blob/master/spec/kernel_array_spec.rb">More usage examples</a> written in minitest.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Objective-C Collection Operators]]></title>
    <link href="http://teohm.github.com/blog/2012/09/24/objective-c-collection-operators/"/>
    <updated>2012-09-24T13:52:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/09/24/objective-c-collection-operators</id>
    <content type="html"><![CDATA[<h2>Calculate average - a shorter way</h2>

<p>When you have a collection of <code>Transactions</code> objects and want to
calculate its average amount, instead of looping through the collection
like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='objective-c'><span class='line'><span class="kt">double</span> <span class="n">sum</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'><span class="k">for</span> <span class="p">(</span><span class="n">Transaction</span> <span class="o">*</span><span class="n">transaction</span> <span class="k">in</span> <span class="n">transactions</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="n">sum</span> <span class="o">+=</span> <span class="p">[</span><span class="n">transaction</span><span class="p">.</span><span class="n">amount</span> <span class="n">doubleValue</span><span class="p">];</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="n">NSNumber</span> <span class="o">*</span><span class="n">avg</span> <span class="o">=</span> <span class="p">[</span><span class="n">NSNumber</span> <span class="nl">numberWithDouble:</span><span class="p">(</span><span class="n">sum</span> <span class="o">/</span> <span class="p">[</span><span class="n">transactions</span> <span class="n">count</span><span class="p">])];</span>
</span></code></pre></td></tr></table></div></figure>


<p>you can <strong>reduce the loop to 1 line of code</strong>, using
<a href="http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html">Objective-C key-value coding</a>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='objective-c'><span class='line'><span class="n">NSNumber</span> <span class="o">*</span><span class="n">avg</span> <span class="o">=</span> <span class="p">[</span><span class="n">transactions</span> <span class="nl">valueForKeyPath:</span><span class="s">@&quot;@avg.amount&quot;</span><span class="p">];</span>
</span></code></pre></td></tr></table></div></figure>


<p>Currently, there is a <strong>fixed set</strong> of collection operators:</p>

<ul>
<li>Simple collection operators (<code>@avg</code>, <code>@count</code>, <code>@sum</code>, <code>@max</code>, <code>@min</code>)</li>
<li>Object operators (<code>@distinctUnionOfObjects</code>, <code>@unionOfObjects</code>)</li>
<li>Array and set operators (<code>@distinctUnionOfArrays</code>, <code>@unionOfArrays</code>)</li>
</ul>


<p>For details, refer to more
<a href="http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html">usage</a> <a href="https://github.com/teohm/a-dip-in-objective-c/blob/master/ADipInObjectiveCTests/CollectionOperatorTests.m">examples</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Breaking ARC retain cycle in Objective-C blocks]]></title>
    <link href="http://teohm.github.com/blog/2012/09/03/breaking-arc-retain-cycle-in-objective-c-blocks/"/>
    <updated>2012-09-03T17:50:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/09/03/breaking-arc-retain-cycle-in-objective-c-blocks</id>
    <content type="html"><![CDATA[<p>In a recent client project, we noticed its iOS app often <strong>received low memory
warning</strong>. The iOS app is developed with ARC-enabled (Automatic Reference Counting).</p>

<p>When profiled the app using <strong>Instruments > Allocations</strong>, we found that
a lot of unused ViewController objects were not released from memory.</p>

<h2>Retain Cycle</h2>

<p>The codebase uses a lot of <strong>Objective-C blocks</strong> as shown below, and
<code>self</code> is often being called within the blocks:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='objective-c'><span class='line'><span class="k">@interface</span> <span class="nc">DetailPageViewController</span> : <span class="nc">UIViewController</span>
</span><span class='line'><span class="k">@property</span><span class="p">(</span><span class="n">nonatomic</span><span class="p">,</span> <span class="n">strong</span><span class="p">)</span> <span class="n">UIButton</span> <span class="o">*</span><span class="n">backButton</span><span class="p">;</span>
</span><span class='line'><span class="p">...</span>
</span><span class='line'><span class="k">@end</span>
</span><span class='line'>
</span><span class='line'><span class="err">@</span><span class="n">implementation</span> <span class="n">DetailPageViewController</span>
</span><span class='line'><span class="k">@synthesize</span> <span class="n">backButton</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">loadView</span> <span class="p">{</span>
</span><span class='line'>  <span class="p">...</span>
</span><span class='line'>  <span class="p">[</span><span class="n">self</span><span class="p">.</span><span class="n">doneButton</span> <span class="nl">onTouch:</span><span class="o">^</span><span class="p">(</span><span class="kt">id</span> <span class="n">sender</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="p">[</span><span class="n">self</span> <span class="n">doSomething</span><span class="p">];</span>
</span><span class='line'>    <span class="n">self</span><span class="p">.</span><span class="n">isDone</span> <span class="o">=</span> <span class="n">YES</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}];</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="p">...</span>
</span><span class='line'><span class="k">@end</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this example code, the controller object holds a <strong>strong reference to
<code>doneButton</code> object</strong>. But because <code>doneButton onTouch:</code> block is calling
<code>self</code>, now the button object <strong>holds a strong reference back to the controller
object</strong>.</p>

<p>When object A points strongly to object B, and B points strongly to A, a
<a href="http://cocoawithlove.com/2009/07/rules-to-avoid-retain-cycles.html"><strong>retain cycle</strong></a> is created,
and both objects cannot be released from memory.</p>

<h2>Use Lifetime Qualifiers</h2>

<p><a href="http://developer.apple.com/library/mac/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW9">Apple Developer&#8217;s guide on ARC transition</a> suggested a few ways to <strong>break the retain cycle using different lifetime
qualifiers</strong>. It is definitely a <strong>must read</strong> for iOS development.</p>

<p>If your app is targeted for iOS 5, you can use <code>__weak</code> lifetime qualifier to break the cycle:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='objective-c'><span class='line'><span class="k">@interface</span> <span class="nc">DetailPageViewController</span> : <span class="nc">UIViewController</span>
</span><span class='line'><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">loadView</span> <span class="p">{</span>
</span><span class='line'>  <span class="p">...</span>
</span><span class='line'>  <span class="n">__weak</span> <span class="n">DetailPageViewController</span> <span class="o">*</span><span class="n">controller</span> <span class="o">=</span> <span class="n">self</span><span class="p">;</span>
</span><span class='line'>  <span class="p">[</span><span class="n">self</span><span class="p">.</span><span class="n">doneButton</span> <span class="nl">onTouch:</span><span class="o">^</span><span class="p">(</span><span class="kt">id</span> <span class="n">sender</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="p">[</span><span class="n">controller</span> <span class="n">doSomething</span><span class="p">];</span>
</span><span class='line'>    <span class="n">controller</span><span class="p">.</span><span class="n">isDone</span> <span class="o">=</span> <span class="n">YES</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}];</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="k">@end</span>
</span></code></pre></td></tr></table></div></figure>


<p>Because we are using <code>__weak</code> qualifier, <code>doneButton onTouch:</code> block
only has <strong>a weak reference to the controller object</strong>. Now, the controller
object can be released from memory when its reference count drops to 0.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mac Tips: Use Caps Lock as Control key]]></title>
    <link href="http://teohm.github.com/blog/2012/04/08/mac-tips-use-caps-lock-as-control-key/"/>
    <updated>2012-04-08T10:20:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/04/08/mac-tips-use-caps-lock-as-control-key</id>
    <content type="html"><![CDATA[<p>After using <a href="http://tmux.sourceforge.net/">tmux</a>, I start using Control
key a lot often. I decided to move my Control key up to the home row,
by assigning it to <strong>Caps Lock</strong>.</p>

<p>For Mac users, open <strong>System Preferences > Keyboard</strong>, choose <strong>Keyboard</strong> tab.
Click button <strong>Modifier Keys..</strong> and change <strong>Caps Lock Key:</strong> to <strong>^ Control</strong>.</p>

<p><img src="http://teohm.github.com/images/mac-tips/caps-lock-as-control-key.png" title="A screenshot of Key Modifier Keys dialog" alt="A screenshot of Key Modifier Key dialog"></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mac Tips: Change default application for a file type]]></title>
    <link href="http://teohm.github.com/blog/2012/04/07/mac-tips-change-default-application-for-a-file-type/"/>
    <updated>2012-04-07T18:46:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/04/07/mac-tips-change-default-application-for-a-file-type</id>
    <content type="html"><![CDATA[<p>To switch the default application for file type,
right-click the file, select <strong>Get Info</strong> and change the application in
<strong>Open With</strong> section.</p>

<p>Remember, remember.. click <strong>Change All&#8230;</strong> button to <strong>apply the changes to <em>all</em>
files</strong>. It seems obvious, but took me a while to figure this out. :)</p>

<p><img src="http://teohm.github.com/images/mac-tips/default-application-for-file-type.png" title="A screenshot of Get Info dialog" alt="A screenshot of Get Info dialog"></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mac Tips: Turn on remote login (SSH server)]]></title>
    <link href="http://teohm.github.com/blog/2012/04/07/mac-tips-turn-on-remote-login-ssh-server/"/>
    <updated>2012-04-07T15:12:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/04/07/mac-tips-turn-on-remote-login-ssh-server</id>
    <content type="html"><![CDATA[<p>Enable SSH server on Mac OSX is surprisingly easy. Open <strong>System Preferences >
Sharing</strong>, and turn on <strong>Remote Login</strong>. You can futher restrict which user can
login via SSH on the same screen.</p>

<p><img src="http://teohm.github.com/images/mac-tips/remote-login.png" title="A screenshot Sharing dialog box." alt="A screenshot Sharing dialog box."></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using sshuttle in daily work]]></title>
    <link href="http://teohm.github.com/blog/2012/04/01/using-sshuttle-in-daily-work/"/>
    <updated>2012-04-01T13:13:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/04/01/using-sshuttle-in-daily-work</id>
    <content type="html"><![CDATA[<p>I was first introduced to <a href="https://github.com/apenwarr/sshuttle"><strong>sshuttle</strong></a> by Sooyoung (<a href="https://twitter.com/#!/5ooyoung">@5ooyoung</a>) in <a href="http://favoritemedium.com/">Favorite Medium</a>
as a workaround to The Great Firewall in China.</p>

<p>Since then, it has become my <strong>light-weight network tunneling tool</strong> in daily work.</p>

<h2>Install sshuttle</h2>

<p>The installation is easy now. You can install it through Mac OSX Homebrew, or <a href="http://packages.ubuntu.com/precise/sshuttle">Ubuntu apt-get</a>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>brew install sshuttle
</span></code></pre></td></tr></table></div></figure>


<h2>I use sshuttle to..</h2>

<h3>1. Tunnel all traffic</h3>

<p>This is the first command I learned.
It <strong>forwards all TCP traffic and DNS requests to a remote SSH server</strong>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>sshuttle --dns -vr ssh_server 0/0
</span></code></pre></td></tr></table></div></figure>


<p>Just like <code>ssh</code>, you can use any server specified in <code>~/.ssh/config</code>.
The <code>-v</code> flag means verbose mode.</p>

<p>Besides TCP and DNS, currently <code>sshuttle</code> <strong>does not forward other requests
<em>such as</em> UDP, ICMP ping etc</strong>.</p>

<h3>2. Tunnel all traffic, but exclude some</h3>

<p>You can <strong>exclude certain TCP traffic using <code>-x</code> option</strong>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>sshuttle --dns -vr ssh_server -x 121.9.204.0/24 -x 61.135.196.21 0/0
</span></code></pre></td></tr></table></div></figure>


<p>For instance, when I am in China, I don&#8217;t want to tunnel
<a href="http://youku.com">Youku.com</a> traffic to a foreign server,
because its movie streaming service is only available within China.</p>

<p>In this case, I use <code>-x</code> option to exclude Youku.com IP addresses.</p>

<h3>3. Tunnel only certain traffic</h3>

<p>To tunnel only certain TCP traffic, <strong>specify the IP addresses
or <a href="http://www.subnet-calculator.com/cidr.php">IP ranges</a> that need tunneling</strong>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>sshuttle -vr ssh_server 121.9.204.0/24 61.135.196.21
</span></code></pre></td></tr></table></div></figure>


<p>This command comes in handy, whenever I need to test an app feature (e.g. Netflix movie streaming)
which only available in certain countries, or to bypass ISP faulty caches.</p>

<h3>4. VPN to office network</h3>

<p>I seldom do VPN, but all you need is <strong>the remote SSH server with <code>-NH</code> flags turned on</strong>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>sshuttle -NHvr office_ssh_server
</span></code></pre></td></tr></table></div></figure>


<p><code>-N</code> flag tells sshuttle to figure out by itself the IP subnets to forward,
and <code>-H</code> flag to scan for hostnames within remote subnets and store them temporarily in <code>/etc/hosts</code>.</p>

<h2>IP addresses.. troublesome?</h2>

<p>Well, I try not to deal with IP addresses manually. So I wrote a few
<strong><a href="https://github.com/teohm/dotfiles/blob/master/.bashrc.d/sshuttle_helpers">sshuttle helpers</a>
(<code>tnl</code>, <code>tnlbut</code>, <code>tnlonly</code>, <code>vpnto</code>)</strong> that allow me to <strong>use domain names instead of IP addresses</strong>:</p>

<h3>Tunnel all traffic</h3>

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


<h3>Tunnel all traffic, but exclude some</h3>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>tnlbut youku.com weibo.com
</span></code></pre></td></tr></table></div></figure>


<h3>Tunnel only certain traffic</h3>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>tnlonly netflix.com movies.netflix.com
</span></code></pre></td></tr></table></div></figure>


<h3>VPN to office network</h3>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>vpnto office_ssh_server
</span></code></pre></td></tr></table></div></figure>


<p>The script is available on <a href="https://github.com/teohm/dotfiles/blob/master/.bashrc.d/sshuttle_helpers">my GitHub repo</a>.
You can load it into your <code>~/.bashrc</code>. <strong>To override the default tunneling SSH server</strong> in the script:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="nv">TNL_SERVER</span><span class="o">=</span>user@another_server tnl
</span></code></pre></td></tr></table></div></figure>



]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[UTF-8 param name issue in Rails multipart form]]></title>
    <link href="http://teohm.github.com/blog/2012/03/27/utf-8-param-name-issue-in-rails-multipart-form/"/>
    <updated>2012-03-27T21:36:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/03/27/utf-8-param-name-issue-in-rails-multipart-form</id>
    <content type="html"><![CDATA[<p>I first stumbled upon this issue when <a href="http://thekindof.me">Yasith</a>
(<a href="https://twitter.com/meaningful">@meaningful</a>) showed me a strange bug
in a Rails project. Here&#8217;s what happened:</p>

<h2>Issue</h2>

<p>When submit a multipart form that contains <strong>Unicode parameter name</strong> e.g.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;form</span> <span class="na">method=</span><span class="s">&quot;post&quot;</span> <span class="na">enctype=</span><span class="s">&quot;multipart/form-data&quot;</span> <span class="na">action=</span><span class="s">&quot;&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>  <span class="nt">&lt;input</span> <span class="na">name=</span><span class="s">&quot;Iñtërnâtiônàlizætiøn_name&quot;</span>
</span><span class='line'>         <span class="na">value=</span><span class="s">&quot;Iñtërnâtiônàlizætiøn_value&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'><span class="nt">&lt;/form&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Rails controller returns the param value <code>"Iñtërnâtiônàlizætiøn_value"</code> as expected.</p>

<p>But the <strong>param name becomes</strong>:
<code>"I\xC3\xB1t\xC3\xABrn\xC3\xA2ti\xC3\xB4n\xC3\xA0liz\xC3\xA6ti\xC3\xB8n_name"</code>.</p>

<p>It makes life miserable, if you are not expecting this to happen:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">params</span><span class="o">[</span><span class="s2">&quot;Iñtërnâtiônàlizætiøn_name&quot;</span><span class="o">]</span> <span class="c1"># =&gt; nil</span>
</span><span class='line'><span class="n">params</span><span class="o">[</span><span class="s2">&quot;I</span><span class="se">\xC3\xB1</span><span class="s2">t</span><span class="se">\xC3\xAB</span><span class="s2">rn</span><span class="se">\xC3\xA2</span><span class="s2">ti</span><span class="se">\xC3\xB4</span><span class="s2">n</span><span class="se">\xC3\xA0</span><span class="s2">liz</span><span class="se">\xC3\xA6</span><span class="s2">ti</span><span class="se">\xC3\xB8</span><span class="s2">n_name&quot;</span><span class="o">]</span> <span class="c1"># =&gt; &quot;Iñtërnâtiônàlizætiøn_value&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<h2>What happened?</h2>

<p>When <a href="https://github.com/rack/rack/blob/master/lib/rack/multipart/parser.rb"><strong>Rack</strong></a>
returns multipart form data to Rails, it returns:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="p">{</span> <span class="s2">&quot;I</span><span class="se">\xC3\xB1</span><span class="s2">t</span><span class="se">\xC3\xAB</span><span class="s2">rn</span><span class="se">\xC3\xA2</span><span class="s2">ti</span><span class="se">\xC3\xB4</span><span class="s2">n</span><span class="se">\xC3\xA0</span><span class="s2">liz</span><span class="se">\xC3\xA6</span><span class="s2">ti</span><span class="se">\xC3\xB8</span><span class="s2">n_name&quot;</span> <span class="o">=&gt;</span>
</span><span class='line'>  <span class="s2">&quot;I</span><span class="se">\xC3\xB1</span><span class="s2">t</span><span class="se">\xC3\xAB</span><span class="s2">rn</span><span class="se">\xC3\xA2</span><span class="s2">ti</span><span class="se">\xC3\xB4</span><span class="s2">n</span><span class="se">\xC3\xA0</span><span class="s2">liz</span><span class="se">\xC3\xA6</span><span class="s2">ti</span><span class="se">\xC3\xB8</span><span class="s2">n_value&quot;</span> <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>However, <code>ActionDispatch::Http::Parameters#encode_params</code> in <a href="https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/http/parameters.rb"><strong>Rails</strong></a>
decided to <strong> <em>only</em> encode parameter values</strong>, but <em>not</em> parameter names. <strong>As a result, we get:</strong></p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="p">{</span> <span class="s2">&quot;I</span><span class="se">\xC3\xB1</span><span class="s2">t</span><span class="se">\xC3\xAB</span><span class="s2">rn</span><span class="se">\xC3\xA2</span><span class="s2">ti</span><span class="se">\xC3\xB4</span><span class="s2">n</span><span class="se">\xC3\xA0</span><span class="s2">liz</span><span class="se">\xC3\xA6</span><span class="s2">ti</span><span class="se">\xC3\xB8</span><span class="s2">n_name&quot;</span> <span class="o">=&gt;</span>
</span><span class='line'>  <span class="s2">&quot;Iñtërnâtiônàlizætiøn_value&quot;</span> <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Solutions?</h2>

<ol>
<li><strong>Don&#8217;t use Unicode param name</strong>.</li>
<li>Patch Rails source code. I added a <a href="https://github.com/teohm/rails/compare/multipart_unicode_param_name">fix in my forked branch</a>, and <a href="https://github.com/rails/rails/issues/5606">reported the issue</a>. Hopefully it will get fixed soon in the coming release.</li>
</ol>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Working effectively with iTerm2]]></title>
    <link href="http://teohm.github.com/blog/2012/03/22/working-effectively-with-iterm2/"/>
    <updated>2012-03-22T22:42:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/03/22/working-effectively-with-iterm2</id>
    <content type="html"><![CDATA[<p>I have been using <a href="http://www.iterm2.com">iTerm</a> in <a href="http://www.favoritemedium.com">daily work</a> for almost a year now.
Along the way, I learned a few handy <strong>settings tweaks and shortcut keys to boost my productivity</strong> in command-line environment.</p>

<h2>Install iTerm2</h2>

<p>If you haven&#8217;t heard of <a href="http://www.iterm2.com">iTerm</a>, it&#8217;s a popular <strong>open source alternative to Mac OS X Terminal</strong>.
Give it a try, download and install it from <a href="http://www.iterm2.com">http://www.iterm2.com</a>.</p>

<h2>Fine-Tune Settings</h2>

<p>Launch iTerm, open <strong>iTerm > Preferences</strong> or just <code>Cmd + ,</code>.</p>

<h3>Open tab/pane with current working directory</h3>

<p>Under <strong>Profiles</strong> tab, go to <strong>General</strong> subtab, set <strong>Working Directory</strong> to <em>&#8220;Reuse previous session&#8217;s directory&#8221;</em>.</p>

<h3>Enable <code>Meta</code> key</h3>

<p>To enable Meta key for <a href="http://teohm.github.com/blog/2012/01/04/shortcuts-to-move-faster-in-bash-command-line">Bash readline editing</a> e.g. <code>Alt + b</code> to move to previous word, under <strong>Profiles</strong> tab, go to <strong>Keys</strong> subtab, set <strong>Left option key acts as:</strong> to <em>&#8220;+Esc&#8221;</em>.</p>

<h3>Hotkey to toggle iTerm2</h3>

<p>Under <strong>Keys</strong> tab, in <strong>Hotkey</strong> section, enable <em>&#8220;Show/hide iTerm2 with  a system-wide hotkey&#8221;</em> and input your hotkey combination, e.g. I use <code>Ctrl + Shift + L</code>.</p>

<h3>Switch pane with mouse cursor</h3>

<p>Under <strong>Pointer</strong>, in <strong>Miscellaneous Settings</strong> section, enable <em>&#8220;Focus follows mouse&#8221;</em>.</p>

<h2>Handy Shortcut Keys</h2>

<p>Here&#8217;s a set of <strong>shortcut keys I commonly use</strong>. You can always look for other shortcut keys in the iTerm menu.</p>

<h3>Tab navigation</h3>

<ul>
<li>open new tab <code>Cmd + t</code></li>
<li>next tab <code>Cmd + Shift + ]</code></li>
<li>previous tab <code>Cmd + Shift + [</code></li>
</ul>


<h3>Pane navigation</h3>

<ul>
<li>split pane left-right <code>Cmd + d</code></li>
<li>split pane top-bottom <code>Cmd + Shift + d</code></li>
<li>next pane <code>Cmd + ]</code></li>
<li>previous pane <code>Cmd + [</code></li>
</ul>


<h3>Search</h3>

<ul>
<li>open search bar <code>Cmd + f</code></li>
<li>find next <code>Cmd + g</code></li>
</ul>


<h3>Input to all panes</h3>

<ul>
<li>input to all panes in current tab <code>Cmd + Alt + i</code></li>
</ul>


<h3>Clear screen</h3>

<ul>
<li>clear buffer <code>Cmd + k</code></li>
<li>clear lines (Bash command) <code>Ctrl + l</code></li>
</ul>


<h3>Zooming / Font Resize</h3>

<ul>
<li>toggle maximize window <code>Cmd + Alt + =</code></li>
<li>toggle full screen <code>Cmd + Enter</code></li>
<li>make font larger <code>Cmd + +</code></li>
<li>make font smaller <code>Cmd + -</code></li>
</ul>


<p>iTerm lovers, did I miss anything out?</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Shortcuts to move faster in Bash command line]]></title>
    <link href="http://teohm.github.com/blog/2012/01/04/shortcuts-to-move-faster-in-bash-command-line/"/>
    <updated>2012-01-04T20:13:00+08:00</updated>
    <id>http://teohm.github.com/blog/2012/01/04/shortcuts-to-move-faster-in-bash-command-line</id>
    <content type="html"><![CDATA[<p>Nowadays, I spend more time in Bash shell, typing longer commands. One of my new year resolutions for this year
is to <strong>stop using left/right arrow keys to move around in the command line</strong>.
I learned <a href="http://pivotallabs.com/users/hunter/blog/articles/1925-terminal-beyond-ctrl-a-and-ctrl-e">a few shortcuts</a>
a while ago.</p>

<p>Last night, I spent some time to read about <strong>&#8220;Command Line Editing&#8221; in <a href="http://www.gnu.org/software/bash/manual/bashref.html#Command-Line-Editing">the bash manual</a></strong>.
The bash manual is a well-written piece of documentation. I think I should read it more often.</p>

<p>Well, here&#8217;s the new shortcuts I learned:</p>

<h2>Basic moves</h2>

<ul>
<li>Move back one character. <code>Ctrl</code> + <code>b</code></li>
<li>Move forward one character. <code>Ctrl</code> + <code>f</code></li>
<li>Delete current character. <code>Ctrl</code> + <code>d</code></li>
<li>Delete previous character. <code>Backspace</code></li>
<li>Undo. <code>Ctrl</code> + <code>-</code></li>
</ul>


<h2>Moving faster</h2>

<ul>
<li>Move to the start of line. <code>Ctrl</code> + <code>a</code></li>
<li>Move to the end of line. <code>Ctrl</code> + <code>e</code></li>
<li>Move forward a word. <code>Meta</code> + <code>f</code> <em>(a word contains alphabets and digits, no symbols)</em></li>
<li>Move backward a word. <code>Meta</code> + <code>b</code></li>
<li>Clear the screen. <code>Ctrl</code> + <code>l</code></li>
</ul>


<p><strong>What is Meta?</strong> <code>Meta</code> is your <code>Alt</code> key, normally. For <strong>Mac OSX user, you need to
enable it yourself</strong>. Open <em>Terminal > Preferences > Settings > Keyboard</em>,
and enable <em>Use option as meta key</em>. <code>Meta</code> key, by convention, is used for operations on word.</p>

<h2>Cut and paste (&#8216;Kill and yank&#8217; for old schoolers)</h2>

<ul>
<li>Cut from cursor to the end of line. <code>Ctrl</code> + <code>k</code></li>
<li>Cut from cursor to the end of word. <code>Meta</code> + <code>d</code></li>
<li>Cut from cursor to the start of word. <code>Meta</code> + <code>Backspace</code></li>
<li>Cut from cursor to previous whitespace. <code>Ctrl</code> + <code>w</code></li>
<li>Paste the last cut text. <code>Ctrl</code> + <code>y</code></li>
<li>Loop through and paste previously cut text. <code>Meta</code> + <code>y</code> (use it after <code>Ctrl</code> + <code>y</code>)</li>
<li>Loop through and paste the last argument of previous commands. <code>Meta</code> + <code>.</code></li>
</ul>


<h2>Search the command history</h2>

<ul>
<li>Search as you type. <code>Ctrl</code> + <code>r</code> and type the search term; Repeat <code>Ctrl</code> + <code>r</code> to loop through results.</li>
<li>Search the last remembered search term. <code>Ctrl</code> + <code>r</code> twice.</li>
<li>End the search at current history entry. <code>Ctrl</code> + <code>j</code></li>
<li>Cancel the search and restore original line. <code>Ctrl</code> + <code>g</code></li>
</ul>


<h2>Need more?</h2>

<ul>
<li>A comprehensive <a href="http://www.catonmat.net/blog/bash-emacs-editing-mode-cheat-sheet/"><strong>bash editing mode cheatsheet</strong></a> by Peteris Krumin (<a href="http://catonmat.net">catonmat.net</a>).</li>
<li><strong>Vim users!</strong> Do you know you can switch to Vi-style editing mode?
Here: <a href="http://www.catonmat.net/blog/bash-vi-editing-mode-cheat-sheet/">vi-style cheatsheet</a>.</li>
<li>Bash command line editing is actually handled by <strong>GNU Readline Library</strong>. So
just dive into <a href="http://www.gnu.org/software/readline/#Documentation">Readline manual</a>
for everything else.</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using RABL in Rails JSON Web API]]></title>
    <link href="http://teohm.github.com/blog/2011/05/31/using-rabl-in-rails-json-web-api/"/>
    <updated>2011-05-31T00:00:00+08:00</updated>
    <id>http://teohm.github.com/blog/2011/05/31/using-rabl-in-rails-json-web-api</id>
    <content type="html"><![CDATA[<p>Let&#8217;s use an event management app as the example.</p>

<p>The app has a simple feature: a user can add some events, then invite other users to attend the event. Its data are represented in 3 models: User, Event, and Event Guest.
<img src="http://teohm.github.com/images/2011-05-31-using-rabl-in-rails-json-web-api/models.png" alt="An ER digram that shows the domain models." /></p>

<p>Let say, we are going to add a read-only JSON web API for clients to browse data records from the app.</p>

<h2>Problems</h2>

<h3>Model is not view</h3>

<p>When working on a non-trivial web API, you will soon <a href="http://engineering.gomiso.com/2011/05/16/if-youre-using-to_json-youre-doing-it-wrong/">realize</a> that, model often cannot be serialized directly in web API.</p>

<p>Within the same app, one API may need to render a summary view of the model, while another needs a detail view of the same model. You want to serialize a view or view object, not a model.</p>

<p><a href="https://github.com/nesquena/rabl"><strong>RABL (Ruby API Builder Language) gem</strong></a> is designed for this purpose.</p>

<h3>Define once, reuse everywhere</h3>

<p>Let say, we need to render these user attributes: <code>id</code>, <code>username</code>, <code>email</code>, <code>display_name</code>, except <code>password</code>.</p>

<p>In RABL, we can define the attribute whitelist in a RABL template.</p>

<div>
  <pre><code class='ruby'># tryrabl/app/views/users/base.rabl
attributes :id, :username, :email, :display_name</code></pre>
</div>


<p>To show individual user, we can now reuse the template through RABL <code>extends</code>.</p>

<div>
  <pre><code class='ruby'># tryrabl/app/views/users/show.rabl
extends &quot;users/base&quot;
object @user

## JSON output:
# {
#     &quot;user&quot;: {
#         &quot;id&quot;: 8,
#         &quot;username&quot;: &quot;blaise&quot;,
#         &quot;email&quot;: &quot;matteo@wilkinsonhuel.name&quot;,
#         &quot;display_name&quot;: &quot;Ms. Noe Lowe&quot;
#     }
# }</code></pre>
</div>


<p>Here&#8217;s another example to show a list of users.</p>

<div>
  <pre><code class='ruby'># tryrabl/app/views/users/index.rabl
extends &quot;users/base&quot;
collection @users

## JSON output:
# [{
#     &quot;user&quot;: {
#         &quot;id&quot;: 1,
#         &quot;username&quot;: &quot;alanna&quot;,
#         &quot;email&quot;: &quot;rubie@hayes.name&quot;,
#         &quot;display_name&quot;: &quot;Mrs. Gaylord Hoeger&quot;
#     }
# }, {
#     &quot;user&quot;: {
#         &quot;id&quot;: 2,
#         &quot;username&quot;: &quot;jarrell.robel&quot;,
#         &quot;email&quot;: &quot;jarod@eichmann.com&quot;,
#         &quot;display_name&quot;: &quot;Oran Lebsack&quot;
#     }
# }]</code></pre>
</div>


<p>The template can be reused in nested child as well, through RABL <code>child</code>.</p>

<div>
  <pre><code class='ruby'>attributes :id, :title, :description, :start, :end, :location
child :creator =&gt; :creator do
  extends 'users/base'
end

## JSON output:
# {
#     &quot;event&quot;: {
#         &quot;id&quot;: 7,
#         &quot;title&quot;: &quot;Et earum sed fuga.&quot;,
#         &quot;description&quot;: &quot;Quis sed ..e ad.&quot;,
#         &quot;start&quot;: &quot;2011-05-31T08:31:45Z&quot;,
#         &quot;end&quot;: &quot;2011-06-01T08:31:45Z&quot;,
#         &quot;location&quot;: &quot;Saul Tunnel&quot;,
#         &quot;creator&quot;: {
#             &quot;id&quot;: 1,
#             &quot;username&quot;: &quot;alanna&quot;,
#             &quot;email&quot;: &quot;rubie@hayes.name&quot;,
#             &quot;display_name&quot;: &quot;Mrs. Gaylord Hoeger&quot;
#         }
#     }
# }</code></pre>
</div>


<h3>Join table rendered as subclass</h3>

<p>I notice a recurring pattern in two recent projects. For instance, in this example, from client&#8217;s point of view, Event Guest is basically a User with an additional attribute: RSVP status.</p>

<p>When query database, usually we need to query the join table: <code>event_guests</code>.</p>

<div>
  <pre><code class='ruby'>class GuestsController &lt; ApplicationController
  def index
    @guests = EventGuest.where(:event_id =&gt; params[:event_id])
  end
end</code></pre>
</div>


<p>But when rendering, the result set needs to be rendered as a list of Users. RABL allows you to do that easily, using its <code>glue</code> feature (a weird name though :).</p>

<div>
  <pre><code class='ruby'># tryrabl/app/views/guests/index.rabl
collection @event_guests

# include the additional attribute
attributes :rsvp

# add child attributes to parent model
glue :user do
  extends &quot;users/base&quot;
end

## JSON output:
# [{
#     &quot;event_guest&quot;: {
#         &quot;rsvp&quot;: &quot;PENDING&quot;,
#         &quot;id&quot;: 3,
#         &quot;username&quot;: &quot;myrna_harvey&quot;,
#         &quot;email&quot;: &quot;shad.armstrong@littelpouros.name&quot;,
#         &quot;display_name&quot;: &quot;Savion Balistreri&quot;
#     }
# }, {
#     &quot;event_guest&quot;: {
#         &quot;rsvp&quot;: &quot;PENDING&quot;,
#         &quot;id&quot;: 4,
#         &quot;username&quot;: &quot;adelle.nader&quot;,
#         &quot;email&quot;: &quot;brendon.howe@cormiergrady.info&quot;,
#         &quot;display_name&quot;: &quot;Edgardo Dickens&quot;
#     }
# }]</code></pre>
</div>


<p>I think I will use RABL for the next Rails web API project.</p>

<p>The complete Rails example code is available at <a href="https://github.com/teohm/tryrabl">github.com/teohm/tryrabl</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Learning Git Internals by Example]]></title>
    <link href="http://teohm.github.com/blog/2011/05/30/learning-git-internals-by-example/"/>
    <updated>2011-05-30T00:00:00+08:00</updated>
    <id>http://teohm.github.com/blog/2011/05/30/learning-git-internals-by-example</id>
    <content type="html"><![CDATA[<p><em>Status: Draft.</em><br/>
<em>Plan to revise this post, probably simplify it in future..</em></p>

<h2>Movitation</h2>

<p>After switching to Git from Subversion and Mercurial for a few months, somehow I feel that Git is fundamentally different from Subversion or Mercurial, but couldn&#8217;t really tell the differences. I often see terms like tree, parent etc. in GitHub, which I have no idea what they actually mean.</p>

<p>So I decided to spent some time to learn Git.</p>

<p>I will try to summarize and publish important stuffs I learned about Git along the way.. but here is the first entry, about Git internals, which helped me to answer how Git is different other source control tools.</p>

<h2>Objects, References, The Index</h2>

<p>To understand the core of Git internals, there are 3 things to we should know: <strong>objects, references, the index</strong>.</p>

<p>I find this model is elegant. It fits well in a small diagram, as well as in my head.</p>

<p><img src="http://teohm.github.com/images/2011-05-30-learning-git-internals-by-example/big-picture.png" alt="A picture illustrates files in .git directory mentioned in this article." /></p>

<h3>Objects</h3>

<p>All files that you commited into a Git repository, including the commit info are stored as <strong>objects</strong> in <code>.git/objects/</code>.</p>

<p>An object is identified by a 40-character-long string &#8211; SHA1 hash of the object&#8217;s content.</p>

<p>There are <strong>4 types</strong> of objects:</p>

<ol>
<li><em>blob</em> - stores file content.</li>
<li><em>tree</em> - stores direcotry layouts and filenames.</li>
<li><em>commit</em> - stores commit info and forms the Git commit graph.</li>
<li><em>tag</em> - stores annotated tag.</li>
</ol>


<p>The example will illustrate how these objects relate to each others.</p>

<h3>References</h3>

<p>A <em>branch</em>, <em>remote branch</em> or a <em>tag</em> (also called <em>lightweight tag</em>) in Git, is just a <strong>pointer to an object</strong>, usually a commit object.</p>

<p>They are stored as plain text files in <code>.git/refs/</code>.</p>

<h4>Symbolic References</h4>

<p>Git has a special kind of reference, called <em>symbolic reference</em>. It doesn&#8217;t point to an object directly. Instead, it <strong>points to another reference</strong>.</p>

<p>For instance, <code>.git/HEAD</code> is a symbolic reference. It points to the current branch you are working on.</p>

<h3>The Index</h3>

<p>The index is a staging area, stored as a binary file in <code>.git/index</code>.</p>

<p>When <code>git add</code> a file, Git adds the file info to the index. When <code>git commit</code>, Git only commits what&#8217;s listed in the index.</p>

<hr />

<h2>Examples</h2>

<p>Let&#8217;s walkthrough a simple example, to create a Git repository, commit some files and see what happened behind the scene in <code>.git</code> directory.</p>

<h3>Initialize New Repository</h3>

<div>
  <pre><code class='bash'>$ git init canai</code></pre>
</div>


<p><img src="http://teohm.github.com/images/2011-05-30-learning-git-internals-by-example/init.png" alt="illustration" /></p>

<p>What happened:</p>

<ul>
<li>Empty <code>.git/objects/</code> and <code>.git/refs/</code> created.</li>
<li>No index file yet.</li>
<li><code>HEAD</code> symbolic reference created.

<pre><code>$ cat .git/HEAD 
ref: refs/heads/master
</code></pre></li>
</ul>


<h3>Add New File</h3>

<div>
  <pre><code class='bash'>$ echo &quot;A roti canai project.&quot; &gt;&gt; README
$ git add README</code></pre>
</div>


<p><img src="http://teohm.github.com/images/2011-05-30-learning-git-internals-by-example/new-file.png" alt="illustration" /></p>

<p>What happened:</p>

<ul>
<li>Index file created.<br/>
It has a SHA1 hash that points to a blob object.

<pre><code>$ git ls-files --stage
100644 5f89c6f016cad2d419e865df380595e39b1256db 0 README
</code></pre></li>
<li>Blob object created.<br/>
The content of README file is stored in this blob.

<pre><code># .git/objects/5f/89c6f016cad2d419e865df380595e39b1256db
$ git cat-file blob 5f89c6
A roti canai project.
</code></pre></li>
</ul>


<h3>First Commit</h3>

<div>
  <pre><code class='bash'>$ git commit -m'first commit'
[master (root-commit) d9976cf] first commit
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 README</code></pre>
</div>


<p><img src="http://teohm.github.com/images/2011-05-30-learning-git-internals-by-example/first-commit.png" alt="illustration" /></p>

<p>What happened:</p>

<ul>
<li>Branch &#8216;master&#8217; reference created.<br/>
It points to the lastest commit object in &#8216;master&#8217; branch.

<pre><code>$ cat .git/refs/heads/master 
d9976cfe0430557885d162927dd70186d0f521e8
</code></pre></li>
<li>First commit object created.<br/>
It points to the root tree object.

<pre><code># .git/objects/d9/976cfe0430557885d162927dd70186d0f521e8
$ git cat-file commit d9976cf
tree 0ff699bbafc5d17d0637bf058c924ab405b5dcfe
author Huiming Teo &lt;huiming@favoritemedium.com&gt; 1306739524 +0800
committer Huiming Teo &lt;huiming@favoritemedium.com&gt; 1306739524 +0800

first commit
</code></pre></li>
<li>Tree object created.<br/>
This tree represents the &#8216;canai&#8217; directory.

<pre><code># .git/objects/0f/f699bbafc5d17d0637bf058c924ab405b5dcfe
$ git ls-tree 0ff699
100644 blob 5f89c6f016cad2d419e865df380595e39b1256db  README
</code></pre></li>
</ul>


<h3>Add Modified File</h3>

<div>
  <pre><code class='bash'>$ echo &quot;Welcome everyone.&quot; &gt;&gt; README
$ git add README</code></pre>
</div>


<p><img src="http://teohm.github.com/images/2011-05-30-learning-git-internals-by-example/modified-file.png" alt="illustration" /></p>

<p>What happened:</p>

<ul>
<li>Index file updated.<br/>
Notice it points to a new blob?

<pre><code>$ git ls-files --stage
100644 1192db4c15e019da7fc053225d09dea14bc3ac07 0 README
</code></pre></li>
<li>Blob object created.<br/>
The entire README content is stored as a new blob.

<pre><code># .git/objects/11/92db4c15e019da7fc053225d09dea14bc3ac07
$ git cat-file blob 1192db
A roti canai project.
Welcome everyone.
</code></pre></li>
</ul>


<h3>Add File into Subdirectory</h3>

<div>
  <pre><code class='bash'>$ mkdir doc
$ echo &quot;[[TBD]] manual toc&quot; &gt;&gt; doc/manual.txt
$ git add doc</code></pre>
</div>


<p><img src="http://teohm.github.com/images/2011-05-30-learning-git-internals-by-example/subdir.png" alt="illustration" /></p>

<p>What happened:</p>

<ul>
<li>Index file updated.

<pre><code>$ git ls-files --stage
100644 1192db4c15e019da7fc053225d09dea14bc3ac07 0 README
100644 ea283e4fb22719fad512405d41dffa050cd16f9a 0 doc/manual.txt
</code></pre></li>
<li>Blob object created.

<pre><code># .git/objects/ea/283e4fb22719fad512405d41dffa050cd16f9a
$ git cat-file blob ea283
[[TBD]] manual toc
</code></pre></li>
</ul>


<h3>Second Commit</h3>

<div>
  <pre><code class='bash'>$ git commit -m'second commit'
[master 556eaf3] second commit
 2 files changed, 2 insertions(+), 0 deletions(-)
 create mode 100644 doc/manual.txt</code></pre>
</div>


<p><img src="http://teohm.github.com/images/2011-05-30-learning-git-internals-by-example/second-commit.png" alt="illustration" /></p>

<p>What happened:</p>

<ul>
<li>Branch &#8216;master&#8217; reference updated.<br/>
It points to a lastest commit in this branch.

<pre><code>$ cat .git/refs/heads/master 
556eaf374886d4c07a1906b9fdcaba195292b96
</code></pre></li>
<li>Second commit object created.
Notice its &#8216;parent&#8217; points to the first commit object. This forms a commit graph.

<pre><code>$ git cat-file commit 556e
tree 7729a8b15b747bce541a9752a8f10d57daf221b6
parent d9976cfe0430557885d162927dd70186d0f521e8
author Huiming Teo &lt;huiming@favoritemedium.com&gt; 1306743598 +0800
committer Huiming Teo &lt;huiming@favoritemedium.com&gt; 1306743598 +0800

second commit
</code></pre></li>
<li>New root tree object created.

<pre><code>$ git ls-tree 7729
100644 blob 1192db4c15e019da7fc053225d09dea14bc3ac07  README
040000 tree 6ff17d485bf857514f299f0bde0e2a5c932bd055  doc
</code></pre></li>
<li>New subdir tree object created.

<pre><code>$ git ls-tree 6ff1
100644 blob ea283e4fb22719fad512405d41dffa050cd16f9a  manual.txt
</code></pre></li>
</ul>


<h3>Add Annotated Tag</h3>

<div>
  <pre><code class='bash'>$ git tag -a -m'this is annotated tag' v0.1 d9976</code></pre>
</div>


<p><img src="http://teohm.github.com/images/2011-05-30-learning-git-internals-by-example/annotated-tag.png" alt="illustration" /></p>

<p>What happened:</p>

<ul>
<li>Tag reference created.<br/>
It points to a tag object.

<pre><code>$ cat .git/refs/tags/v0.1 
c758f4820f02acf20bb3f6d7f6098f25ee6ed730
</code></pre></li>
<li>Tag object created.

<pre><code>$ git cat-file tag c758
object d9976cfe0430557885d162927dd70186d0f521e8
type commit
tag v0.1
tagger Huiming Teo &lt;huiming@favoritemedium.com&gt; 1306744918 +0800

this is annotated tag
</code></pre></li>
</ul>


<h3>Add new (lightweight) tag</h3>

<div>
  <pre><code class='bash'>$ git tag root-commit d9976</code></pre>
</div>


<p><img src="http://teohm.github.com/images/2011-05-30-learning-git-internals-by-example/new-tag.png" alt="illustration" /></p>

<p>What happened:</p>

<ul>
<li>Tag reference created.<br/>
It points to a commit object.

<pre><code>$ cat .git/refs/tags/root-commit 
d9976cfe0430557885d162927dd70186d0f521e8
</code></pre></li>
</ul>


<h2>More Readings</h2>

<ul>
<li>&#8220;Chapter 7: Internals and Plumbing&#8221; in <a href="http://book.git-scm.com/index.html">The Git Community Book</a>.</li>
<li>&#8220;Chapter 9: Git Internals&#8221; in <a href="http://progit.org/book/ch9-0.html">Pro Git</a>.</li>
</ul>


<h2>What&#8217;s Next?</h2>

<p>Looking for a minimal git workflow suitable for a distributed team, long-running project..</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using JQuery Validation in Rails Remote Form]]></title>
    <link href="http://teohm.github.com/blog/2011/05/25/using-jquery-validation-in-rails-remote-form/"/>
    <updated>2011-05-25T00:00:00+08:00</updated>
    <id>http://teohm.github.com/blog/2011/05/25/using-jquery-validation-in-rails-remote-form</id>
    <content type="html"><![CDATA[<p>In a recent project, I was trying to use <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">JQuery Validation</a> in an <a href="https://github.com/rails/jquery-ujs/blob/bb620a29199214b5c7a3a015372fda28b69c69a1/src/rails.js">earlier version</a> of Rails 3 remote form (<a href="https://github.com/rails/jquery-ujs">jquery-ujs</a>). They didn&#8217;t work out well in IE.</p>

<p>After experimenting with the <a href="https://github.com/rails/jquery-ujs/blob/dad6982dc592686677e6845e681233c40d2ead27/src/rails.js">latest jquery-ujs</a> and making an embarrassing mistake, it turns out that the issue is resolved in the latest version.</p>

<p>(<em>Mistake</em>: You may notice I removed a previous post about this topic, where I mistakenly concluded the latest jquery-ujs is not working with JQuery Validation. Thanks to JangoSteve for <a href="https://github.com/rails/jquery-ujs/issues/165#comment_1228899">pointing it out</a>. The post was misleading, so I believe it&#8217;s best to remove it to avoid confusion. :-)</p>

<h2>Get the latest <code>jquery-ujs</code></h2>

<p>There are 2 reasons to use the latest jquery-ujs:</p>

<ol>
<li>it has a patch that fixes the issue (see <a href="https://github.com/rails/jquery-ujs/issues/118">issue #118</a>).</li>
<li>it exposes an internal function that we may need &#8211; <code>$.rails.handleRemote()</code> (see <a href="http://www.alfajango.com/blog/rails-jquery-ujs-now-interactive/">more details</a>)</li>
</ol>


<h2>Working example</h2>

<p>The example is tested with:</p>

<ul>
<li>JQuery 1.6.1</li>
<li>JQuery Vaidation 1.8.1</li>
<li>Latest Rails UJS (commit: <a href="https://github.com/rails/jquery-ujs/blob/dad6982dc592686677e6845e681233c40d2ead27/src/rails.js">dad6982dc592686677e6</a>)</li>
</ul>


<h3>When using <code>submitHandler</code> in JQuery Validation</h3>

<p>If you are using JQuery Validation&#8217;s <code>submitHandler(form)</code> function, you need to
call <code>$.rails.handleRemote( $(form) )</code> function manually, so that it submits the form via XHR.</p>

<div>
  <pre><code class='javascript'>$('#submit_form').validate({

  submitHandler: function(form) {
    // .. do something before submit ..
    $.rails.handleRemote( $(form) );  // submit via xhr
    //form.submit();                  // don't use, it submits the form directly
  }

});</code></pre>
</div>



]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[ActiveRecord Mass Assignment]]></title>
    <link href="http://teohm.github.com/blog/2011/05/09/activerecord-mass-assignment/"/>
    <updated>2011-05-09T00:00:00+08:00</updated>
    <id>http://teohm.github.com/blog/2011/05/09/activerecord-mass-assignment</id>
    <content type="html"><![CDATA[<p>Even you haven&#8217;t heard of
<a href="http://guides.rubyonrails.org/security.html#mass-assignment">mass assignment</a>,
it already exists in your first Rails generated scaffold code.</p>

<div>
  <pre><code class='ruby'>def create
  @comment = Comment.new(params[:comment])
  ..
end

def update
  ..
  @comment.update_attributes(params[:comment])
  ..
end</code></pre>
</div>


<h2>Why knowing mass assignment is important?</h2>

<p>By default, mass assignment opens up an undesirable <strong>security hole</strong>,
by allowing web clients to update any attributes they passing in,
including attributes like <code>created_at</code>.</p>

<p>For details, you can read:</p>

<ul>
<li><a href="http://guides.rubyonrails.org/security.html#mass-assignment">Ruby On Rails Security Guide - Mass Assignment</a></li>
<li><a href="http://railspikes.com/2008/9/22/is-your-rails-application-safe-from-mass-assignment">Rail Spikes: Is your Rails application safe?</a></li>
</ul>


<h2>Mass assignment methods</h2>

<p>There are a few <strong>ActiveRecord methods</strong> that accept mass assignment:</p>

<ul>
<li><a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-new"><code>new</code></a></li>
<li><a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-create"><code>create</code></a></li>
<li><a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-attributes-3D"><code>attributes=</code></a></li>
<li><a href="http://apidock.com/rails/ActiveRecord/Base/update_attributes"><code>update_attributes</code></a></li>
</ul>


<p>Using any of these methods, means you are now responsible for the safety
of the web application.</p>

<h2>Minimal protection</h2>

<p>To use mass assignment safely, we want to specify exactly which attributes
allowed to be updated.</p>

<h3>1. Define <code>attr_accessible</code> on every model</h3>

<p><code>attr_accessible</code> defines a white-list of attributes
that can be updated during mass assignment.</p>

<div>
  <pre><code class='ruby'>class Comment &lt; ActiveRecord::Base
  attr_accessible :title, :content
end</code></pre>
</div>


<h3>2. Enforce <code>attr_accessible</code> usage</h3>

<p>You may set the white-list default to empty. This forces you
to define the whitelist explicitly on a model, before
mass assignment can be used.</p>

<div>
  <pre><code class='ruby'># config/initializer/enforce_attr_accessible.rb

ActiveRecord::Base.send(:attr_accessible, nil)</code></pre>
</div>



]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[ActiveRecord Model Equality]]></title>
    <link href="http://teohm.github.com/blog/2011/05/05/activerecord-model-equality/"/>
    <updated>2011-05-05T00:00:00+08:00</updated>
    <id>http://teohm.github.com/blog/2011/05/05/activerecord-model-equality</id>
    <content type="html"><![CDATA[<p>In daily web app development, we often need to check if two model objects are equal.
When I first started using Rails, this is what I wrote:</p>

<div>
  <pre><code class='ruby'>if user.id == current_user.id
  # do something
end</code></pre>
</div>


<h2>Use obj1 == obj2 instead</h2>

<p>Of course, that reflects my ignorance on learning the new tool.</p>

<p>So, here&#8217;s a proper way to compare if
<a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-3D-3D">two model objects are equal</a>:</p>

<div>
  <pre><code class='ruby'>test &quot;2 records with same #id equal to each others.&quot; do
  c1 = Comment.create
  c2 = Comment.find(c1.id)

  assert c1 == c2
  assert c2 == c1
end</code></pre>
</div>


<h2>What about new record?</h2>

<p>Basically, a new model object only equals to itself:</p>

<div>
  <pre><code class='ruby'>test &quot;New record does not equal to another new record.&quot; do
  new_record = Comment.new
  another_new = Comment.new

  assert new_record == new_record
  assert another_new == another_new
  assert new_record != another_new
end</code></pre>
</div>


<p>Learning to use <code>==</code> operator for checking model equality
is useful. Because now, we can start using other methods
that depend on <code>==</code> operator. For instance, <code>Array#include?</code>.</p>

<div>
  <pre><code class='ruby'>test &quot;When applied in Array&quot; do
  c1 = Comment.create
  c2 = Comment.find(c1.id)

  assert [c1].include? c2
  assert [c2].include? c1
  assert [c1, c2] == [c1, c2]
end</code></pre>
</div>


<h2>Rails learning tests</h2>

<p>You may notice the code examples are written as tests.
This is my first <a href="https://github.com/teohm/lt_rails">Rails learning test</a>.
So the plan is to write more tests as a way to learn Rails. I will
post them here occationally if interesting enough to share.</p>

<p>Source code: <a href="https://github.com/teohm/lt_rails/blob/master/test/unit/model_equality_test.rb">model_equality_test.rb</a></p>
]]></content>
  </entry>
  
</feed>
