Elijah Miller2023-04-18T16:06:54+00:00http://thejqr.com/Elijah Millerelijah.miller@gmail.comSelfless Ruby2013-10-14T00:00:00+00:00http://thejqr.com/2013/10/14/selfless-ruby<p>There are only a few occasions when you need to use self prefix in Ruby. Understanding these only takes a few minutes and can help you avoid some pretty common bugs and wasteful debugging attempts.</p>
<h3 id="avoiding-local-variable-assignment">Avoiding local variable assignment</h3>
<p>Calling a writer in the current scope, as in:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span>
<span class="k">def</span> <span class="nf">verify</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">verified</span> <span class="o">=</span> <span class="kp">true</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">verified</span><span class="o">=</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="vi">@verified</span> <span class="o">=</span> <span class="n">value</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>If you didn’t prefix self to that assignment, you would be making a new local variable and setting it to true. This variable has a lifetime of 1 statement, probably not what you were looking for and an easy bug to miss.</p>
<h3 id="side-stepping-reserved-words">Side-stepping reserved words</h3>
<p>Occasionally you need to call a method in the current scope that has the same name as a Ruby keyword. An instance wanting to introspect its its own class is a very common use.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Song</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
<span class="k">def</span> <span class="nf">find_dupliactes</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">class</span><span class="p">.</span><span class="nf">find_by_name</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>In this case you are explicitly side-stepping the global behavior of the keyword. If you omit self, Ruby thinks you’re about to define a new class, and is going to give you a syntax error.</p>
<h3 id="defining-class-methods">Defining class methods</h3>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Store</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">locate_by_zip_code</span><span class="p">(</span><span class="n">zip_code</span><span class="p">)</span>
<span class="c1"># some fancy searching code</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>The use of self in this example tells Ruby that we’re making methods on the <code class="language-plaintext highlighter-rouge">Store</code> class and not its instances.</p>
<h3 id="thats-it">That’s it!</h3>
<p>Three simple cases where you need to use self. All other uses are just being overly explicit.</p>
<h3 id="gotcha-tricky-sub-objects">Gotcha: Tricky sub-objects</h3>
<p>Sub-objects only need to use the self prefix when you want to assign the whole object at a time. For example when initializing or setting an entire Hash, Array, or some other object.</p>
<p>If you’re actually just manipulating the other object, you don’t need to call self, because you’re really calling two methods. In this case one is the reader, the other is the <code class="language-plaintext highlighter-rouge">[]</code> method on a Hash.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Server</span>
<span class="nb">attr_accessor</span> <span class="ss">:options</span>
<span class="k">def</span> <span class="nf">initialize</span>
<span class="c1"># required, we want to call Server#options=</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">options</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">toggle_warnings</span>
<span class="c1"># not required, options[:warnings] is actually two method calls:</span>
<span class="c1"># * Server#options</span>
<span class="c1"># * Hash#[]</span>
<span class="n">options</span><span class="p">[</span><span class="ss">:warnings</span><span class="p">]</span> <span class="o">=</span> <span class="o">!</span><span class="n">options</span><span class="p">[</span><span class="ss">:warnings</span><span class="p">]</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
Automatically Generated Maps with Microformats2013-09-09T00:00:00+00:00http://thejqr.com/2013/09/09/automatically-generated-maps-with-microformats<p>
Got a few addresses and want to show them on a map without writing any javascript?
It turns out, there's an incredibly easy way: mark up your addresses as
<a href="http://microformats.org/wiki/hcard">hCards</a> and use the
<a href="https://github.com/collectiveidea/simple-maps">simple-maps</a> javascript library.
</p>
<h3>Microformats to the Rescue!</h3>
<p>
Microformats are a simple way to attach meaning to standard HTML tags by
using classes. Here is an example I made with the
<a href="http://microformats.org/code/hcard/creator">hCard Creator</a>.
</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt"><div</span> <span class="na">id=</span><span class="s">"hcard-starbucks"</span> <span class="na">class=</span><span class="s">"vcard"</span><span class="nt">></span>
<span class="nt"><a</span> <span class="na">class=</span><span class="s">"url fn"</span> <span class="na">href=</span><span class="s">"http://starbucks.com"</span><span class="nt">></span>Starbucks<span class="nt"></a></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"adr"</span><span class="nt">></span>
<span class="nt"><span</span> <span class="na">class=</span><span class="s">"street-address"</span><span class="nt">></span>854 Broad Ripple Ave<span class="nt"></span><br/></span>
<span class="nt"><span</span> <span class="na">class=</span><span class="s">"locality"</span><span class="nt">></span>Indianapolis<span class="nt"></span></span>,
<span class="nt"><span</span> <span class="na">class=</span><span class="s">"region"</span><span class="nt">></span>IN<span class="nt"></span></span>,
<span class="nt"><span</span> <span class="na">class=</span><span class="s">"postal-code"</span><span class="nt">></span>46220<span class="nt"></span></span>
<span class="nt"><span</span> <span class="na">class=</span><span class="s">"country-name"</span><span class="nt">></span>USA<span class="nt"></span></span>
<span class="nt"></div></span>
<span class="nt"></div></span>
</code></pre></div></div>
<p>
Rendered as HTML using default styling, this looks like:
</p>
<p>
<div id="hcard-starbucks" class="vcard">
<a class="url fn" href="https://starbucks.com">Starbucks</a>
<div class="adr">
<span class="street-address">854 Broad Ripple Ave</span><br />
<span class="locality">Indianapolis</span>,
<span class="region">IN</span>,
<span class="postal-code">46220</span>
<span class="country-name">USA</span>
</div>
</div>
</p>
<p>
Pretty simple, it usually means adding some classes to data that's
already on the page. We can style this however we like, including
completely hiding elements with <code>display: none</code> for things
that may be obvious (country name?).
</p>
<p>
To display the map we just use an element with id="map"
</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt"><div</span> <span class="na">id=</span><span class="s">"map"</span> <span class="na">style=</span><span class="s">"width: 100%; height: 400px"</span><span class="nt">></div></span>
</code></pre></div></div>
<div id="map" style="width: 100%; height: 400px">Map would be here if you had javascript enabled.</div>
<p>
There are two pins because it also picks up my hCard from the site layout.
</p>
<h3>Automatic Geocoding</h3>
<p>
You may have noticed I didn't specify longitude or latitude anywhere
in the hCard. simple-maps detects and computes geocodes when they're not given.
</p>
Easy Heroku Deploys with Heroku San2010-08-27T00:00:00+00:00http://thejqr.com/2010/08/27/easy-heroku-deploys-with-heroku-san<p>We deploy a great deal of our apps to <a href="https://heroku.com">Heroku</a>, but maintaining multiple environments (staging, production, demo) was traditionally <a href="/2009/04/25/deploying-multiple-environments-on-heroku.html">very painful</a>.</p>
<p><a href="https://github.com/fastestforward/heroku_san">heroku_san</a> is a simple set of rake tasks to make standard Rails deployment easy. Multiple apps, environments, branches and users are handled with the minimum of effort.</p>
<h3 id="initial-setup">Initial Setup</h3>
<p>I won’t bore you with the details of <a href="https://github.com/fastestforward/heroku_san/blob/master/README.rdoc">installing the gem and including the rake tasks</a>, but you need to know that heroku_san works by using a YAML file with shorthand versions of your Heroku application names. It looks like this:</p>
<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">apps</span><span class="pi">:</span>
<span class="c1"># shorthand: heroku app</span>
<span class="na">production</span><span class="pi">:</span> <span class="s">awesomeapp</span>
<span class="na">staging</span><span class="pi">:</span> <span class="s">awesomeapp-staging</span>
<span class="na">demo</span><span class="pi">:</span> <span class="s">awesomeapp-demo</span>
</code></pre></div></div>
<h3 id="first-time">First Time</h3>
<p>If this app has never been deployed to Heroku, you will need to create the remote applications. heroku_san can do this for you, using the data in config/heroku.yml.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>rake all heroku:create
</code></pre></div></div>
<p>Most multi-app deployments change the environment to something different for each app, allowing you to override things like S3 buckets, email policies, etc. heroku_san is happy to handle this too, it assumes you want the RACK_ENV set to the shorthand name of the application.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># set RACK_ENV on each application to the shorthand:</span>
<span class="c"># awesomeapp-staging => staging</span>
<span class="c"># awesomeapp-demo => demo</span>
rake all heroku:rack_env
</code></pre></div></div>
<p>The old Heroku stack (aspen) requires you to use a Gem manifest (.gems) to list the gems your application depends on. heroku_san can auto-populate this using config.gem requirements for Rails 2 applications.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>rake heroku:gems
</code></pre></div></div>
<h3 id="everyday-use">Everyday Use</h3>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>rake staging deploy <span class="c"># deploy staging and migrate</span>
rake production console <span class="c"># open a console for production</span>
rake demo staging heroku:share <span class="c"># add a new developer to demo and staging</span>
rake all heroku:unshare <span class="c"># remove a developer from all apps</span>
</code></pre></div></div>
<h3 id="branches">Branches</h3>
<p>Deploying always uses the current branch, so be careful! Occasionally you might need to force a deploy, especially if you’re deploying multiple feature branches to the same app.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>rake staging deploy <span class="c"># deploy current branch to staging</span>
rake staging force_deploy <span class="c"># force deploy current branch to staging</span>
</code></pre></div></div>
<h3 id="only-one-app">Only One App?</h3>
<p>If you’re only using one app, you can skip the server names and just issue the commands directly.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>rake deploy <span class="c"># deploy the only app you have configured</span>
rake console <span class="c"># open a console on your single app</span>
</code></pre></div></div>
<h3 id="curious">Curious?</h3>
<p>heroku_san works entirely by using the git and heroku binaries. So if you’re ever curious about how a command works or need to debug something you can just watch the screen as you run a command to see exactly what it’s up to.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>rake staging deploy
<span class="c"># git push git@heroku.com:awesomeapp-staging.git master:master && \</span>
<span class="c"># heroku rake --app awesomeapp-staging db:migrate && \</span>
<span class="c"># heroku restart --app awesomeapp-staging</span>
</code></pre></div></div>
<h3 id="even-more">Even More!</h3>
<p>A full list of commands heroku_san provides is available in the <a href="https://github.com/fastestforward/heroku_san/blob/master/README.rdoc">README</a>.</p>
<h3 id="special-thanks">Special Thanks</h3>
<p>Thanks to <a href="https://github.com/glennr">Glenn Roberts</a>, who was kind enough to convert heroku_san from a Rails plugin into a gem, making updates a breeze.</p>
iPhone Toggle Switches2009-08-05T00:00:00+00:00http://thejqr.com/2009/08/05/iphone-toggle-switches<p>
Way back in June, <a href="https://awardwinningfjords.com/">Thomas Reynolds</a>
released <a
href="http://awardwinningfjords.com/2009/06/16/iphone-style-checkboxes.html">iPhone-style-checkboxes
for jQuery</a>, a progressive enhancement for checkboxes which makes them into
the beautiful iPhone toggle switches. I really like these switches on the
iPhone so I went about finishing up his version for the Prototype framework.
Of course, I couldn't help but add some new features along the way!
</p>
<p class="rss_only">
<strong>
You definitely need to <a href="https://thejqr.com/2009/08/05/iphone-toggle-switches.html">read
this article on my site</a> to see all the cool JavaScript effects I'm
talking about!
</strong>
</p>
<h3>Variable sizes</h3>
<p>
The initial version supported changing the ON/OFF label text, but if you made
the text longer than a few characters, it would be hidden under the handle. I
set about making the handle and label sizes automatic based on the actual
label text, giving a really nice
<a href="http://shop.o2.co.uk/new-iphone/index.html">iphone 4</a> look to the
handle and label.
</p>
<p>
<div><label class="left" for="variable_size_male_female">Sex</label> <input type="checkbox" id="variable_size_male_female"/></div>
<div><label class="left" for="variable_size_a_b">Path</label> <input type="checkbox" id="variable_size_a_b"/></div>
</p>
<p>
As a bonus, you can also specify that no automatic resizing should be done and
do the control and handle sizing with CSS to make a group of controls uniform.
</p>
<div style="width: 400px;">
<div><label class="left" for="static_size_a">Be you robot?</label> <input type="checkbox" id="static_size_a"/></div>
<div><label class="left" for="static_size_b">Comments</label> <input type="checkbox" id="static_size_b"/></div>
<div><label class="left" for="static_size_c">Option C</label> <input type="checkbox" id="static_size_c"/></div>
</div>
<h3>Draggable</h3>
<p>
They certainly looked like the iPhone switches, but they didn't feel like
them. You could only click them to toggle, we needed to add support for
dragging the control.
</p>
<div><label class="left" for="variable_size_male_female">Do it</label> <input type="checkbox" id="draggable" checked="checked"/></div>
<h3>Sliding labels</h3>
<p>
A quick check through the network graph revealed <a
href="https://github.com/mlangenberg">Matthijs Langenberg</a> had devised a
clever way to slide the labels along with the handle. This was the final
piece, now the our JavaScript was nearly indistinguishable from the native
iPhone one.
</p>
<p>
<div><label class="left" for="sliding_labels">Go man go!</label> <input type="checkbox" id="sliding_labels" /></div>
</p>
<h3>iPhone compatibility</h3>
<p>
Last but not least, our checkboxes didn't support dragging on the iPhone!
Since the iPhone sends out touch events instead of mouse ones, all of our
cool dragging code would need to be updated. As of today, both
versions of this plugin now fully support the iPhone.
</p>
<h3>Thanks</h3>
<p>
A huge thanks to Thomas Reynolds for his development on this awesome plugin
and giving me the ability to add these improvements.
</p>
<h3>Download</h3>
<p>
The <a href="https://github.com/tdreyno/iphone-style-checkboxes">source code</a> is available on GitHub
or you can download a <a href="https://github.com/tdreyno/iphone-style-checkboxes/zipball/master">zip</a> /
<a href="https://github.com/tdreyno/iphone-style-checkboxes/tarball/master">tar.gz</a>
archive.
</p>
Deploying Multiple Environments on Heroku2009-04-25T00:00:00+00:00http://thejqr.com/2009/04/25/deploying-multiple-environments-on-heroku<p class="update">UPDATE: This post is outdated, check out <a href="/2010/08/27/easy-heroku-deploys-with-heroku-san.html">Easy Deploys with Heroku San</a>.</p>
<p>So you followed yesterday's guide on <a href="/2009/04/24/deploy-your-rails-application-in-2-minutes-with-heroku.html">getting your application deployed to
Heroku</a>, and now you've fallen in love with it. Now you need to setup both a
production and staging environment that you can easily deploy your application
to.</p>
<p>So far Heroku only runs code in one branch, so we'll work around this by
creating two remote repositories that we can push to.</p>
<p>For example simplicity, we'll be pushing all code out of the same git
branch. You'll probably be pushing staging and production servers from different branches, adjust accordingly.</p>
<h3>Create your servers and fix your remotes</h3>
<p>Application names have to be unique on Heroku, so make sure to replace myapp with your application’s name. You can do that automatically by <a href="#" id="replace_application_name">clicking here</a>.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>heroku create myapp-staging <span class="nt">--remote</span> staging
heroku create myapp-production <span class="nt">--remote</span> production
</code></pre></div></div>
<p>Since we'll be pushing to two applications we are using the --remote argument to make two sensibly named remotes.</p>
<h3>Environment specific variables</h3>
<p>Heroku has a nice interface for setting up application specific settings, but
I will assume your application configures itself according to the
RAILS_ENV variable. Check out <a href="https://docs.heroku.com/config-vars">Heroku's docs</a> if you need more
control.</p>
<p>If you run your staging server in the production environment, you can skip this step.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>heroku config:add <span class="nv">RACK_ENV</span><span class="o">=</span>staging <span class="nt">--app</span> myapp-staging
heroku config:add <span class="nv">RACK_ENV</span><span class="o">=</span>production <span class="nt">--app</span> myapp-production
</code></pre></div></div>
<h3>Deploy and migrate</h3>
<p>You'll be doing this next command pretty often. We push the current branch to
the staging server's master branch. Since this is the first deploy we'll need to do the same thing for production and run all the migrations.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git push staging master
git push production master
heroku rake db:migrate <span class="nt">--app</span> myapp-staging
heroku rake db:migrate <span class="nt">--app</span> myapp-production
heroku open <span class="nt">--app</span> myapp-staging
heroku open <span class="nt">--app</span> myapp-production
</code></pre></div></div>
<h3>Done</h3>
<p>Celebrate! You now have two servers running on Heroku with different databases and accessible through domains. Seriously, how long did that take?</p>
<h3>Caveats</h3>
<p>The heroku command seems to detect the application name by looking through
git's remotes for remotes that are located at heroku.com. This means it will
get confused by the multiple entries we created. You will need to work around
this by passing --app myapp-staging after the normal heroku command.</p>
<h3>Troubleshooting</h3>
<p>Make sure you followed my original guide on <a href="/2009/04/24/deploy-your-rails-application-in-2-minutes-with-heroku.html">getting
your application deployed to Heroku</a>.</p>
<script type="text/javascript">
document.observe('dom:loaded', function() {
$('replace_application_name').observe('click', replaceApplicationName)
});
var old_name = 'myapp';
function replaceApplicationName(event) {
event.stop();
var new_name = prompt('Enter your application name:');
$$('pre').each(function(element) {
element.update(element.innerHTML.replace(RegExp(old_name, 'g'), new_name));
});
old_name = new_name;
}
</script>
Deploy Your Rails Application in 2 Minutes with Heroku2009-04-24T00:00:00+00:00http://thejqr.com/2009/04/24/deploy-your-rails-application-in-2-minutes-with-heroku<p><a href="https://heroku.com/">Heroku</a>, Instant Ruby Platform. We've been using Heroku's free service for hosting staging servers for a few weeks now. It takes just a moment to setup and it couldn't be any easier to use.</p>
<p>Today Heroku announced a <a href="https://heroku.com/pricing">pricing model</a> and we should be using them for more than staging servers in the near future.</p>
<h3>Start the clock</h3>
<p>First timer? You'll need to do some minor setup. The middle command will ask you for your Heroku login/password and upload your SSH pubkey.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>gem <span class="nb">install </span>heroku
heroku keys:add
heroku create
</code></pre></div></div>
<p>Heroku installs gem dependencies for your app when you do a git push, so it needs to have a .gems file in an easy to parse format.</p>
<p>Run these commands to install a rake task for automatically generating a .gems file from your Rails gem dependencies. You'll need to rerun the rake task whenever you change your dependencies.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl https://gist.github.com/101101.txt <span class="o">></span> lib/tasks/heroku.rake
rake heroku:gems
git add lib/tasks/heroku.rake .gems
git commit lib/tasks/heroku.rake .gems <span class="nt">-m</span> <span class="s2">"Adding gem manifest for Heroku."</span>
</code></pre></div></div>
<p>Here we go, push your app, migrate the database and open it in a web browser! </p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git push heroku master
heroku rake db:migrate
heroku open
</code></pre></div></div>
<h3>Done</h3>
<p>Your application is up and running on Heroku's servers, 100% ready to use. Check out the next guide on setting up <a href="/2009/04/25/deploying-multiple-environments-on-heroku.html">multiple environments with Heroku</a>.</p>
<h3>Troubleshooting</h3>
<p>If the application had any trouble starting try the commands below to get a better view.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>heroku logs <span class="c"># view the application logs</span>
heroku open <span class="c"># some error messages show on the web</span>
</code></pre></div></div>
Use Instant Debugger on Rare Exceptions2009-03-02T00:00:00+00:00http://thejqr.com/2009/03/02/use-instant-debugger-on-rare-exceptions<p>Most of the time a backtrace can help you zero in on a bug in your code quickly, but sometimes the issue is not your code but the data your code is processing. In these cases, a backtrace is just a clue to your problems, you really need to see what data your code was processing to get a feel for the issue.</p>
<p>You could throw in some statements to print out certain variables to “see” what your code “sees” at that point in time, but there is a far easier way.</p>
<h3 id="your-friend-debugger">Your friend: debugger</h3>
<p>The excellent ruby-debug gem lets you open up an instance of irb wherever you put a call to debugger. If you haven’t already, check out the excellent <a href="https://pivotallabs.com/users/chad/blog/articles/366-ruby-debug-in-30-seconds-we-don-t-need-no-stinkin-gui-">30 second guide to ruby-debug</a>. Just type in “irb” when the debugger triggers to get a live irb session with the current state.</p>
<p>Normally this is more than enough to fix the problematic data/code. Today though I was iterating through a rather large set of data for importing from CSV. The problem data was something like 5 minutes into the import. I needed to open the debugger at the instant of the problem data and not on the thousands of rows of good data that preceded it.</p>
<h3 id="start-on-a-dime">Start on a dime</h3>
<p>A light when off in my head after a few minutes of stumbling around in console. Why not just wrap the offending bit of code in a rescue block and only open the debugger at that instant? I give you Instant Debug.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">rows</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">row</span><span class="o">|</span>
<span class="k">begin</span>
<span class="no">Item</span><span class="p">.</span><span class="nf">create!</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
<span class="k">rescue</span> <span class="o">=></span> <span class="n">err</span>
<span class="nb">require</span> <span class="s1">'ruby-debug'</span>
<span class="n">debugger</span>
<span class="mi">1</span> <span class="c1"># no-op so the debugger can land in this context</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Now if this code fails for any reason, we can see the exact state of the application that caused this problem. We are able to reproduce the issue easily by calling Item.create!(row) and we can even modify row to see if we can fix bad data.</p>
<p>A helpful hint: Because you want to be able to trigger the problem easily, you should wrap the rescue block as tightly around the problematic code as possible.</p>
ActiveRecord::Base#find_each Now in Rails2009-02-23T00:00:00+00:00http://thejqr.com/2009/02/23/active-record-each-now-in-edge-rails<p><em>Updated to reflect Rails 2.3 release implementation</em></p>
<p>When you absolutely need to traverse a large number of objects in a table and have the ActiveRecord instance available, Rails now has a Model.find_each method that makes this safe and easy.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="no">User</span><span class="p">.</span><span class="nf">find_each</span><span class="p">(</span><span class="ss">:conditions</span> <span class="o">=></span> <span class="p">[</span><span class="s1">'last_login_at < ?'</span><span class="p">,</span> <span class="mi">30</span><span class="p">.</span><span class="nf">days</span><span class="p">.</span><span class="nf">ago</span><span class="p">])</span> <span class="k">do</span> <span class="o">|</span><span class="n">user</span><span class="o">|</span>
<span class="c1"># ...</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This feature has been available for a while through the use of a few <a href="https://github.com/guillermo/active_record_each">plugins</a> and <a href="https://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord">snippets</a> floating around, but as of Rails 2.3 ActiveRecord::Base#find_each is now in Rails core.</p>
<p>All the implementations of this feature take roughly the same route. Grab a sizable amount of records, yield them individually and repeat. The key feature is only a small subset of all rows are instantiated at any time. This prevents your process from using far more memory than is available. Most implementations even force the ordering to the primary key to easily ensure all records are retrieved without repetition and an index is used.</p>
<p>You can use any options a normal find call would take except for order or limit. Model.find_each then calls the find_in_batches. The new batch_size option defaults to 1000 objects. Higher number means less database calls, but also more memory.</p>
Ruby's Rescue Statement Can Has Value?2009-02-19T00:00:00+00:00http://thejqr.com/2009/02/19/rubys-rescue-statement-can-has-value<p>I just discovered something interesting about Ruby’s exception rescuing. Check out these two example methods that differ only by exception assignment.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">return_nil_on_error</span>
<span class="k">begin</span>
<span class="k">yield</span>
<span class="k">rescue</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">return_exception_on_error</span>
<span class="k">begin</span>
<span class="k">yield</span>
<span class="k">rescue</span> <span class="o">=></span> <span class="n">err</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="nb">puts</span> <span class="n">return_nil_on_error</span> <span class="p">{</span> <span class="k">raise</span> <span class="s2">"error!"</span> <span class="p">}.</span><span class="nf">inspect</span>
<span class="nb">puts</span> <span class="n">return_exception_on_error</span> <span class="p">{</span> <span class="k">raise</span> <span class="s2">"error!"</span> <span class="p">}.</span><span class="nf">inspect</span>
</code></pre></div></div>
<p>Running the code above and this is what you will see.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kp">nil</span>
<span class="c1">#<RuntimeError: error!></span>
</code></pre></div></div>
<p>It’s interesting to see that Ruby treats the a rescue block as a value expression if it assigns the exception to a variable. Is there a valid use for this oddity?</p>
Passing Data With Ruby Exceptions2009-02-11T00:00:00+00:00http://thejqr.com/2009/02/11/passing-data-with-ruby-exceptions<p>Have you ever needed more than the exception class, error message and back-trace when handling an exception?</p>
<p>I’ve run into this situation a few times, most recently while adding some automatic cache expiry to <a href="https://github.com/jqr/stale_object_destroyer">stale_object_destroyer</a> when it rescues a ActiveRecord::StaleObjectError.</p>
<p>First we subclass an exception and add an accessor for the data we’d like to pass and add it to the initialize method for easy construction.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">MyException</span> <span class="o"><</span> <span class="no">StandardError</span>
<span class="nb">attr_accessor</span> <span class="ss">:object</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">message</span> <span class="o">=</span> <span class="kp">nil</span><span class="p">,</span> <span class="n">object</span> <span class="o">=</span> <span class="kp">nil</span><span class="p">)</span>
<span class="k">super</span><span class="p">(</span><span class="n">message</span><span class="p">)</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">object</span> <span class="o">=</span> <span class="n">object</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>The only other important bit is how you raise this new exception.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">raise</span> <span class="no">MyException</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"Too Lazy"</span><span class="p">,</span> <span class="n">object</span><span class="p">)</span>
</code></pre></div></div>
<h3 id="a-realistic-example">A realistic example</h3>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">CacheError</span> <span class="o"><</span> <span class="no">StandardError</span>
<span class="nb">attr_accessor</span> <span class="ss">:object</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">message</span> <span class="o">=</span> <span class="kp">nil</span><span class="p">,</span> <span class="n">object</span> <span class="o">=</span> <span class="kp">nil</span><span class="p">)</span>
<span class="k">super</span><span class="p">(</span><span class="n">message</span><span class="p">)</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">object</span> <span class="o">=</span> <span class="n">object</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
<span class="nb">attr_accessor</span> <span class="ss">:name</span>
<span class="k">def</span> <span class="nf">save_with_cache_update</span>
<span class="k">raise</span> <span class="no">CacheError</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"Object is Stale"</span><span class="p">,</span> <span class="nb">self</span><span class="p">)</span> <span class="k">if</span> <span class="n">stale?</span>
<span class="n">save</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">stale?</span>
<span class="c1"># ...</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">begin</span>
<span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">find_by_name</span><span class="p">(</span><span class="s2">"Billy Mays"</span><span class="p">)</span>
<span class="c1"># ...</span>
<span class="n">user</span><span class="p">.</span><span class="nf">save_with_cache_update</span>
<span class="k">rescue</span> <span class="no">CacheError</span> <span class="o">=></span> <span class="n">err</span>
<span class="nb">puts</span> <span class="s2">"Rescued </span><span class="si">#{</span><span class="n">err</span><span class="p">.</span><span class="nf">inspect</span><span class="si">}</span><span class="s2"> on user named </span><span class="si">#{</span><span class="n">err</span><span class="p">.</span><span class="nf">object</span><span class="p">.</span><span class="nf">name</span><span class="p">.</span><span class="nf">inspect</span><span class="si">}</span><span class="s2">"</span>
<span class="n">err</span><span class="p">.</span><span class="nf">object</span><span class="p">.</span><span class="nf">expire_cache</span>
<span class="k">retry</span>
<span class="k">end</span>
</code></pre></div></div>
TextMate, Rspec and Dot Spec Party2009-02-06T00:00:00+00:00http://thejqr.com/2009/02/06/textmate-rspec-and-dot-spec-party<p>I’m going to show you how to get a great looking RSpec runner window and not go insane while trying to use it.</p>
<p><img src="/images/posts/rspec_runner.jpg" /></p>
<p>Beautiful passing green specs, easy to read failing red specs, a clickable backtrace and the failing spec block for good measure.</p>
<p>Pretty sweet right? Let’s get started.</p>
<h3>Install RSpec bundle</h3>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">mkdir</span> <span class="nt">-p</span> ~/Library/Application<span class="se">\ </span>Support/TextMate/Bundles/
<span class="nb">cd</span> ~/Library/Application<span class="se">\ </span>Support/TextMate/Bundles/
git clone git://github.com/dchelimsky/rspec-tmbundle.git RSpec.tmbundle
osascript <span class="nt">-e</span> <span class="s1">'tell app "TextMate" to reload bundles'</span>
</code></pre></div></div>
<h3>And now the fun begins</h3>
<ol>
<li>First you press Shift-Control-Option R (⇧⌃⌥R) to select the RSpec Bundle. This is so easy it only takes two hands.
<img src="/images/posts/shift_control_option_r.jpg" /></li>
<li>Now we need to press Command 3 (⌘3) to select the RSpec Bundle out of the list.
<img src="/images/posts/mode_select_r.png" /></li>
<li>Command R (⌘R) to run the spec or Shift Command R (⇧⌘R) to run an individual spec.</li>
<li>Party time!</li>
</ol>
<h3>The party's over</h3>
<p>The next time you open a spec or regular Ruby file you’ll be started in the mode you last forced. That means you’ll probably have to learn to do that tedious keyboard finger dance quite often.</p>
<script type="text/javascript" src="/javascripts/audio-player.js"></script>
<script type="text/javascript">
AudioPlayer.setup("/media/player.swf", {
width: 290
});
</script>
<p class="audio" id="obama_complicated">[Audio] "This shit's getting way too complicated for me." - Barack Obama</p>
<script type="text/javascript">
AudioPlayer.embed("obama_complicated", {soundFile: "/media/obama_complicated.mp3"});
</script>
<p>We could switch the Ruby and RSpec shortcuts to a simpler keystroke, that would alleviate most of the problem. Except we would still need to press some keystroke to force the mode upon opening a new file.</p>
<p>Running specs needs to be dead simple so people actually do it!</p>
<h3>Dot spec has invited you to a party!</h3>
<p>There’s a far easier way to solve this problem. Just rename all your spec files to .spec and you will only have to tell TextMate one time to use RSpec mode and it will remember forever!</p>
<p>The steps after switching to dot spec:</p>
<ol>
<li>Command R (⌘R) to run the spec or Shift Command R (⇧⌘R) to run an individual spec.</li>
<li>Party Time!
<img src="http://www.scienceyear.com/parents/party_time/images/party_time_top.gif" /></li>
</ol>
<h3>You've also been invited to a pre-party!</h3>
<p>Who has time to rename all those files? Definitely not you!</p>
<p>There is also a <a href="https://github.com/jqr/thor_tasks/raw/master/rspec_rename_to_dotspec.thor">fancy converter</a> for renaming all of your old specs!</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># in your project dir</span>
gem <span class="nb">install </span>thor <span class="o">&&</span>
thor <span class="nb">install</span> <span class="se">\</span>
https://github.com/jqr/thor_tasks/raw/master/rspec_rename_to_dotspec.thor <span class="o">&&</span>
thor rspec:rename_to_dotspec
</code></pre></div></div>
Global Git Ignore2009-02-03T00:00:00+00:00http://thejqr.com/2009/02/03/global-git-ignore<p>OS X has this file that creeps into any directory you browse called <a href="https://en.wikipedia.org/wiki/.DS_Store">.DS_Store</a>. All too often this file will accidentally get committed to a repository.</p>
<p>Every time I setup a new git project, I end up adding .DS_Store to the .gitignore file. This ensures no one will accidentally commit this unimportant file.</p>
<p>Git supports global ignores just like any good SCM.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git config <span class="nt">--global</span> core.excludesfile ~/.gitignore
<span class="nv">$ </span><span class="nb">printf</span> <span class="s2">".DS_Store</span><span class="se">\n</span><span class="s2">Thumbs.db</span><span class="se">\n</span><span class="s2">"</span> <span class="o">>></span> ~/.gitignore
</code></pre></div></div>
<p>For good measure I threw in Windows’ creepy file <a href="https://en.wikipedia.org/wiki/Thumbs.db">Thumbs.db</a>.</p>
<p>Sadly this won’t stop other developers from accidentally committing those files, so you still need to add those ignores to your .gitignore in every project. I’ve setup my <a href="https://github.com/jqr/dotfiles/blob/master/bash_profile.d/git.sh">git init alias</a> to do this for me.</p>
The Making of typed_serialize2009-02-01T00:00:00+00:00http://thejqr.com/2009/02/01/the-making-of-typed-serialize<p>My <a href="https://github.com/jqr/typed_serialize">typed_serialize plugin</a> came from the repetition of code just like this.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">serialize</span> <span class="ss">:options</span><span class="p">,</span> <span class="no">Hash</span>
<span class="k">def</span> <span class="nf">options</span>
<span class="n">value</span> <span class="o">=</span> <span class="k">super</span>
<span class="k">if</span> <span class="n">value</span><span class="p">.</span><span class="nf">is_a?</span><span class="p">(</span><span class="no">Hash</span><span class="p">)</span>
<span class="n">value</span>
<span class="k">else</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">options</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>It calls super to peek at what ActiveRecord would return for the serialized column. If it’s a Hash, we just return it right away. If it’s anything else we set it to a new Hash and return that.</p>
<h3>Distilling the interface</h3>
<p>After thinking about the pattern for a bit, I decided that simplest shorthand would be this.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
<span class="n">typed_serialize</span> <span class="ss">:options</span><span class="p">,</span> <span class="no">Hash</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This code says “there is a typed and serialized attribute named options, that will always be a Hash.” Notice that it is nearly the same usage as the original serialize method.</p>
<h3>Get to it</h3>
<p>First off, we define a method that is accessible at the time of class definition. Since the usage is the same as serialize, we can use the original serialize method definition as a starting point.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">ActiveRecord::Base</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">typed_serialize</span><span class="p">(</span><span class="n">attr_name</span><span class="p">,</span> <span class="n">class_name</span> <span class="o">=</span> <span class="no">Object</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>On second thought, what’s the point of class_name being optional? It made sense for the original serialize method, but not typed_serialize. Let’s make class_name mandatory.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">ActiveRecord::Base</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">typed_serialize</span><span class="p">(</span><span class="n">attr_name</span><span class="p">,</span> <span class="n">class_name</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>OK, now our User model can properly execute, but it does absolutely nothing. So let’s at least call Rails’ serialize method to get the standard behavior.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">ActiveRecord::Base</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">typed_serialize</span><span class="p">(</span><span class="n">attr_name</span><span class="p">,</span> <span class="n">class_name</span> <span class="o">=</span> <span class="no">Object</span><span class="p">)</span>
<span class="n">serialize</span><span class="p">(</span><span class="n">attr_name</span><span class="p">,</span> <span class="n">class_name</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<h3>Adding the meat</h3>
<p>Our repeated code revolved around a custom reader for a serialized attribute. So let’s add a custom reader for attr_name using define_method and our original repeated code.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">ActiveRecord::Base</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">typed_serialize</span><span class="p">(</span><span class="n">attr_name</span><span class="p">,</span> <span class="n">class_name</span> <span class="o">=</span> <span class="no">Object</span><span class="p">)</span>
<span class="n">serialize</span><span class="p">(</span><span class="n">attr_name</span><span class="p">,</span> <span class="n">class_name</span><span class="p">)</span>
<span class="n">define_method</span><span class="p">(</span><span class="n">attr_name</span><span class="p">)</span> <span class="k">do</span>
<span class="n">value</span> <span class="o">=</span> <span class="k">super</span>
<span class="k">if</span> <span class="n">value</span><span class="p">.</span><span class="nf">is_a?</span><span class="p">(</span><span class="no">Hash</span><span class="p">)</span>
<span class="n">value</span>
<span class="k">else</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">options</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>The original code has a couple of small problems when inserted into this context. It assumes the value should always be a Hash and written attribute is always named options.</p>
<p>A quick look at serialize’s implementation tells us it stores its data in a hash with the key as the attribute name in string form, and the value is the class_name. We’ll use that to derive the expected class.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">expected_class</span> <span class="o">=</span> <span class="nb">self</span><span class="p">.</span><span class="nf">class</span><span class="p">.</span><span class="nf">serialized_attributes</span><span class="p">[</span><span class="n">attr_name</span><span class="p">.</span><span class="nf">to_s</span><span class="p">]</span>
</code></pre></div></div>
<p>We’ll use Ruby’s send method to call a method with a name we won’t know until runtime.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">send</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="n">attr_name</span><span class="si">}</span><span class="s2">="</span><span class="p">,</span> <span class="n">expected_class</span><span class="p">.</span><span class="nf">new</span><span class="p">)</span>
</code></pre></div></div>
<h3>All together now.</h3>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">ActiveRecord::Base</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">typed_serialize</span><span class="p">(</span><span class="n">attr_name</span><span class="p">,</span> <span class="n">class_name</span> <span class="o">=</span> <span class="no">Object</span><span class="p">)</span>
<span class="n">serialize</span><span class="p">(</span><span class="n">attr_name</span><span class="p">,</span> <span class="n">class_name</span><span class="p">)</span>
<span class="n">define_method</span><span class="p">(</span><span class="n">attr_name</span><span class="p">)</span> <span class="k">do</span>
<span class="n">expected_class</span> <span class="o">=</span> <span class="nb">self</span><span class="p">.</span><span class="nf">class</span><span class="p">.</span><span class="nf">serialized_attributes</span><span class="p">[</span><span class="n">attr_name</span><span class="p">.</span><span class="nf">to_s</span><span class="p">]</span>
<span class="n">value</span> <span class="o">=</span> <span class="k">super</span>
<span class="k">if</span> <span class="n">value</span><span class="p">.</span><span class="nf">is_a?</span><span class="p">(</span><span class="n">expected_class</span><span class="p">)</span>
<span class="n">value</span>
<span class="k">else</span>
<span class="nb">send</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="n">attr_name</span><span class="si">}</span><span class="s2">="</span><span class="p">,</span> <span class="n">expected_class</span><span class="p">.</span><span class="nf">new</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This is my first post detailing an implementation. Interestingly enough, it alerted me to a few unnecessarily complex portions of even this tiny amount of code.</p>
Making Rails' Serialize Even Better2009-02-01T00:00:00+00:00http://thejqr.com/2009/02/01/making-rails-serialize-even-better<p>Rails has this handy method that allows you store almost any object in the database with ease. Most often I end up using it for storing optional attributes in a hash.</p>
<p>Here is the proper syntax for telling Rails that there is an options attribute that should only store Hash values.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
<span class="n">serialize</span> <span class="ss">:options</span><span class="p">,</span> <span class="no">Hash</span>
<span class="k">end</span>
</code></pre></div></div>
<h3>The problem</h3>
<p>The options attribute will start off as nil, and remain nil until you set it to something else. Setting the class_name to Hash only affects what you can write to this attribute.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">>></span> <span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span>
<span class="o">=></span> <span class="c1">#<User id: nil, name: nil, options: nil></span>
<span class="o">>></span> <span class="n">user</span><span class="p">.</span><span class="nf">options</span><span class="p">[</span><span class="ss">:theme</span><span class="p">]</span>
<span class="no">NoMethodError</span><span class="p">:</span> <span class="no">You</span> <span class="n">have</span> <span class="n">a</span> <span class="kp">nil</span> <span class="n">object</span> <span class="k">when</span> <span class="n">you</span> <span class="n">didn</span><span class="err">'</span><span class="n">t</span> <span class="n">expect</span> <span class="n">it!</span>
<span class="no">You</span> <span class="n">might</span> <span class="n">have</span> <span class="n">expected</span> <span class="n">an</span> <span class="n">instance</span> <span class="n">of</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span><span class="o">.</span>
<span class="no">The</span> <span class="n">error</span> <span class="n">occurred</span> <span class="k">while</span> <span class="n">evaluating</span> <span class="kp">nil</span><span class="p">.</span><span class="nf">[</span><span class="p">]</span>
<span class="n">from</span> <span class="p">(</span><span class="n">irb</span><span class="p">):</span><span class="mi">2</span>
<span class="o">=></span> <span class="kp">nil</span>
</code></pre></div></div>
<h3>The solution</h3>
<p>What we really need is to automatically return an empty Hash on this new object so we can go on our merry way.</p>
<p>Add this to your environment.rb.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">config</span><span class="p">.</span><span class="nf">gem</span> <span class="s1">'jqr-typed_serialize'</span><span class="p">,</span>
<span class="ss">:lib</span> <span class="o">=></span> <span class="s1">'typed_serialize'</span><span class="p">,</span>
<span class="ss">:source</span> <span class="o">=></span> <span class="s1">'https://gems.github.com'</span>
</code></pre></div></div>
<p>Now run this command to install the gem.</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>rake gems:install
</code></pre></div></div>
<p>A quick change of our model will fix all of our woes.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
<span class="n">typed_serialize</span> <span class="ss">:options</span><span class="p">,</span> <span class="no">Hash</span>
<span class="k">end</span>
</code></pre></div></div>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">>></span> <span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span>
<span class="o">=></span> <span class="c1">#<User id: nil, name: nil, options: nil></span>
<span class="o">>></span> <span class="n">user</span><span class="p">.</span><span class="nf">options</span><span class="p">[</span><span class="ss">:theme</span><span class="p">]</span>
<span class="o">=></span> <span class="kp">nil</span>
<span class="o">>></span> <span class="n">user</span><span class="p">.</span><span class="nf">options</span>
<span class="o">=></span> <span class="p">{}</span>
</code></pre></div></div>
<p>Voila!</p>
<h3>The how and why</h3>
<p>If you’re curious about how this works, I’ve written a simple post describing the <a href="/2009/02/01/the-making-of-typed-serialize.html">the making of typed_serialize</a>, or you can <a href="https://github.com/jqr/typed_serialize">browse the code</a>.</p>
All My Code Are Belong to Us2009-01-31T00:00:00+00:00http://thejqr.com/2009/01/31/all-my-code-are-belong-to-us<p>I’ve really been pushing myself to move as much code as possible into the public space. <a href="https://github.com">GitHub</a> has come at a perfect time to encourage this behavior. It makes the tedious process of sharing code so easy you’d be stupid not to.</p>
<p>I put all of it <a href="https://github.com/jqr">directly on GitHub</a> as a Rails plugin and a Ruby gem. Learning how to do this is a few hours of investment, but it’s an investment you only need to make once. I’m using <a href="https://blog.evanweaver.com/files/doc/fauna/echoe/files/README.html">Echoe</a> right now, but I’ll probably switch to <a href="https://technicalpickles.com/posts/craft-the-perfect-gem-with-jeweler">Jeweler</a> for even simpler releases.</p>
<p>I am certain that making code reusable is one of the best ways to gain a solid understanding of how a software developer’s tools should be used. Polishing up code for public release encourages a ton of good behavior that makes even personal reuse easier and as a side benefit, other people will improve my code for free!</p>
<p>Most of the plugins and gems I write are simple enhancements to patterns and are the result of DRYing up code in a single project. After abstracting the initial idea from one project, I find it’s much easier to recognize the same pattern in other projects.</p>
<p>So take a few minutes and look for patterns in your code. Give the pattern a name. Uncover the simplest way to express it. Start using it. Discover it’s limitations. Publish it. Talk about it.</p>