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

  <title><![CDATA[the Pickard Ayune]]></title>
  <link href="http://pickardayune.com/atom.xml" rel="self"/>
  <link href="http://pickardayune.com/"/>
  <updated>2025-08-18T13:35:33+00:00</updated>
  <id>http://pickardayune.com/</id>
  <author>
    <name><![CDATA[Matt Burke]]></name>
    
  </author>

  
  <entry>
    <title type="html"><![CDATA[Concurrency control and Linux's Pressure Stall Information]]></title>
    <link href="http://pickardayune.com/blog/2024/10/10/psi"/>
    <updated>2024-10-10T00:00:00+00:00</updated>
    <id>http://pickardayune.com/blog/2024/10/10/psi</id>
    <content type="html"><![CDATA[<p>I did some performance analysis recently where I needed to download and process
a bunch of data. It was easily parallelizable since the data set was made up of
many independent items. I was mostly interested in the average time to process
each individual item. So the amount of parallelization wasn’t too interesting,
other than that I wanted to do some parallelization but I didn’t want to
overload my test machine.</p>

<p>One of the other topics I’ve been interested in recently is concurrency
control, and how we can do that more effectively within my team’s services. We
would like to allow our servers to do as much work as possible without
overloading them. Overloading a server can make everything slow down, even
cheap fast calls get crazy slow.</p>

<p>In <a href="https://www.youtube.com/watch?v=m64SWl9bfvk">Stop Rate Limiting</a>, Jon Moore
describes a method of concurrency control using a dynamically determined limit.
The method works like this: given some limit to the number of jobs, when you go
to schedule a job beyond the limit, you check to see if the system is
overloaded. If it isn’t, you add a constant to the limit and allow the new
request. On the other hand, when the system is overloaded, you reduce the limit
by dividing by a constant. This is known as <a href="https://en.wikipedia.org/wiki/Additive_increase/multiplicative_decrease">Additive Increase/Multiplicative
Decrease</a>,
and is used in algorithms like TCP congestion control.</p>

<p>My performance problem provided a scenario that I could use to try AIMD. My
jobs are all assumed to be similar in size, so the limit is the maximum number
of jobs. (If the jobs weren’t consistently sized, I might estimate their weight
and use a sum of the weights as the limit.) When the system isn’t overloaded, I
increased the limit by 1, at most once per second. When the system was
overloaded, I decreased the limit by a factor of 0.9, again at most once per
second.</p>

<p>I needed a way to check if the system was overloaded. An obvious choice would
be load average. But I’d recently learned about Linux’s <a href="https://docs.kernel.org/accounting/psi.html">Pressure Stall
Information</a> (PSI), so I thought I
would try using it. PSI has three different counters, one each for CPU, memory,
and I/O. PSI tells you how often some or all tasks are blocked waiting for a
given resource. I looked at PSI values for some of our other servers, and
decided to set up three ranges for each: overloaded, acceptable, underloaded,
as a percent of the time that some tasks were stalled waiting for the resource.
The max healthy limit that I used for CPU was 10%, for memory 1%, for I/O 1%.</p>

<p>The end result is in this
<a href="https://gist.github.com/spraints/8e538ff016833f25bd5ce5b6a7f71ffd">gist</a>.</p>

<p>So, how did it go?</p>

<p>I ended up running a couple different types of jobs inadvertently. One was more
compute heavy, and one was more balanced between compute and network transfer.
The more balanced version downloaded archives, reassembled them, and then ran a
couple of consistency checks across the data. The compute heavy version did
mostly the same thing, except that it ended up doing the consistency checks
many times per job. Another way to look at it: the balanced job did O(N)
downloads and O(N) scans; the compute heavy one did O(N) downloads and
O(N<sup>2</sup>) scans.</p>

<p>For the balanced job, the concurrency control worked pretty well. I ran this
job a few times. Each time, utilization was just about right so that work got
done quickly but the system remained responsive. The number of concurrent
workers was 50 - 70 for the duration. CPU usage was around 80%, load was 73 -
120 (on a 128 core system), I/O utilization was around 40% at the peak.
Overall, I was happy with how it turned out.</p>

<p>For the compute heavy job, the concurrency control didn’t work as well. I ran
this job once. In this case, the number of concurrent jobs was nearer 140, load
was also about 140, and CPU usage was pegged at 100%. The system was overloaded
badly enough that I interrupted it and ran it differently so that the network
to compute ratio was closer to 1:1 again.</p>

<p>If I were to do this again or for production use, I would add a step to the
compute-heavy job that checks in with the controller to see if it’s ok to do
the next computational step. This would allow the limiter to claw back some of
the work if it accidentally allowed too much through. I would also want to tune
the overload detector quite a bit, I need to learn more about how to interpret
the PSI values.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Nil isn't always nil in Go]]></title>
    <link href="http://pickardayune.com/blog/2018/01/05/nil-is-not-always-nil-in-go"/>
    <updated>2018-01-05T00:00:00+00:00</updated>
    <id>http://pickardayune.com/blog/2018/01/05/nil-is-not-always-nil-in-go</id>
    <content type="html"><![CDATA[<p>I ran across some interesting behavior in <a href="https://golang.org/">Go</a> today.
Given <a href="https://gist.github.com/spraints/7fa7f93366b6cdfffe30e4e5232adb02">this program</a>, what would you expect to happen?</p>

<script src="https://gist.github.com/spraints/7fa7f93366b6cdfffe30e4e5232adb02.js"></script>

<p>My first guess is that it would output this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Trying &amp;main.Owner{org:(*main.Organization)(nil), user:(*main.User)(nil)}
 =&gt; "NIL"
Trying &amp;main.Owner{org:(*main.Organization)(0xc42000e200), user:(*main.User)(nil)}
 =&gt; "organization:group"
Trying &amp;main.Owner{org:(*main.Organization)(nil), user:(*main.User)(0xc42000e250)}
 =&gt; "user:person"
</code></pre></div></div>

<p>However, that’s not what actually happens. Instead, you’d see this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Trying &amp;main.Owner{org:(*main.Organization)(nil), user:(*main.User)(nil)}
 =&gt; panic!! "invalid memory address or nil pointer dereference"
Trying &amp;main.Owner{org:(*main.Organization)(0xc42000e200), user:(*main.User)(nil)}
 =&gt; "organization:group"
Trying &amp;main.Owner{org:(*main.Organization)(nil), user:(*main.User)(0xc42000e250)}
 =&gt; panic!! "invalid memory address or nil pointer dereference"
</code></pre></div></div>

<p>To see why, it helps to see the output from the <code class="language-plaintext highlighter-rouge">fmt.Printf</code> statements that are in <code class="language-plaintext highlighter-rouge">Owner.DatabaseString</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Trying &amp;main.Owner{org:(*main.Organization)(nil), user:(*main.User)(nil)}
  [0] &lt;nil&gt;
  [1] (*main.Organization)(nil)
 =&gt; panic!! "invalid memory address or nil pointer dereference"
Trying &amp;main.Owner{org:(*main.Organization)(0xc42000e200), user:(*main.User)(nil)}
  [0] &lt;nil&gt;
  [1] &amp;main.Organization{name:"group"}
 =&gt; "organization:group"
Trying &amp;main.Owner{org:(*main.Organization)(nil), user:(*main.User)(0xc42000e250)}
  [0] &lt;nil&gt;
  [1] (*main.Organization)(nil)
 =&gt; panic!! "invalid memory address or nil pointer dereference"
</code></pre></div></div>

<p>I think this is happening because Go interface types are really a <a href="https://golang.org/doc/faq#nil_error">type plus a value</a>. The call to <code class="language-plaintext highlighter-rouge">GetOrganization()</code> returns a nil <code class="language-plaintext highlighter-rouge">Organization</code>, but not a nil <code class="language-plaintext highlighter-rouge">DatabaseStringer</code>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Greenhouse Lift]]></title>
    <link href="http://pickardayune.com/blog/2015/12/25/greenhouse-lift"/>
    <updated>2015-12-25T00:00:00+00:00</updated>
    <id>http://pickardayune.com/blog/2015/12/25/greenhouse-lift</id>
    <content type="html"><![CDATA[<blockquote>
  <p>In which a programmer puts on his mechanical (?) engineer hat.</p>
</blockquote>

<p>Recently we lost a greenhouse cover because the U-channel it was attached to came off of the greenhouse. We’ve already had two other wind related events with this particular greenhouse. I’d like to avoid having any more. So, I sat down with a pen, paper, and the Internet of engineering information.</p>

<p>Lift is what we’re working with here. I’ve seen a couple different renderings of it (<a href="https://www.grc.nasa.gov/www/k-12/WindTunnel/Activities/lift_formula.html">NASA’s</a>, <a href="https://en.wikipedia.org/wiki/Lift_(force)#Lift_coefficient">Wikipedia’s</a>). Here’s the one we’ll use, so that I don’t have to type Greek letters.</p>

<p><em>L = 1/2 * d * v^2 * s * CL</em></p>

<ul>
  <li><em>d</em> is the density of air</li>
  <li><em>v</em> is the speed of the aircraft</li>
  <li><em>s</em> is the area of the airfoil</li>
  <li><em>CL</em> is the coefficient of lift</li>
</ul>

<p><a href="https://en.wikipedia.org/wiki/International_Standard_Atmosphere"><em>d = 1.225 kg / m^3</em></a>.</p>

<p>The airfoil is fixed, so I used wind speed instead. Gusts of 50mph have been a problem for us, and that’s about the highest wind gusts that we get. So <em>v = 50mph = 73 ft / s = 22.352 m /s</em>.</p>

<p>The area of the airfoil is the footprint of the greenhouse. If I recall correctly, it’s 96 ft x 30 ft. So <em>s = 96 * 30 ft^2 = 2880 ft^2 = 270 m^2</em>.</p>

<p>The coefficient of lift is a tough one to figure out. NASA has a <a href="https://www.grc.nasa.gov/www/k-12/WindTunnel/Activities/lift_formula.html">set of academic problems related to lift</a>, and the accompanying chart shows a peak <em>CL</em> of approximately 1.6. Wikipedia’s <a href="https://en.wikipedia.org/wiki/Lift_coefficient">Lift coefficient page</a> shows a maximum <em>CL</em> of 1.75. An aerospace engineering school’s <a href="http://www.dept.aoe.vt.edu/~mason/Mason_f/HiLiftPresPt1.pdf">high lift slide deck</a> maxes out around 1.75. I’m going to assume that we haven’t found a magic formula for generating even higher lift, so I used <em>CL = 1.75</em> to have a worst-case estimate.</p>

<p><em>L</em> = 1/2 * 1.225 * (22.352)^2 * 270 * 1.75<br />
<em>L</em> = 144,468.292 Newtons<br />
<em>L</em> = 32,477 lbf<br /></p>

<p>Where does this force end up? We have 34 metal 2 5/8” ground posts. Each post is bolted to a wooden hip board with a 3/8” carriage bolt. U-channel is screwed onto the hip board with Tek screws or wood screws. The plastic is clamped to the U-channel with wiggle wire.</p>

<p>I don’t know how much force you need to apply to pull the metal pipes out of the ground. We have heavy clay soil. I’m going to assume that this is more than enough (over 1000 lb per post?) to handle the wind.</p>

<p>I’m not sure what grade the bolts are. Nucor has a <a href="https://www.nucor-fastener.com/Files/PDFs/TechDataSheets/TDS_013_Shear_Strength.pdf">shear strength data sheet</a> that says that 3/8” bolts have at least 3900 lb shear strength. So our 34 bolts should be able to hold down 132,600 pounds.</p>

<p>The U-channels may have been screwed onto the boards about every 2 ft. This is what pulled off, so I can’t measure it now. We used a combination of Tek screws and wood screws. A <a href="http://www.9wood.com/files/rd_reports/screw_withdrawl.pdf">random study of wood screw pullout strength</a> shows that screws pull out well before 300 lb. So, if we managed to get 200 lb of pullout resistance per screw (and I doubt that we did), the U-channel should have been able to withstand 28,800 pounds of pull out force. That doesn’t directly translate to the type of force the screws received, but if it’s anything like the actual number, it’s way too low. Our plan is to attach new double-U-channel with carriage bolts. If we use 1/4” carriage bolts at every post, we should be able to handle 60,000 pounds of force. If we use 2 at each post and one in between, we should be good for 160,000 pounds of force.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Introducing Resqued]]></title>
    <link href="http://pickardayune.com/blog/2013/11/25/resqued"/>
    <updated>2013-11-25T00:00:00+00:00</updated>
    <id>http://pickardayune.com/blog/2013/11/25/resqued</id>
    <content type="html"><![CDATA[<p><a href="https://github.com/spraints/resqued">Resqued</a>
(res-kyu-dee) is a prefork daemon that manages a pool of resque workers.
It’s designed to support continuous deployment, long-running jobs, and high availability.</p>

<p>The resqued daemon can be restarted, paused, or stopped gracefully via <a href="https://github.com/spraints/resqued/blob/master/docs/signals.md">signals</a>.
On restart, resqued reloads your configuration in a new process.
When the new process is ready, the old workers are spun down and new workers are forked.
If the configuration does not load, the old workers will continue running.
Workers that exit unexpectedly are restarted.</p>

<h2 id="using-resqued">Using resqued</h2>

<p>Resqued is configured with a ruby-based configuration file.
It includes a command-line program that starts the daemon either in the foreground or background.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ resqued --help
Usage: resqued [options] resqued-config-files...
    -h, --help                       Show this message
    -v, --version                    Show the version
        --test                       Report which worker would start
    -p, --pidfile PIDFILE            Store the pid of the master process in PIDFILE
    -l, --logfile LOGFILE            Write output to LOGFILE instead of stdout
    -D, --daemonize                  Run daemonized in the background
</code></pre></div></div>

<p>For a typical rails application, create <code class="language-plaintext highlighter-rouge">config/resqued.rb</code>:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># Run 4 workers</span>
<span class="n">worker_pool</span> <span class="mi">4</span>

<span class="n">before_fork</span> <span class="k">do</span>
  <span class="c1"># Load the app environment.</span>
  <span class="nb">require</span> <span class="no">File</span><span class="p">.</span><span class="nf">expand_path</span><span class="p">(</span><span class="s1">'config/environment.rb'</span><span class="p">)</span>
  <span class="c1"># Free up a DB connection.</span>
  <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span><span class="p">.</span><span class="nf">connection</span><span class="p">.</span><span class="nf">disconnect!</span>
<span class="k">end</span>

<span class="n">after_fork</span> <span class="k">do</span> <span class="o">|</span><span class="n">worker</span><span class="o">|</span>
  <span class="c1"># Reconnect to the database.</span>
  <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span><span class="p">.</span><span class="nf">establish_connection</span>
<span class="k">end</span></code></pre></figure>

<p>You can see which workers will be started:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ resqued --test config/resqued.rb
Workers defined in config/resqued.rb
1: *
2: *
3: *
4: *
</code></pre></div></div>

<p>To start the daemon in the foreground:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ resqued config/resqued
</code></pre></div></div>

<p>In production, you would start the daemon like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ resqued -D -p tmp/pids/resqued.pid -l log/resqued.log config/resqued.rb
</code></pre></div></div>

<h2 id="migrating-from-rake-resquework">Migrating from <code class="language-plaintext highlighter-rouge">rake resque:work</code></h2>

<p>If you’ve got an existing pool of workers, you’re probably doing something like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ rake resque:work QUEUE=high
$ rake resque:work QUEUE=high
$ rake resque:work QUEUE=high,normal
$ rake resque:work QUEUE=high,normal
</code></pre></div></div>

<p>To reproduce this in resqued, you would create a config file that looks like this:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># before_fork and after_fork as above</span>

<span class="n">worker_pool</span> <span class="mi">4</span>
<span class="n">queue</span> <span class="s1">'high'</span>
<span class="n">queue</span> <span class="s1">'normal'</span><span class="p">,</span> <span class="ss">:count</span> <span class="o">=&gt;</span> <span class="mi">2</span></code></pre></figure>

<h3 id="without-a-pool">without a pool</h3>

<p>The worker pool might not work for you if you’re doing something like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ rake resque:work QUEUE=high
$ rake resque:work QUEUE=high
$ rake resque:work QUEUE=normal
$ rake resque:work QUEUE=*
</code></pre></div></div>

<p>To reproduce this in resqued, you would create a config file like this:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># before_fork and after_fork as above</span>

<span class="mi">2</span><span class="p">.</span><span class="nf">times</span> <span class="p">{</span> <span class="n">worker</span> <span class="s1">'high'</span> <span class="p">}</span>
<span class="n">worker</span> <span class="s1">'normal'</span>
<span class="n">worker</span> <span class="s1">'*'</span></code></pre></figure>

<p>Many variants of worker configuration are documented in the <a href="https://github.com/spraints/resqued/blob/master/spec/resqued/config/worker_spec.rb">worker specs</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Serialized Attributes in ActiveRecord 3.2]]></title>
    <link href="http://pickardayune.com/blog/2012/08/22/serialized-attributes-in-activerecord-3-dot-2"/>
    <updated>2012-08-22T08:45:00+00:00</updated>
    <id>http://pickardayune.com/blog/2012/08/22/serialized-attributes-in-activerecord-3-dot-2</id>
    <content type="html"><![CDATA[<p>Rails has had serialized attributes for a while, and every
time I try to do something fancy with them, I have to rediscover
how they work.</p>

<p>I have used <a href="http://apidock.com/rails/ActiveRecord/Aggregations/ClassMethods/composed_of"><code class="language-plaintext highlighter-rouge">composed_of</code></a>
to do some of these things in the past, so take a look at it if
<a href="http://apidock.com/rails/ActiveRecord/AttributeMethods/Serialization/ClassMethods/serialize"><code class="language-plaintext highlighter-rouge">serialize</code></a>
isn’t quite what you’re looking for.</p>

<h2 id="the-basics">The basics</h2>

<p>To get started with serialize, add a <code class="language-plaintext highlighter-rouge">text</code> column to your table,
and add the serialize directive to your model.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">MyModel</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
  <span class="c1"># This serializes whatever you assign.</span>
  <span class="n">serialize</span> <span class="ss">:my_field</span>
  <span class="c1"># This serializes a hash. If the DB value is nil, the AR value will be {}</span>
  <span class="n">serialize</span> <span class="ss">:my_field</span><span class="p">,</span> <span class="no">Hash</span>
  <span class="c1"># This serializes some class that you've written.</span>
  <span class="n">serialize</span> <span class="ss">:my_field</span><span class="p">,</span> <span class="no">MyField</span>
<span class="k">end</span></code></pre></figure>

<p>If you choose the last option, what aspects of serialization
can you control?</p>

<h2 id="default-serialization-with-yaml">Default serialization with YAML</h2>

<p>By default, your attribute will be serialized as YAML. Let’s say
you define MyField like this:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">MyField</span>
<span class="k">end</span></code></pre></figure>

<p>It will be serialized like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>--- !ruby/object:MyField {}
</code></pre></div></div>

<p>It will deserialize back to a <code class="language-plaintext highlighter-rouge">MyField</code> instance.</p>

<h2 id="custom-serialization">Custom serialization</h2>

<p>You can customize the serialization in a couple of different ways.
One way is to implement the instance method <code class="language-plaintext highlighter-rouge">to_yaml</code>. I wouldn’t
do this, because you’ll need to do it in a way that <code class="language-plaintext highlighter-rouge">Yaml.load</code> can
use to create an instance of your class.</p>

<p>The other way to do it is to add <code class="language-plaintext highlighter-rouge">dump</code> and <code class="language-plaintext highlighter-rouge">load</code> class methods to
your class. For example:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">MyField</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">dump</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
    <span class="c1"># ...</span>
  <span class="k">end</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">load</span><span class="p">(</span><span class="n">string</span><span class="p">)</span>
    <span class="c1"># ...</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p>Dump converts your object to a string, and load converts a string into
an instance of your class. Here’s an example of a custom formatting of
attributes:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">MyField</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">dump</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
    <span class="n">coder</span><span class="p">.</span><span class="nf">dump</span><span class="p">(</span><span class="ss">:a</span> <span class="o">=&gt;</span> <span class="n">obj</span><span class="p">.</span><span class="nf">a</span><span class="p">,</span> <span class="ss">:b</span> <span class="o">=&gt;</span> <span class="n">obj</span><span class="p">.</span><span class="nf">b</span><span class="p">)</span>
  <span class="k">end</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">load</span><span class="p">(</span><span class="n">string</span><span class="p">)</span>
    <span class="n">new</span> <span class="n">coder</span><span class="p">.</span><span class="nf">load</span><span class="p">(</span><span class="n">string</span><span class="p">)</span>
  <span class="k">end</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">coder</span>
    <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Coders</span><span class="o">::</span><span class="no">YAMLColumn</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="no">Hash</span><span class="p">)</span>
  <span class="k">end</span>
  <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">options</span> <span class="o">=</span> <span class="p">{})</span>
    <span class="vi">@a</span> <span class="o">=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:a</span><span class="p">]</span>
    <span class="vi">@b</span> <span class="o">=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:b</span><span class="p">]</span>
  <span class="k">end</span>
  <span class="nb">attr_accessor</span> <span class="ss">:a</span><span class="p">,</span> <span class="ss">:b</span>
<span class="k">end</span></code></pre></figure>

<p>Now, let’s say you want to be able to assign a hash to the serialized
object, maybe from a form. You can do that:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">MyField</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">dump</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
    <span class="k">case</span> <span class="n">obj</span>
    <span class="k">when</span> <span class="no">Hash</span> <span class="k">then</span> <span class="n">coder</span><span class="p">.</span><span class="nf">dump</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
    <span class="k">else</span>           <span class="n">coder</span><span class="p">.</span><span class="nf">dump</span><span class="p">(</span><span class="ss">:a</span> <span class="o">=&gt;</span> <span class="n">obj</span><span class="p">.</span><span class="nf">a</span><span class="p">,</span> <span class="ss">:b</span> <span class="o">=&gt;</span> <span class="n">obj</span><span class="p">.</span><span class="nf">b</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">load</span><span class="p">(</span><span class="n">string</span><span class="p">)</span>
    <span class="n">new</span> <span class="n">coder</span><span class="p">.</span><span class="nf">load</span><span class="p">(</span><span class="n">string</span><span class="p">)</span>
  <span class="k">end</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">coder</span>
    <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Coders</span><span class="o">::</span><span class="no">YAMLColumn</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="no">Hash</span><span class="p">)</span>
  <span class="k">end</span>
  <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">options</span> <span class="o">=</span> <span class="p">{})</span>
    <span class="vi">@a</span> <span class="o">=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:a</span><span class="p">]</span>
    <span class="vi">@b</span> <span class="o">=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:b</span><span class="p">]</span>
  <span class="k">end</span>
  <span class="nb">attr_accessor</span> <span class="ss">:a</span><span class="p">,</span> <span class="ss">:b</span>
<span class="k">end</span></code></pre></figure>

<p>It’s worth noting that you’ll be without the instance of MyField at first.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; rec = MyModel.new
&gt;&gt;&gt; rec.my_field.class
 =&gt; MyField
&gt;&gt;&gt; rec.my_field = {}
&gt;&gt;&gt; rec.my_field.class
 =&gt; Hash
&gt;&gt;&gt; rec.save
 =&gt; true
&gt;&gt;&gt; rec.my_field.class
 =&gt; MyField
</code></pre></div></div>

<p>So, another option is to override the setter on MyModel:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">MyModel</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
  <span class="n">serialize</span> <span class="ss">:my_field</span><span class="p">,</span> <span class="no">MyField</span>
  <span class="n">attr_accessible</span> <span class="ss">:my_field</span>
  <span class="k">def</span> <span class="nf">my_field</span><span class="o">=</span> <span class="n">value</span>
    <span class="k">case</span> <span class="n">value</span>
    <span class="k">when</span> <span class="no">Hash</span>
      <span class="k">super</span> <span class="no">MyField</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
    <span class="k">else</span>
      <span class="k">super</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; rec = MyModel.new
&gt;&gt;&gt; rec.my_field.class
 =&gt; MyField
&gt;&gt;&gt; rec.my_field = {}
&gt;&gt;&gt; rec.my_field.class
 =&gt; MyField
&gt;&gt;&gt; rec.save
 =&gt; true
&gt;&gt;&gt; rec.my_field.class
 =&gt; MyField
&gt;&gt;&gt; rec.attributes = {:my_field =&gt; {}}
&gt;&gt;&gt; rec.my_field.class
 =&gt; MyField
</code></pre></div></div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Cache with method replacement in ruby]]></title>
    <link href="http://pickardayune.com/blog/2012/07/04/cache-with-method-replacement-in-ruby"/>
    <updated>2012-07-04T09:49:00+00:00</updated>
    <id>http://pickardayune.com/blog/2012/07/04/cache-with-method-replacement-in-ruby</id>
    <content type="html"><![CDATA[<p>After my last post, about
<a href="/blog/2012/07/02/clever-caching-on-javascript-objects">caching method results in javascript</a>,
I wondered if I could do the same thing in ruby.</p>

<p>Here’s the basic class:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">NoCaching</span>
  <span class="nb">attr_accessor</span> <span class="ss">:a</span><span class="p">,</span> <span class="ss">:b</span>
  <span class="k">def</span> <span class="nf">sum</span>
    <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">+</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">+</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">+</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">+</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">+</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p>As expected, sum is evaluated every time you call it.</p>

<p>For comparison, I created a cached version using ActiveSupport::Memoizable.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="nb">require</span> <span class="s1">'active_support/memoizable'</span>
<span class="k">class</span> <span class="nc">CachedWithActiveSupport</span> <span class="o">&lt;</span> <span class="no">NoCaching</span>
  <span class="kp">extend</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">Memoizable</span>
  <span class="n">memoize</span> <span class="ss">:sum</span>
<span class="k">end</span></code></pre></figure>

<p>As expected, calling sum on <code class="language-plaintext highlighter-rouge">CachedWithActiveSupport</code> returns the same thing,
regardless of changes to <code class="language-plaintext highlighter-rouge">a</code> or <code class="language-plaintext highlighter-rouge">b</code>.</p>

<p>Finally, I created a class with a new memoizer.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">CachedWithRedefinedMethod</span> <span class="o">&lt;</span> <span class="no">NoCaching</span>
  <span class="kp">extend</span> <span class="no">RedefinedMethodCaching</span>
  <span class="n">memoize</span> <span class="ss">:sum</span>
<span class="k">end</span></code></pre></figure>

<p>This new memoizer will, on the first call to the memoized method, create a singleton
method on the instance that just returns the memoized value.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">module</span> <span class="nn">RedefinedMethodCaching</span>
  <span class="k">def</span> <span class="nf">memoize</span> <span class="nb">method</span>
    <span class="n">original_method</span> <span class="o">=</span> <span class="nb">instance_method</span><span class="p">(</span><span class="nb">method</span><span class="p">)</span>
    <span class="n">define_method</span> <span class="nb">method</span> <span class="k">do</span>
      <span class="n">value</span> <span class="o">=</span> <span class="n">original_method</span><span class="p">.</span><span class="nf">bind</span><span class="p">(</span><span class="nb">self</span><span class="p">).</span><span class="nf">call</span>
      <span class="nb">class_eval</span> <span class="k">do</span>
        <span class="n">define_method</span> <span class="nb">method</span> <span class="k">do</span>
          <span class="n">value</span>
        <span class="k">end</span>
      <span class="k">end</span>
      <span class="nb">send</span> <span class="nb">method</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p><code class="language-plaintext highlighter-rouge">CachedWithRedefinedMethod</code> has the same basic behavior as <code class="language-plaintext highlighter-rouge">CachedWithActiveSupport</code>.</p>

<h2 id="performance">Performance</h2>

<p>At this point, I got curious about performance. One of the reasons to cache
a method’s result is to avoid some performance hit, so we don’t want to
introduce another performance hit. Here’s the basic benchmark:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="nb">require</span> <span class="s1">'benchmark'</span>
<span class="no">Benchmark</span><span class="p">.</span><span class="nf">bm</span><span class="p">(</span><span class="mi">35</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
  <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">100</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mi">10000</span><span class="p">].</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">usage</span><span class="o">|</span>
    <span class="n">iterations</span> <span class="o">=</span> <span class="mi">500000</span> <span class="o">/</span> <span class="n">usage</span>
    <span class="p">[</span><span class="no">NoCaching</span><span class="p">,</span> <span class="no">CachedWithActiveSupport</span><span class="p">,</span> <span class="no">CachedWithRedefinedMethod</span><span class="p">].</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">k</span><span class="o">|</span>
      <span class="n">x</span><span class="p">.</span><span class="nf">report</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="n">usage</span><span class="si">}</span><span class="s2">x</span><span class="si">#{</span><span class="n">k</span><span class="p">.</span><span class="nf">name</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span> <span class="p">{</span> <span class="n">iterations</span><span class="p">.</span><span class="nf">times</span> <span class="p">{</span> <span class="n">o</span> <span class="o">=</span> <span class="n">k</span><span class="p">.</span><span class="nf">new</span> <span class="p">;</span> <span class="n">o</span><span class="p">.</span><span class="nf">a</span> <span class="o">=</span> <span class="mi">10</span> <span class="p">;</span> <span class="n">o</span><span class="p">.</span><span class="nf">b</span> <span class="o">=</span> <span class="mi">20</span> <span class="p">;</span> <span class="n">usage</span><span class="p">.</span><span class="nf">times</span> <span class="p">{</span> <span class="n">o</span><span class="p">.</span><span class="nf">sum</span> <span class="p">}</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p>Here’s my ruby:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-darwin11.2.0]
</code></pre></div></div>

<p>Here are the results:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>                                          user     system      total        real
1xNoCaching                           0.740000   0.010000   0.750000 (  0.739076)
1xCachedWithActiveSupport             1.080000   0.000000   1.080000 (  1.140270)
1xCachedWithRedefinedMethod           5.100000   0.070000   5.170000 (  5.187266)

10xNoCaching                          0.460000   0.000000   0.460000 (  0.461452)
10xCachedWithActiveSupport            0.250000   0.000000   0.250000 (  0.253478)
10xCachedWithRedefinedMethod          0.560000   0.000000   0.560000 (  0.567997)

100xNoCaching                         0.420000   0.000000   0.420000 (  0.421145)
100xCachedWithActiveSupport           0.230000   0.000000   0.230000 (  0.224381)
100xCachedWithRedefinedMethod         0.120000   0.000000   0.120000 (  0.127860)

1000xNoCaching                        0.420000   0.000000   0.420000 (  0.419429)
1000xCachedWithActiveSupport          0.190000   0.000000   0.190000 (  0.187462)
1000xCachedWithRedefinedMethod        0.080000   0.010000   0.090000 (  0.083700)

10000xNoCaching                       0.380000   0.000000   0.380000 (  0.383493)
10000xCachedWithActiveSupport         0.200000   0.000000   0.200000 (  0.196237)
10000xCachedWithRedefinedMethod       0.100000   0.000000   0.100000 (  0.106058)
</code></pre></div></div>

<p>Notice that, uncached, the times are pretty consistent. The number of calls to sum is
the same in each run (500,000), so this is expected.</p>

<p>For ActiveSupport’s memoize, you can see the overhead on the 1x run, and you can see
the performance gain that even a small number of reps gives.</p>

<p>For the new, redefined method style of memoization, you can see there’s a pretty big
overhead, but the performance gain is significant. I compared it to the simple style
of memoization (<code class="language-plaintext highlighter-rouge">@sum ||= ...</code>), and it’s about the same.</p>

<h2 id="conclusions">Conclusions</h2>

<p>This was an interesting experiment, but I probably won’t use it.</p>

<p>While the performance gain is pretty nice, it’s also not a general purpose solution.
In my applications, most memoized methods are only called a handful of times. For
that type of use, memoization comes with a penalty, rather than a payoff.</p>

<p>Also, comparing to ActiveSupport’s memoization is unfair, as ActiveSupport provides
a couple other nice features. One is cache-busting, via an optional <code class="language-plaintext highlighter-rouge">force</code> argument.
Another is support for arguments (i.e. <code class="language-plaintext highlighter-rouge">cached_method(1)</code> is different from <code class="language-plaintext highlighter-rouge">cached_method(2)</code>).</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[clever caching on javascript objects]]></title>
    <link href="http://pickardayune.com/blog/2012/07/02/clever-caching-on-javascript-objects"/>
    <updated>2012-07-02T10:39:00+00:00</updated>
    <id>http://pickardayune.com/blog/2012/07/02/clever-caching-on-javascript-objects</id>
    <content type="html"><![CDATA[<p>Javascript sports a prototype inheritance model. This morning, I was working on
a Javascript object, and I wanted to lazily evaluate one of its properties.
Normally, I’d write it like this:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">Thing</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span><span class="nx">b</span><span class="p">)</span> <span class="p">{</span> <span class="k">this</span><span class="p">.</span><span class="nx">a</span> <span class="o">=</span> <span class="nx">a</span><span class="p">;</span> <span class="k">this</span><span class="p">.</span><span class="nx">b</span> <span class="o">=</span> <span class="nx">b</span><span class="p">;</span> <span class="p">}</span>
<span class="nx">Thing</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">add</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="k">this</span><span class="p">.</span><span class="nx">_sum</span><span class="p">)</span> <span class="k">this</span><span class="p">.</span><span class="nx">_sum</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">a</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">b</span><span class="p">;</span>
  <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">_sum</span><span class="p">;</span>
<span class="p">};</span></code></pre></figure>

<p>Today, I thought, “Maybe I can make a singleton method (or whatever that’s called
in Javascript) that caches the result?”</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">Thing</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span><span class="nx">b</span><span class="p">)</span> <span class="p">{</span> <span class="k">this</span><span class="p">.</span><span class="nx">a</span> <span class="o">=</span> <span class="nx">a</span><span class="p">;</span> <span class="k">this</span><span class="p">.</span><span class="nx">b</span> <span class="o">=</span> <span class="nx">b</span><span class="p">;</span> <span class="p">}</span>
<span class="nx">Thing</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">add</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">sum</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">a</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">b</span><span class="p">;</span>
  <span class="k">this</span><span class="p">.</span><span class="nx">add</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">sum</span><span class="p">;</span> <span class="p">}</span>
  <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">add</span><span class="p">();</span>
<span class="p">};</span></code></pre></figure>

<p>The last line could return <code class="language-plaintext highlighter-rouge">sum</code>, but it adds to the cleverness to return
what looks like a recursive call.</p>

<p>I tried this out in Chrome’s JS console in order to verify a couple of things.</p>

<p>First, does it return the right answer?</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; var x = new Thing(1,2);
&gt; x.add()
3
</code></pre></div></div>

<p>Did I do the singleton thing right? i.e. does each instance have an independent cached value?</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; var y = new Thing(2,3);
&gt; y.add()
5
</code></pre></div></div>

<p>Does the function change, as expected?</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; var x = new Thing(1,2);
&gt; x.add
function () {
  var sum = this.a + this.b;
  this.add = function() { return sum; }
  return this.add();
}
&gt; x.add()
3
&gt; x.add
function () { return sum; }
</code></pre></div></div>

<p>And, finally, can I invalidate the cache?</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; x.a = 4
4
&gt; x.add() // returns the old value
3
&gt; delete x.add // invalidate the cache
true
&gt; x.add() // returns the new value
6
</code></pre></div></div>

<p>I don’t know if I like this enough to keep using it, but it seems simple and pliable
enough to be worth trying. Thoughts? <a href="http://twitter.com/spraints">Drop me a line on twitter</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[rails 3 exception handling]]></title>
    <link href="http://pickardayune.com/blog/2012/06/25/rails-3-exception-handling"/>
    <updated>2012-06-25T11:00:00+00:00</updated>
    <id>http://pickardayune.com/blog/2012/06/25/rails-3-exception-handling</id>
    <content type="html"><![CDATA[<p>Rails exception handling is pretty flexible. In development, it shows detailed
error information. In production, it shows a user-friendly page, possibly
of your choice. In any environment, it provides hooks that you can use to
customize the process.</p>

<p>In this blog post, I’d like to show how to do some neat exception handling
tricks with rails 3.</p>

<h2 id="trick-1---use-a-custom-exception">Trick #1 - Use a custom exception</h2>

<p>Using a custom exception is simple. Just define the exception class</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">MyCustomException</span> <span class="o">&lt;</span> <span class="no">StandardError</span> <span class="p">;</span> <span class="k">end</span></code></pre></figure>

<p>and raise an exception.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">raise</span> <span class="no">MyCustomException</span></code></pre></figure>

<p>In development, you’ll see the detailed exception page, including the
exception’s type, message, and stack trace. In production, rails renders
the default, generic exception page, normally stored in public/500.html.</p>

<h2 id="trick-2---custom-exception-status-code">Trick #2 - Custom exception status code</h2>

<p>If you want the exception to produce a different HTTP result status, you need
to tell rails about it. The default is 500.</p>

<p>The way to customize the result code has changed slightly in different releases of
rails. Here are some ways to tell rails how to handle the exception.</p>

<p>In all versions of rails, you can refer to HTTP status codes numerically or with
<a href="https://github.com/rack/rack/blob/edc8b923fa4ea4e3c1ce8778f5ddbc89688bc01b/lib/rack/utils.rb#L473">symbols as defined by Rack</a>.
For example, you can refer to ‘404 Not Found’ as <code class="language-plaintext highlighter-rouge">:not_found</code> or <code class="language-plaintext highlighter-rouge">404</code>.</p>

<p>In <strong>Rails 3.0 and 3.1</strong>, you can change the status code of an exception’s response
with <code class="language-plaintext highlighter-rouge">rescue_responses</code>:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="no">ActionDispatch</span><span class="o">::</span><span class="no">ShowExceptions</span><span class="p">.</span><span class="nf">rescue_responses</span><span class="p">[</span><span class="s1">'MyCustomException'</span><span class="p">]</span> <span class="o">=</span> <span class="ss">:unauthorized</span></code></pre></figure>

<p>There are a few <a href="https://github.com/rails/rails/blob/3-0-stable/actionpack/lib/action_dispatch/middleware/show_exceptions.rb">default exception handlers</a>.</p>

<p>In <strong>Rails 3.2</strong>, this hash moved, to make it easier to update via a railtie.
You can change the status code of an exception’s response in your
application configuration (e.g. <code class="language-plaintext highlighter-rouge">config/application.rb</code> or
<code class="language-plaintext highlighter-rouge">config/environments/development.rb</code>):</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">config</span><span class="p">.</span><span class="nf">action_dispatch</span><span class="p">.</span><span class="nf">rescue_responses</span><span class="p">.</span><span class="nf">merge!</span><span class="p">(</span><span class="s1">'MyCustomException'</span> <span class="o">=&gt;</span> <span class="ss">:unauthorized</span><span class="p">)</span></code></pre></figure>

<p>In public (i.e. production), rails will render the exception from a
file in <code class="language-plaintext highlighter-rouge">public/</code>, with the status code as its name. For example, if
the result status is 404, rails will read and return <code class="language-plaintext highlighter-rouge">public/404.html</code>.
In <strong>Rails 3.2</strong>, you can override this behavior by setting <code class="language-plaintext highlighter-rouge">config.exceptions_app</code>.
See <a href="https://github.com/rails/rails/blob/v3.2.6/actionpack/lib/action_dispatch/middleware/public_exceptions.rb">ActionDispatch::PublicExceptions</a>
for an example of what this should look like.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">MyPublicExceptions</span>
  <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="n">env</span><span class="p">)</span>
    <span class="p">[</span><span class="mi">404</span><span class="p">,</span> <span class="p">{</span><span class="s1">'Content-Type'</span> <span class="o">=&gt;</span> <span class="s1">'text/plain'</span><span class="p">},</span> <span class="p">[</span><span class="s1">'not found'</span><span class="p">]]</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="c1"># in config/application.rb</span>
<span class="n">config</span><span class="p">.</span><span class="nf">exceptions_app</span> <span class="o">=</span> <span class="no">MyPublicExceptions</span><span class="p">.</span><span class="nf">new</span></code></pre></figure>

<h2 id="trick-3---custom-exception-handler-on-controller">Trick #3 - Custom exception handler on controller</h2>

<p>If you want to do something else with your exceptions, you can define a
custom exception handler on a controller. For example, in <code class="language-plaintext highlighter-rouge">ApplicationController</code>,
you can add this:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">rescue_from</span> <span class="s1">'MyCustomException'</span><span class="p">,</span> <span class="ss">:with</span> <span class="o">=&gt;</span> <span class="ss">:my_exception_handler</span>

<span class="k">def</span> <span class="nf">my_exception_handler</span> <span class="n">exception</span> <span class="c1"># This method can take 0 or 1 args</span>
  <span class="n">render</span> <span class="ss">:template</span> <span class="o">=&gt;</span> <span class="s1">'blah/blah'</span>
<span class="k">end</span></code></pre></figure>

<p>The nice thing about this is that you can completely control how the exception
is rendered. Unfortunately, using this form of rescue short-circuits other
‘normal’ exception handling. So, it will always call the handler, even in
development. It will not bubble up to the airbrake notification middleware.</p>

<h2 id="trick-4---production-exception-handling-in-development">Trick #4 - Production exception handling in development</h2>

<p>As you build up more intricate exceptions &amp; handlers, you’ll want to
try out your custom handlers in development.</p>

<p>In development mode, you’ll need to do a couple of things to view the
production-style exception pages. First, you need to turn off the config
flag that forces all requests to behave as if they’re local:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># in config/environments/development.rb</span>
<span class="n">config</span><span class="p">.</span><span class="nf">consider_all_requests_local</span>       <span class="o">=</span> <span class="kp">false</span> <span class="c1"># true by default</span></code></pre></figure>

<p>In <strong>Rails 3.2</strong>, that should be all you need to do. You should now see
production-style exception pages.</p>

<p>In <strong>Rails 3.0 and 3.1</strong>, you’ll also need to convice rails that the
request isn’t local. I’m not sure what the best way to do this is, but
one way that worked for me was to add this to the bottom of
<code class="language-plaintext highlighter-rouge">app/controllers/application_controller.rb</code>:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">ActionDispatch::Request</span>
  <span class="k">def</span> <span class="nf">local?</span>
    <span class="kp">false</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Killing complexity with TDD]]></title>
    <link href="http://pickardayune.com/blog/2012/05/18/killing-complexity-with-tdd"/>
    <updated>2012-05-18T06:30:00+00:00</updated>
    <id>http://pickardayune.com/blog/2012/05/18/killing-complexity-with-tdd</id>
    <content type="html"><![CDATA[<p><em>Sometimes it’s the small things…</em></p>

<h1 id="in-short">In short</h1>

<p>I’m working on an API that can take one of its arguments in a couple of different forms.
TDD helped me quickly see where I was going to end up with some combinatorial complexity, so I quickly changed my design to avoid the complexity.</p>

<h1 id="my-rails-controller">My Rails controller</h1>

<p>It’s a common thing: add a user to a group.
The old UI allows adding 1 user at a time.
The new UI allows adding any number of users at a time.
I’m planning to support both.</p>

<p>Here’s what the original controller, supporting the old UI, might look like:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">GroupMembersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
  <span class="c1"># POST /groups/:group_id/members</span>
  <span class="k">def</span> <span class="nf">create</span>
    <span class="n">group</span> <span class="o">=</span> <span class="no">Group</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:group_id</span><span class="p">])</span>
    <span class="k">if</span> <span class="n">group</span><span class="p">.</span><span class="nf">users</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">:id</span> <span class="o">=&gt;</span> <span class="n">params</span><span class="p">[</span><span class="ss">:user_id</span><span class="p">]).</span><span class="nf">count</span><span class="p">.</span><span class="nf">zero?</span>
      <span class="n">group</span><span class="p">.</span><span class="nf">users</span> <span class="o">&lt;&lt;</span> <span class="no">User</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:user_id</span><span class="p">])</span>
    <span class="n">redirect_to</span> <span class="n">root_path</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p>I got the new UI working, and needed to update the controller.
Being that it was so simple of a controller, I had previously skipped unit tests for it.
So, I spun up a new unit test suite with tests to catch any regressions…</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">GroupMembersControllerTest</span> <span class="o">&lt;</span> <span class="no">ActionController</span><span class="o">::</span><span class="no">TestCase</span>
  <span class="n">setup</span> <span class="k">do</span>
    <span class="vi">@group</span> <span class="o">=</span> <span class="no">Group</span><span class="p">.</span><span class="nf">create!</span>
  <span class="k">end</span>

  <span class="nb">test</span> <span class="s1">'adds a group member'</span> <span class="k">do</span>
    <span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">create!</span>
    <span class="n">post</span> <span class="ss">:create</span><span class="p">,</span> <span class="ss">:group_id</span> <span class="o">=&gt;</span> <span class="vi">@group</span><span class="p">.</span><span class="nf">id</span><span class="p">,</span> <span class="ss">:user_id</span> <span class="o">=&gt;</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">id</span>
    <span class="n">assert_equal</span> <span class="p">[</span><span class="vi">@user</span><span class="p">],</span> <span class="vi">@group</span><span class="p">.</span><span class="nf">reload</span><span class="p">.</span><span class="nf">users</span>
  <span class="k">end</span>

  <span class="nb">test</span> <span class="s1">'does not re-add a member'</span> <span class="k">do</span>
    <span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">create!</span>
    <span class="vi">@group</span><span class="p">.</span><span class="nf">users</span> <span class="o">&lt;&lt;</span> <span class="vi">@user</span>
    <span class="n">post</span> <span class="ss">:create</span><span class="p">,</span> <span class="ss">:group_id</span> <span class="o">=&gt;</span> <span class="vi">@group</span><span class="p">.</span><span class="nf">id</span><span class="p">,</span> <span class="ss">:user_id</span> <span class="o">=&gt;</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">id</span>
    <span class="n">assert_equal</span> <span class="p">[</span><span class="vi">@user</span><span class="p">],</span> <span class="vi">@group</span><span class="p">.</span><span class="nf">reload</span><span class="p">.</span><span class="nf">users</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p>Now to add the multi-user test.
(In this case, the UI is building a single input with a ‘,’-delimited list of user ids.)
Here’s the first test:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby">  <span class="nb">test</span> <span class="s1">'adds two members'</span> <span class="k">do</span>
    <span class="vi">@user1</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">create!</span>
    <span class="vi">@user2</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">create!</span>
    <span class="n">post</span> <span class="ss">:create</span><span class="p">,</span> <span class="ss">:group_id</span> <span class="o">=&gt;</span> <span class="vi">@group</span><span class="p">.</span><span class="nf">id</span><span class="p">,</span> <span class="ss">:user_ids</span> <span class="o">=&gt;</span> <span class="s2">"</span><span class="si">#{</span><span class="vi">@user1</span><span class="p">.</span><span class="nf">id</span><span class="si">}</span><span class="s2">,</span><span class="si">#{</span><span class="vi">@user2</span><span class="p">.</span><span class="nf">id</span><span class="si">}</span><span class="s2">"</span>
    <span class="n">assert_equal</span> <span class="p">[</span><span class="vi">@user1</span><span class="p">,</span> <span class="vi">@user2</span><span class="p">],</span> <span class="vi">@group</span><span class="p">.</span><span class="nf">reload</span><span class="p">.</span><span class="nf">users</span>
  <span class="k">end</span></code></pre></figure>

<p>In the back of my mind, I start thinking about other tests I’ll need to write.
One set of tests that comes to mind is the case where a :user_id and :user_ids are both passed in.</p>

<p>Hm. How can I avoid writing all these combination-testing tests?
Well, seeing as 2! is bigger than 1!,
if I can figure out how to drop the number of handled parameters from 2 to 1,
I’ll avoid the extra complexity.</p>

<p>In this case, <code class="language-plaintext highlighter-rouge">:user_id =&gt; '1'</code> and <code class="language-plaintext highlighter-rouge">:user_ids =&gt; '1'</code> should behave the same,
so there’s really no need for two different parameters. A quick UI &amp; test change …</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby">  <span class="nb">test</span> <span class="s1">'adds two members'</span> <span class="k">do</span>
    <span class="vi">@user1</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">create!</span>
    <span class="vi">@user2</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">create!</span>
    <span class="n">post</span> <span class="ss">:create</span><span class="p">,</span> <span class="ss">:group_id</span> <span class="o">=&gt;</span> <span class="vi">@group</span><span class="p">.</span><span class="nf">id</span><span class="p">,</span> <span class="ss">:user_id</span> <span class="o">=&gt;</span> <span class="s2">"</span><span class="si">#{</span><span class="vi">@user1</span><span class="p">.</span><span class="nf">id</span><span class="si">}</span><span class="s2">,</span><span class="si">#{</span><span class="vi">@user2</span><span class="p">.</span><span class="nf">id</span><span class="si">}</span><span class="s2">"</span>
    <span class="n">assert_equal</span> <span class="p">[</span><span class="vi">@user1</span><span class="p">,</span> <span class="vi">@user2</span><span class="p">],</span> <span class="vi">@group</span><span class="p">.</span><span class="nf">reload</span><span class="p">.</span><span class="nf">users</span>
  <span class="k">end</span></code></pre></figure>

<p>… and I’ve crossed off several tests in my mental checklist.</p>

<p>The API isn’t necessarily ideal (I’m mixing up singular and plural concepts).
But, I get a simpler API that still supports the old UI.</p>

<h1 id="wrap-up">Wrap up</h1>

<p>In this case, the added complexity was relatively small (only two choices),
so the savings in test effort was minimal. Also, I don’t know that I would have
actually tested the extra cases, because they’re not that likely or interesting.</p>

<p>However, I think the principal applies: TDD helps you spot complexity as it’s
forming, and trim it back to a reasonable level.</p>

<p>Also, I just didn’t have to think any extra “what-ifs”.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[bundler environment variables]]></title>
    <link href="http://pickardayune.com/blog/2012/05/04/bundler-environment-variables"/>
    <updated>2012-05-04T17:00:00+00:00</updated>
    <id>http://pickardayune.com/blog/2012/05/04/bundler-environment-variables</id>
    <content type="html"><![CDATA[<p>Here are some environment variables that <a href="http://gembundler.com/">bundler</a> uses. This is only
the bundler-specific variables. I’m leaving out other environment
variables, like RUBYOPT or PATH, that bundler uses, but that are used
by other things on the system, too. There is a partial list in
<a href="http://gembundler.com/man/bundle-config.1.html">the bundle-config man page</a>.</p>

<p>Some of the values are accessed through <code class="language-plaintext highlighter-rouge">Bundler::Settings</code>. Any values accessed there can
be set in a local (<code class="language-plaintext highlighter-rouge">./.bundle/config</code>) or global (<code class="language-plaintext highlighter-rouge">~/.bundle/config</code>) settings file. The order
of precedence is: local, environment, global.</p>

<p>Incidentally, while looking through bundler 1.1.1’s code, I learned that you can
trigger whether to load a particular gem with environment variables. So, for example,
if you say <code class="language-plaintext highlighter-rouge">gem 'debugger', :env =&gt; 'USE_DEBUGGER'</code>, it only loads the debugger
gem if <code class="language-plaintext highlighter-rouge">USE_DEBUGGER</code> is set; or, if you say <code class="language-plaintext highlighter-rouge">gem 'debugger', :env =&gt; { 'USE_DEBUGGER' =&gt; 'yes' }</code>,
then it only loads the debugger gem if <code class="language-plaintext highlighter-rouge">USE_DEBUGGER</code> is set to <code class="language-plaintext highlighter-rouge">yes</code>.</p>

<table>
  <thead>
    <tr>
      <th>Variable</th>
      <th>Description</th>
      <th>Source reference</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLER_EDITOR</code></td>
      <td>editor to use for commands like <code class="language-plaintext highlighter-rouge">bundle open</code>, defaults to <code class="language-plaintext highlighter-rouge">$VISUAL</code> or <code class="language-plaintext highlighter-rouge">$EDITOR</code>.)</td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/cli.rb">bundler/cli.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_APP_CONFIG</code></td>
      <td>path to directory where bundler stores local configuration, defaults to <code class="language-plaintext highlighter-rouge">./bundle/config</code></td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler.rb">bundler.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_BIN_PATH</code></td>
      <td> </td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/rubygems_integration.rb">bundler/rubygems_integration.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/runtime.rb">bundler/runtime.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_BIN</code> (<code class="language-plaintext highlighter-rouge">settings[:bin]</code>)</td>
      <td> </td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler.rb">bundler.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/installer.rb">bundler/installer.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_CLEAN</code> (<code class="language-plaintext highlighter-rouge">settings[:clean]</code>)</td>
      <td>Run <code class="language-plaintext highlighter-rouge">bundle clean</code> during <code class="language-plaintext highlighter-rouge">bundle install</code> and <code class="language-plaintext highlighter-rouge">bundle update</code></td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/cli.rb">bundler/cli.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_CONFIG</code></td>
      <td>global bundler settings file, defaults to <code class="language-plaintext highlighter-rouge">~/.bundle/config</code></td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/settings.rb">bundler/settings.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_DISABLE_SHARED_GEMS</code> (<code class="language-plaintext highlighter-rouge">settings[:disable_shared_gems]</code>)</td>
      <td>if set, bundle won’t use shared (system) gems</td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler.rb">bundler.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_FROZEN</code> (<code class="language-plaintext highlighter-rouge">settings[:frozen]</code>)</td>
      <td>used internally</td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/cli.rb">bundler/cli.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/definition.rb">bundler/definition.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/installer.rb">bundler/installer.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_GEMFILE</code></td>
      <td>path to the gemfile</td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/cli.rb">bundler/cli.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/runtime.rb">bundler/runtime.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/shared_helpers.rb">bundler/shared_helpers.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_NO_PRUNE</code> (<code class="language-plaintext highlighter-rouge">settings[:no_prune]</code>)</td>
      <td>Don’t remove stale gems from the cache</td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/cli.rb">bundler/cli.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/runtime.rb">bundler/runtime.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_PATH</code> (<code class="language-plaintext highlighter-rouge">settings.path</code> or <code class="language-plaintext highlighter-rouge">settings[:path]</code>)</td>
      <td>where bundler should install your gems, defaults to the shared (system) gem path</td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/settings.rb">bundler/settings.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/cli.rb">bundler/cli.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/installer.rb">bundler/installer.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_SPEC_RUN</code></td>
      <td>used in bundler’s tests</td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/shared_helpers.rb">bundler/shared_helpers.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_SYSTEM_BINDIR</code> (<code class="language-plaintext highlighter-rouge">settings[:system_bindir]</code>)</td>
      <td>overridden gem binstub directory, similar to <code class="language-plaintext highlighter-rouge">-n</code> in <code class="language-plaintext highlighter-rouge">.gemrc</code></td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler.rb">bundler.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BUNDLE_WITHOUT</code> (<code class="language-plaintext highlighter-rouge">settings.without</code>)</td>
      <td>list of groups to exclude, :-separated</td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/cli.rb">bundler/cli.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/definition.rb">bundler/definition.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">DEBUG</code>, <code class="language-plaintext highlighter-rouge">DEBUG_RESOLVER</code></td>
      <td>outputs debug logs</td>
      <td><a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/resolver.rb">bundler/resolver.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/setup.rb">bundler/setup.rb</a>, <a href="https://github.com/carlhuda/bundler/blob/v1.1.1/lib/bundler/ui.rb">bundler/ui.rb</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">HTTP_PROXY</code>, <code class="language-plaintext highlighter-rouge">HTTP_PROXY_USER</code>, <code class="language-plaintext highlighter-rouge">HTTP_PROXY_PASS</code></td>
      <td>configures an HTTP proxy</td>
      <td> </td>
    </tr>
  </tbody>
</table>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[accurate and lazy config errors]]></title>
    <link href="http://pickardayune.com/blog/2012/02/15/accurate-and-lazy-config-errors"/>
    <updated>2012-02-15T16:21:00+00:00</updated>
    <id>http://pickardayune.com/blog/2012/02/15/accurate-and-lazy-config-errors</id>
    <content type="html"><![CDATA[<p>What is better than being exactly right?
What about being lazy?
How about both?</p>

<p>This was a thought experiment that has migrated through code and into this post.</p>

<p>Here’s the thought:
I write a ruby library that you have to configure, but I don’t want to
pre-check all the config. I also want the exception that I through to come from
the bad config value, not from some weird-o spot in your and my code where we
both have a hard time figuring out what the problem is.</p>

<p>Can we pull off being lazy and accurate?</p>

<p>Here’s one way to do it:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Config</span>
  <span class="k">def</span> <span class="nf">driver</span><span class="o">=</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
    <span class="k">if</span><span class="p">((</span><span class="n">exc</span> <span class="o">=</span> <span class="nb">callcc</span> <span class="p">{</span> <span class="o">|</span><span class="n">cont</span><span class="o">|</span> <span class="vi">@driver_ptr</span> <span class="o">=</span> <span class="n">cont</span> <span class="p">})</span> <span class="o">&amp;&amp;</span> <span class="n">exc</span><span class="p">.</span><span class="nf">is_a?</span><span class="p">(</span><span class="no">Exception</span><span class="p">))</span>
      <span class="k">raise</span> <span class="n">exc</span>
    <span class="k">end</span>
    <span class="vi">@driver</span> <span class="o">=</span> <span class="n">d</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">try</span>
    <span class="vi">@driver_ptr</span><span class="p">.</span><span class="nf">call</span> <span class="no">ArgumentError</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"Driver cannot be :fail"</span><span class="p">)</span> <span class="k">if</span> <span class="vi">@driver</span> <span class="o">==</span> <span class="ss">:fail</span>
    <span class="nb">puts</span> <span class="vi">@driver</span><span class="p">.</span><span class="nf">inspect</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="n">config</span> <span class="o">=</span> <span class="no">Config</span><span class="p">.</span><span class="nf">new</span>

<span class="n">config</span><span class="p">.</span><span class="nf">driver</span> <span class="o">=</span> <span class="ss">:ok</span>
<span class="n">config</span><span class="p">.</span><span class="nf">try</span>

<span class="n">config</span><span class="p">.</span><span class="nf">driver</span> <span class="o">=</span> <span class="ss">:yes</span>
<span class="n">config</span><span class="p">.</span><span class="nf">try</span>

<span class="n">config</span><span class="p">.</span><span class="nf">driver</span> <span class="o">=</span> <span class="ss">:fail</span>
<span class="nb">puts</span> <span class="s2">"Note that the error happens the line before this one (this line = </span><span class="si">#{</span><span class="kp">__LINE__</span><span class="si">}</span><span class="s2">)"</span>
<span class="n">config</span><span class="p">.</span><span class="nf">try</span>

<span class="n">config</span><span class="p">.</span><span class="nf">driver</span> <span class="o">=</span> <span class="ss">:not_reached</span>
<span class="n">config</span><span class="p">.</span><span class="nf">try</span></code></pre></figure>

<p>And, the output:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>:ok
:yes
Note that the error happens the line before this one (this line = 24)
wacky.rb:4:in `driver=': Driver cannot be :fail (ArgumentError)
        from wacky.rb:23
</code></pre></div></div>

<p>I don’t think I’d use this on a general purpose library, because of the ease of creating an infinite loop…</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">begin</span>
  <span class="n">config</span><span class="p">.</span><span class="nf">driver</span> <span class="o">=</span> <span class="ss">:fail</span>
<span class="k">rescue</span> <span class="o">=&gt;</span> <span class="n">e</span>
  <span class="nb">puts</span> <span class="n">e</span>
<span class="k">end</span>
<span class="n">config</span><span class="p">.</span><span class="nf">try</span></code></pre></figure>

<p>… but it was fun to try it out.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[factory_girl and a tree of related objects]]></title>
    <link href="http://pickardayune.com/blog/2012/01/13/factory-girl-and-a-tree-of-related-objects"/>
    <updated>2012-01-13T10:48:00+00:00</updated>
    <id>http://pickardayune.com/blog/2012/01/13/factory-girl-and-a-tree-of-related-objects</id>
    <content type="html"><![CDATA[<p>My fixture replacement of choice is <a href="https://github.com/thoughtbot/factory_girl/">factory_girl</a>.
In general, it’s been very good. But, as with any tool, there are edge cases that just don’t work
as well. This is a common use case for me. It seems common enough that there should be a good solution
for it, but I haven’t googled it up yet.</p>

<h2 id="the-problem">The problem</h2>

<p>The pattern is that I have a root model, with a couple of collections living inside it.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Site</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
  <span class="n">has_many</span> <span class="ss">:members</span>
  <span class="n">has_many</span> <span class="ss">:posts</span>
<span class="k">end</span></code></pre></figure>

<p>One of the collections is made of objects that are just nested…</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Member</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
  <span class="n">belongs_to</span> <span class="ss">:site</span>
  <span class="n">has_many</span> <span class="ss">:posts</span>
<span class="k">end</span></code></pre></figure>

<p>… and the other is associated with both.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Post</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
  <span class="n">belongs_to</span> <span class="ss">:author</span><span class="p">,</span> <span class="ss">:class_name</span> <span class="o">=&gt;</span> <span class="s1">'Member'</span>
  <span class="n">belongs_to</span> <span class="ss">:site</span>
<span class="k">end</span></code></pre></figure>

<p>(An obvious solution to this problem is to drop the
<code class="language-plaintext highlighter-rouge">belongs_to :site</code> from Post, but that’s not always
desirable. Sometimes it just doesn’t work, if Post and
Member had a habtm association, and neither depended on
the other’s existence.)</p>

<p>The straightforward factories for the models above is this:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:site</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
<span class="k">end</span>

<span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:member</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">name</span> <span class="s1">'example member'</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">association</span> <span class="ss">:site</span>
<span class="k">end</span>

<span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:post</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">title</span> <span class="s1">'example post'</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">association</span> <span class="ss">:author</span><span class="p">,</span> <span class="ss">:factory</span> <span class="o">=&gt;</span> <span class="ss">:member</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">association</span> <span class="ss">:site</span>
<span class="k">end</span></code></pre></figure>

<p>The problem I run into is this: If I do <code class="language-plaintext highlighter-rouge">Factory(:post)</code>, then
the post[id:1] has an author[id:1] linked to site[id:1]. But
post[id:1] is linked to site[id:2]!</p>

<h2 id="solution-use-an-after_build-callback">Solution: Use an after_build callback</h2>

<p>The best solution I’ve come up with is to define these associations
that depend on each other in an <code class="language-plaintext highlighter-rouge">after_build</code> block. The simple way
to do it is just to try to hook up common associations.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:site</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
<span class="k">end</span>

<span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:member</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">name</span> <span class="s1">'example member'</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">after_build</span> <span class="k">do</span> <span class="o">|</span><span class="n">member</span><span class="o">|</span>
    <span class="n">member</span><span class="p">.</span><span class="nf">site</span> <span class="o">||=</span> <span class="no">Factory</span><span class="p">.</span><span class="nf">build</span><span class="p">(</span><span class="ss">:site</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:post</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">title</span> <span class="s1">'example post'</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">after_build</span> <span class="k">do</span> <span class="o">|</span><span class="n">post</span><span class="o">|</span>
    <span class="n">post</span><span class="p">.</span><span class="nf">site</span> <span class="o">||=</span> <span class="n">post</span><span class="p">.</span><span class="nf">author</span><span class="p">.</span><span class="nf">try</span><span class="p">(</span><span class="n">site</span><span class="p">)</span> <span class="o">||</span> <span class="no">Factory</span><span class="p">.</span><span class="nf">build</span><span class="p">(</span><span class="ss">:site</span><span class="p">)</span>
    <span class="n">post</span><span class="p">.</span><span class="nf">author</span> <span class="o">||=</span> <span class="no">Factory</span><span class="p">.</span><span class="nf">build</span><span class="p">(</span><span class="ss">:member</span><span class="p">,</span> <span class="ss">:site</span> <span class="o">=&gt;</span> <span class="n">post</span><span class="p">.</span><span class="nf">site</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<h2 id="solution-improved-after_build-and-a-test-global-context">Solution improved: after_build and a test-global context.</h2>

<p>Another method that I like is to create a context class. Because
most of my tests deal with data that is well-formed (e.g. it is
unexpected that the application would contain a post that links
to a member from a different site), the context class can store
a global-to-test site instance.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">TestContext</span>
  <span class="k">class</span> <span class="o">&lt;&lt;</span> <span class="nb">self</span>
    <span class="k">def</span> <span class="nf">reset!</span>
      <span class="vi">@instance</span> <span class="o">=</span> <span class="kp">nil</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="nf">instance</span>
      <span class="vi">@instance</span> <span class="o">||=</span> <span class="n">new</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="nf">method_missing</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
      <span class="n">instance</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>

  <span class="nb">attr_accessor</span> <span class="ss">:site</span>

  <span class="k">def</span> <span class="nf">site!</span>
    <span class="nb">self</span><span class="p">.</span><span class="nf">site</span> <span class="o">=</span> <span class="no">Factory</span> <span class="ss">:site</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:site</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
<span class="k">end</span>

<span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:member</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">name</span> <span class="s1">'example member'</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">after_build</span> <span class="k">do</span> <span class="o">|</span><span class="n">member</span><span class="o">|</span>
    <span class="n">member</span><span class="p">.</span><span class="nf">site</span> <span class="o">||=</span> <span class="no">TestContext</span><span class="p">.</span><span class="nf">site!</span> <span class="o">||</span> <span class="no">Factory</span><span class="p">.</span><span class="nf">build</span><span class="p">(</span><span class="ss">:site</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:post</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">title</span> <span class="s1">'example post'</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">after_build</span> <span class="k">do</span> <span class="o">|</span><span class="n">post</span><span class="o">|</span>
    <span class="n">post</span><span class="p">.</span><span class="nf">author</span> <span class="o">||=</span> <span class="no">Factory</span><span class="p">.</span><span class="nf">build</span><span class="p">(</span><span class="ss">:member</span><span class="p">)</span>
    <span class="n">post</span><span class="p">.</span><span class="nf">site</span> <span class="o">||=</span> <span class="n">post</span><span class="p">.</span><span class="nf">author</span><span class="p">.</span><span class="nf">site</span> <span class="o">||</span> <span class="no">TestContext</span><span class="p">.</span><span class="nf">site!</span> <span class="o">||</span> <span class="no">Factory</span><span class="p">.</span><span class="nf">build</span><span class="p">(</span><span class="ss">:site</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="k">class</span> <span class="nc">MyTestCase</span> <span class="o">&lt;&lt;</span> <span class="no">Test</span><span class="o">::</span><span class="no">Unit</span><span class="o">::</span><span class="no">TestCase</span>
  <span class="k">def</span> <span class="nf">setup</span>
    <span class="no">TestContext</span><span class="p">.</span><span class="nf">site!</span>
  <span class="k">end</span>
  <span class="k">def</span> <span class="nf">teardown</span>
    <span class="no">TestContext</span><span class="p">.</span><span class="nf">reset!</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">test_stuff</span>
    <span class="n">post</span> <span class="o">=</span> <span class="no">Factory</span> <span class="ss">:post</span>
    <span class="c1"># ...</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p>This works pretty well for me, but it seems like there should be a better way.
I think what I want is the concept of a fixed <code class="language-plaintext highlighter-rouge">Site</code> instance for the duration
of a given test, so, a replacement for the TestContext.</p>

<p><em>The exact code in this article has not been tried, so it probably doesn’t run.
Hopefully the intent is clear enough.</em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[with_scope]]></title>
    <link href="http://pickardayune.com/blog/2012/01/04/with-scope"/>
    <updated>2012-01-04T13:14:00+00:00</updated>
    <id>http://pickardayune.com/blog/2012/01/04/with-scope</id>
    <content type="html"><![CDATA[<p>I was writing a custom ‘find_or_create’ method on a model today, that I
was planning to use from an association collection. I wanted it to pick
up the association’s scope (the foreign key value). It turns out, it
happens automatically.</p>

<p>Here’s an example:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Room</span>
  <span class="n">has_many</span> <span class="ss">:members</span>
<span class="k">end</span></code></pre></figure>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Member</span>
  <span class="n">belongs_to</span> <span class="ss">:room</span>
  <span class="k">class</span> <span class="o">&lt;&lt;</span> <span class="nb">self</span>
    <span class="k">def</span> <span class="nf">find_or_create_for_invitation</span><span class="p">(</span><span class="n">id_or_email</span><span class="p">)</span>
      <span class="n">where</span><span class="p">(</span><span class="ss">:id</span> <span class="o">=&gt;</span> <span class="nb">id</span><span class="p">).</span><span class="nf">first</span> <span class="o">||</span> <span class="n">where</span><span class="p">(</span><span class="ss">:email</span> <span class="o">=&gt;</span> <span class="n">email</span><span class="p">).</span><span class="nf">first</span>
      <span class="c1"># ... or create</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p>What I really want, is for my member find-or-create to be scoped to the room
it’s on when I do <code class="language-plaintext highlighter-rouge">room.members.find_or_create_for_invitation(params[:invitee])</code>.</p>

<p>I figured it was possible, so I set a debugger breakpoint in <code class="language-plaintext highlighter-rouge">find_or_create_for_invitation</code>
and checked out the available information. What I found is that the static method
is called inside of a <code class="language-plaintext highlighter-rouge">with_scope</code> block, so <code class="language-plaintext highlighter-rouge">Member.scoped_methods</code> has some
useful information. In this case, it’s an array with one element, the scoped
association relation (i.e. the thing returned by <code class="language-plaintext highlighter-rouge">room.members</code>). It’s possible for
the array to contain hashes, too, and several elements, if there are several
nested scopes. So, any find-like or create-like calls that you make inside the
class method will automatically get the right scope.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Configuring your Ruby/Rails application with static_config]]></title>
    <link href="http://pickardayune.com/blog/2011/11/22/static-config"/>
    <updated>2011-11-22T00:00:00+00:00</updated>
    <id>http://pickardayune.com/blog/2011/11/22/static-config</id>
    <content type="html"><![CDATA[<p>I’ve written a ruby gem called <a href="http://github.com/spraints/static_config">static_config</a> that handles a common
(for me) configuration task. The pattern is: I’m writing a rails
application, and I have some extra bits of configuration that doesn’t fit
into the normal set of configuration files. And, usually I want to vary
the behavior by environment.</p>

<p>For example, one application does not yet allow open signups in production.
I want to be able to turn that on &amp; off in development so that
(a) I can test it and
(b) I can not be bothered by it at other times. Also, we expect to allow
open signups in production eventually, just not yet, so I would like to
be able to flip the switch without necessarily needing to deploy new code.</p>

<p>In another application, we’ve been trying out a couple different
background task runners, and it was uncertain enough as to which we’d use
that I abstracted the particulars out so that I could focus on getting
the jobs running. So now, I can set the queue type in the config file.
And, for easing my development setup, I have dev set to ‘immediate’. And
test is set to ‘none’. And, of course, production is set to use the real
queue, ‘resque’ (for now). Very flexible.</p>

<p>To do this, I wrote <a href="http://github.com/spraints/static_config">static_config</a>.</p>

<h2 id="installation">Installation</h2>

<p>To install, you’ll need the static_config gem. You can
<code class="language-plaintext highlighter-rouge">gem install static_config</code> or use Bundler:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem 'static_config'
</code></pre></div></div>

<h2 id="an-ad-hoc-config-file">An ad-hoc config file</h2>

<p>The simplest case is just a config file that you can put anything into.
This would be the case where you just want to collect some configuration
into one place.</p>

<p>First, create a file called config.yml, maybe with something like this:</p>

<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="na">thing</span><span class="pi">:</span> <span class="s">abc</span>
<span class="na">nested</span><span class="pi">:</span>
  <span class="na">thing</span><span class="pi">:</span> <span class="s">def</span></code></pre></figure>

<p>In your app, load up the config and use it.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="nb">require</span> <span class="s1">'static_config'</span>
<span class="no">MyConfig</span> <span class="o">=</span> <span class="no">StaticConfig</span><span class="p">.</span><span class="nf">build</span> <span class="k">do</span>
  <span class="n">file</span> <span class="no">File</span><span class="p">.</span><span class="nf">expand_path</span><span class="p">(</span><span class="s1">'config.yml'</span><span class="p">,</span> <span class="no">File</span><span class="p">.</span><span class="nf">dirname</span><span class="p">(</span><span class="kp">__FILE__</span><span class="p">))</span>
<span class="k">end</span>
<span class="nb">puts</span> <span class="no">MyConfig</span><span class="p">.</span><span class="nf">thing</span>        <span class="c1"># =&gt; abc</span>
<span class="nb">puts</span> <span class="no">MyConfig</span><span class="p">.</span><span class="nf">nested</span><span class="p">.</span><span class="nf">thing</span> <span class="c1"># =&gt; def</span></code></pre></figure>

<h2 id="an-ad-hoc-per-environment-config-file">An ad-hoc, per-environment config file</h2>

<p>So now, you want to change nested.thing to ‘ghi’ in production. It’s
not much different.</p>

<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="na">development</span><span class="pi">:</span>
  <span class="na">thing</span><span class="pi">:</span> <span class="s">abc</span>
  <span class="na">nested</span><span class="pi">:</span>
    <span class="na">thing</span><span class="pi">:</span> <span class="s">def</span>
<span class="na">production</span><span class="pi">:</span>
  <span class="na">thing</span><span class="pi">:</span> <span class="s">abc</span>
  <span class="na">nested</span><span class="pi">:</span>
    <span class="na">thing</span><span class="pi">:</span> <span class="s">ghi</span></code></pre></figure>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1">#...</span>
<span class="no">MyConfig</span> <span class="o">=</span> <span class="no">StaticConfig</span><span class="p">.</span><span class="nf">build</span> <span class="k">do</span>
  <span class="n">file</span> <span class="no">File</span><span class="p">.</span><span class="nf">expand_path</span><span class="p">(</span><span class="s1">'config.yml'</span><span class="p">,</span> <span class="no">File</span><span class="p">.</span><span class="nf">dirname</span><span class="p">(</span><span class="kp">__FILE__</span><span class="p">)),</span>
    <span class="ss">:section</span> <span class="o">=&gt;</span> <span class="no">ENV</span><span class="p">[</span><span class="s1">'MY_APP_ENV'</span><span class="p">]</span> <span class="o">||</span> <span class="s1">'development'</span>
<span class="k">end</span>
<span class="c1">#...</span></code></pre></figure>

<h2 id="an-ad-hoc-per-environment-config-file-that-you-can-override-with-environment-variables">An ad-hoc, per-environment config file that you can override with environment variables</h2>

<p>Now, let’s override some of the configuration with environment variables.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="nb">require</span> <span class="s1">'static_config'</span>
<span class="no">MyConfig</span> <span class="o">=</span> <span class="no">StaticConfig</span><span class="p">.</span><span class="nf">build</span> <span class="k">do</span>
  <span class="n">file</span> <span class="no">File</span><span class="p">.</span><span class="nf">expand_path</span><span class="p">(</span><span class="s1">'config.yml'</span><span class="p">,</span> <span class="no">File</span><span class="p">.</span><span class="nf">dirname</span><span class="p">(</span><span class="kp">__FILE__</span><span class="p">)),</span>
    <span class="ss">:section</span> <span class="o">=&gt;</span> <span class="no">ENV</span><span class="p">[</span><span class="s1">'MY_APP_ENV'</span><span class="p">]</span> <span class="o">||</span> <span class="s1">'development'</span>
  <span class="n">env</span> <span class="s1">'MY_APP'</span>
<span class="k">end</span>
<span class="nb">puts</span> <span class="no">MyConfig</span><span class="p">.</span><span class="nf">nested</span><span class="p">.</span><span class="nf">thing</span></code></pre></figure>

<p>Now, you get this output:</p>

<figure class="highlight"><pre><code class="language-sh" data-lang="sh"><span class="nv">$ </span>ruby app.rb
def
<span class="nv">$ MY_APP_ENV</span><span class="o">=</span>production ruby app.rb
ghi
<span class="nv">$ MY_APP_NESTED_THING</span><span class="o">=</span>blah ruby app.rb
blah</code></pre></figure>

<h2 id="all-that-and-reloading">All that, and reloading!</h2>

<p>Finally, let’s say you’re doing this in a rails app.
You’re going to want to have the configuration loaded
automatically, and, in development, reloaded, too.</p>

<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="na">development</span><span class="pi">:</span>
  <span class="na">thing</span><span class="pi">:</span> <span class="s">abc</span>
  <span class="na">nested</span><span class="pi">:</span>
    <span class="na">thing</span><span class="pi">:</span> <span class="s">def</span>
<span class="na">test</span><span class="pi">:</span>
  <span class="na">thing</span><span class="pi">:</span> <span class="s">test</span>
  <span class="na">nested</span><span class="pi">:</span>
    <span class="na">thing</span><span class="pi">:</span> <span class="s">test</span>
<span class="na">production</span><span class="pi">:</span>
  <span class="na">thing</span><span class="pi">:</span> <span class="s">abc</span>
  <span class="na">nested</span><span class="pi">:</span>
    <span class="na">thing</span><span class="pi">:</span> <span class="s">ghi</span></code></pre></figure>

<p>In config/initializers/config.rb:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="no">MyConfig</span> <span class="o">=</span> <span class="no">StaticConfig</span><span class="p">.</span><span class="nf">build</span> <span class="k">do</span>
  <span class="n">file</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s1">'config/my_app.yml'</span><span class="p">),</span> <span class="ss">:section</span> <span class="o">=&gt;</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">env</span>
  <span class="n">env</span> <span class="s1">'MY_APP'</span>
<span class="k">end</span>

<span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">to_prepare</span> <span class="k">do</span>
  <span class="no">MyConfig</span><span class="p">.</span><span class="nf">reload!</span>
<span class="k">end</span></code></pre></figure>

]]></content>
  </entry>
  
</feed>
