<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:posterous="http://posterous.com/help/rss/1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title>Rando's Random Ramblings</title>
    <link>http://blog.theamazingrando.com</link>
    <description>Paul's ill-concieved and poorly thought out ideas on programming and the web</description>
    <generator>posterous.com</generator>
    <link xmlns="http://www.w3.org/2005/Atom" href="http://posterous.com/api/sup_update#164b84d7d" type="application/json" rel="http://api.friendfeed.com/2008/03#sup" />
    
    
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/theamazingrando" /><feedburner:info uri="theamazingrando" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://posterous.superfeedr.com/" /><item>
      <pubDate>Sun, 10 Apr 2011 08:17:12 -0700</pubDate>
      <title>Annoucing ProgressBar</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/EV5cJPxM70k/annoucing-progressbar</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/annoucing-progressbar</guid>
      <description>
        <![CDATA[<p>
	<h1>ProgressBar</h1>

<p>I was working on a script to sync hundreds of thousands of records between two databases, and wanted a simple way to keep track of progress. I couldn&#8217;t find one that was easy to use and did what I wanted, so I <a href="https://github.com/paul/progress_bar">wrote my own</a>. Not much more introduction needed, how about a simple example?</p>

<div class="CodeRay">
  <div class="code"><pre>$ cat examples/simple.rb

require 'progres_bar'
bar = ProgressBar.new

100.times do
  sleep 0.1
  bar.increment!
end

$ ruby examples/simple.rb
[#########################                                      ] [ 39/100] [ 39%] [00:04] [00:06] [  9.12/s]</pre></div>
</div>
	
</p>

<p><a href="http://blog.theamazingrando.com/annoucing-progressbar">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/annoucing-progressbar#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/annoucing-progressbar</feedburner:origLink></item>
    <item>
      <pubDate>Sun, 06 Feb 2011 07:23:21 -0800</pubDate>
      <title>Rando's Wing Sauce Recipe</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/26_EU4mCXD8/randos-wing-sauce-recipe</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/randos-wing-sauce-recipe</guid>
      <description>
        <![CDATA[<p>
	<h1>Motto: If it didn&#8217;t burn going in, and it didn&#8217;t burn going out, it wasn&#8217;t hot enough.</h1>

<p>In honor of the <a href="http://i.imgur.com/JI58O.jpg">Superb Owl</a>:</p>

<ol>
<li>
<p>Melt 1tbsp butter in a large saucepan.</p>
</li>

<li>
<p>Add:</p>

<ul>
<li>2 large bottles (24oz total) Louisiana &#8220;Red Hot&#8221; Sauce (Or Frank&#8217;s, but its not as good).</li>

<li>1 small bottle Tabasco Sauce</li>

<li>1 tsp garlic powder</li>

<li>1 tbsp Worcestershire Sauce</li>

<li>1 tbsp soy sauce</li>

<li>2 heaping tbsp ketchup</li>

<li>2 tbsp pure maple syrup</li>
</ul>
</li>

<li>
<p>Turn on the vent hood and simmer this mess for 15-30 minutes. You&#8217;re trying to reduce as much of the water as you can. Don&#8217;t turn it up past low - med-low, or it&#8217;ll burn.</p>
</li>

<li>
<p>Let the mixture cool.</p>
</li>

<li>
<p>Deep fry some wings, or bake some boneless breaded chicken tenders, according to the instructions on the package.</p>
</li>

<li>
<p>In a large, watertight container, put a few wings, and ladle in some of the sauce. Shake vigorously. Repeat for all the wings.</p>
</li>
</ol>

<p>If you&#8217;re a wimp, serve with celery or ranch dressing.</p>

<p>To make it less hot, don&#8217;t cook it as long, and/or add more ketchup. For more hot, add cayenne pepper.</p>

<p>This should be enough sauce to coat 100 wings, or a 10-lb bag of chicken fingers.</p>

<p>Slightly modified from <a href="http://www.richterscale.org/recipes/buffwing.htm">Jake&#8217;s Famous Buffalo Wing Recipe</a>.</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/randos-wing-sauce-recipe">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/randos-wing-sauce-recipe#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/randos-wing-sauce-recipe</feedburner:origLink></item>
    <item>
      <pubDate>Fri, 21 Jan 2011 04:20:50 -0800</pubDate>
      <title>The Road to Better Authorization</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/NMdceaoabUA/the-road-to-better-authorization</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/the-road-to-better-authorization</guid>
      <description>
        <![CDATA[<p>
	<h2>The Problem</h2>

<p>I have several Google accounts: My <a href="mailto:psadauskas@gmail.com">personal email</a>, Google Apps at <a href="http://absolute-performance.com">my employer</a>, and Gmail for <a href="http://theamazingrando.com">my domain</a>. I use my personal email all the time, and have several Google Docs spreadsheets and letters. Our company uses Google Docs and Sites. Its extremely annoying that switching between these accounts is brittle, and unpredictable. The same situation existed on Github between my personal and the company account, before they added &#8220;Organizations&#8221;.</p>

<p>The other problem is poor integration with the hundreds of accounts I have across various sites. I have a simple password that I use for throwaway, which is still horribly insecure. The alternative is a password manager such as KeePass or 1Password, but browser integration is poor or non-existent.</p>

<p>I use the <a href="http://chrome.desc.se/">Google Mail Checker Plus</a> extension for Chrome, which can automatically redirect me to the Gmail inbox for each account, and from there I can follow links to Docs or Sites. However, all the accounts are &#8220;logged in&#8221;, and I occasionally experience trouble and get permission denied errors when I click on a document link in my list.</p>

<p>My main workaround at this point is to use Chrome for normal browsing and personal accounts, and Firefox, which I use for development &amp; debugging anyways, has the saved passwords for company accounts. This has worked for awhile, but as I amass various side-projects, and need a 3rd login for some sites (Github and Amazon AWS seem to be the main ones), I don&#8217;t want to have to maintain more browser profiles.</p>

<p>Ideally, the browser and sites would integrate and work together to manage everything automatically, but this is a chicken and egg problem. The solution will likely have to be completed in stages.</p>

<p>OpenID and OAuth are attempts at solving this on the server side, but they are complicated. And they need to be, because there&#8217;s several parties involved, all needing to handshake with each other and prove everyone&#8217;s identity. I feel a simpler solution, and a much better way to handle this, would be in the browser itself. Even the technical name for the browser, &#8220;User Agent&#8221;, indicates its purpose. I see it as the concierge at an expensive hotel. They have the inside knowledge of the city, and the personal contacts, to get you anything you need. Want blueberry and peanut-butter waffles at 11pm? Call the concierge and he&#8217;ll figure out how to get it for you.</p>

<p>Same for the browser. It&#8217;s your concierge for the web. You don&#8217;t need to know HTML and CSS to be able to use a website, the browser renders the text and images into a sensible layout for you to read. If a page moved, you don&#8217;t have to type in the new location manually, the browser automatically goes there for you. If you need credentials to visit your Facebook page, you don&#8217;t have to deal with the ugly bouncer directly, the concierge coughs and politely asks you for your password. What I&#8217;m proposing is promoting your concierge to your own personal assistant. You shouldn&#8217;t even need to know there <em>is</em> a bouncer, because your assistant has already made arrangements and you can walk right in.</p>

<h2>Phase 1</h2>

<p>The first step is a browser extension for managing all my accounts at various sites. On a site where I have several accounts, or a personal account and a shared corporate account, it would be great to have a simple way to switch between them. When I come to a page, but want to view it as a different account, I have to:</p>

<ol>
<li>Find and click a &#8220;Sign Out&#8221; link.</li>

<li>Find the &#8220;Sign In&#8221; link.</li>

<li>Clear the &#8220;username&#8221; field of the form, and replace it with the other account&#8217;s username.</li>

<li>Hope the browser remembers the other account&#8217;s password, or look it up and fill it in.</li>

<li>Navigate back to the original page.</li>
</ol>

<p>Compare that to a browser extension or built-in feature:</p>

<ol>
<li>Click &#8220;Account Manager&#8221; toolbar button, which provides a list of known accounts for the site.</li>

<li>Select the account from the list.</li>
</ol>

<p>The implementation would be straightforward. Just save all the cookies currently associated with the domain and tie them to that account, then load the previously stored cookies for the account that was selected, and re-request the page with the new cookies. If the page is using http authentication, the browser only has to change which Authorization header it is providing to the site.</p>

<p>There have been various attempts to do this, but nothing ever seems completed. I haven&#8217;t attempted my own, so maybe there&#8217;s some complication that I&#8217;m missing. Mozilla has a proposal for such an extension called <a href="https://wiki.mozilla.org/Labs/Weave/Identity/Account_Manager">Account Manager</a>, but there seems to be no real activity since a few weeks after the project was announced back in March 2010. This seems like a real win for users, I can&#8217;t understand why no browser has this built-in, or even an extension. I&#8217;d switch to Opera or Safari in a minute if they offered this, its a killer feature for a browser.</p>

<p>There&#8217;s also programs such as <a href="http://www.keepassx.org/">KeePassX</a>, <a href="http://agilewebsolutions.com/onepassword">1Password</a>, and <a href="https://lastpass.com/">LastPass</a>, some of which include browser plugins that can manage passwords for you. These all seem to be standalone password managers first, with the browser integration coming 2nd, which can sometimes be pretty clunky. Phase one needs to be a browser extension specifically designed to integrate with web site logins.</p>

<h2>Phase 2</h2>

<p>The next phase would be for the browser to be able to manage account creation. Since the browser can manage my accounts, it would be handy if it would create them, by automatically filling out the sign up form at the site. Browsers already have my name, email, address, etc, from being able to auto-fill forms. It could auto-fill the sign up form with my personal information (or suitably anonymized information if I choose), create a login and a random password, and save all that with the account manager.</p>

<p>Undoubtedly, this would require &#8220;rules&#8221; for lots of sites, similar to adblock extensions, to know which signup fields are which, and how exactly to fill out the signup form. Perhaps some JSON to indicate field names, or even some javascript.</p>

<p>For example, say we have a signup form (like, say, Facebook&#8217;s, with non-essential tags stripped out):</p>

<div class="CodeRay">
  <div class="code"><pre>&lt;form method=&quot;post&quot; id=&quot;reg&quot; name=&quot;reg&quot;&gt;
  &lt;input type=&quot;text&quot; class=&quot;inputtext&quot; id=&quot;firstname&quot; name=&quot;firstname&quot;&gt;
  &lt;input type=&quot;text&quot; class=&quot;inputtext&quot; id=&quot;lastname&quot; name=&quot;lastname&quot;&gt;
  &lt;input type=&quot;text&quot; class=&quot;inputtext&quot; id=&quot;reg_email__&quot; name=&quot;reg_email__&quot;&gt;
  &lt;input type=&quot;text&quot; class=&quot;inputtext&quot; id=&quot;reg_email_confirmation__&quot; name=&quot;reg_email_confirmation__&quot;&gt;
  &lt;input type=&quot;password&quot; class=&quot;inputtext&quot; id=&quot;reg_passwd__&quot; name=&quot;reg_passwd__&quot; value=&quot;&quot;&gt;
  &lt;select class=&quot;select&quot; name=&quot;sex&quot; id=&quot;sex&quot;&gt;&lt;option value=&quot;1&quot;&gt;Female&lt;option value=&quot;2&quot;&gt;Male&lt;/select&gt;
  &lt;select id=&quot;birthday_month&quot; name=&quot;birthday_month&quot;&gt;...&lt;/select&gt;
  &lt;select name=&quot;birthday_day&quot; id=&quot;birthday_day&quot;&gt;...&lt;/select&gt;
  &lt;select name=&quot;birthday_year&quot; id=&quot;birthday_year&quot;&gt;...&lt;/select&gt;
  &lt;input value=&quot;Sign Up&quot; type=&quot;submit&quot;&gt;
&lt;/form&gt;</pre></div>
</div>


<p>Since names like <code>&quot;reg_email__&quot;</code> are rather nonstandard, we&#8217;ll need some way to map the fields we know for our profile to the fields on the website form. The mappings are probably too complicated to be one-to-one with a simple XML or JSON file, however a JavaScript function could be executed:</p>

<div class="CodeRay">
  <div class="code"><pre>function performSignup(profile) {
  $(&quot;#firstname&quot;).val(profile.first_name);
  $(&quot;#lastname&quot;).val(profile.last_name);
  $(&quot;#reg_email__&quot;).val(profile.email);
  $(&quot;#reg_email_confirmation__&quot;).val(profile.email);
  $(&quot;#reg_passwd__&quot;).val(profile.generate_random_password());
  $(&quot;#sex&quot;).val(profile.gender == &quot;male&quot; ? &quot;2&quot; : &quot;1&quot;);
  $(&quot;#birthday_day&quot;).val(profile.birthday.day);
  $(&quot;#birthday_month&quot;).val(profile.birthday.month);
  $(&quot;#birthday_year&quot;).val(profile.birthday.year);

  $(&quot;#reg&quot;).submit();
}</pre></div>
</div>


<p>Some helpers to make that less verbose, and getting contributions to write rules for the most common sites, and now your browser can perform signups for you. If this becomes popular or compelling to websites to implement, a JavaScript browser API could be exposed so that websites could implement the signup function themselves.</p>

<div class="CodeRay">
  <div class="code"><pre>&lt;script&gt;
  accountManager.setSignup(function(profile) { ... } );
&lt;/script&gt;</pre></div>
</div>


<p>Where <code>setSignup</code> is the browser API function to call to assign your website&#8217;s signup function, and <code>profile</code> is an object containing the personal information provided by the user.</p>

<h2>Phase 3</h2>

<p>Phase 3 involves developing an API between the browser and the web page directly. It can be a simple extension to some of the new HTML5 APIs out there for dealing with video or local storage in javascript. Hopefully (but not likely, given how similar projects have played out before), each browser that implements this would have a similar API that common elements could be used.</p>

<h2>Conclusion</h2>

<p>In conclusion, authentication for web services sucks, and has for a long time. The right place to manage this is in the browser itself, rather than a complicated handshaking protocol between servers. Writing a browser extension like the one described in Phase 1 is on my TODO list, but I know nothing about browser extensions, and have plenty of other projects to keep me busy. If someone out there is willing to take this on, drop me a line, I&#8217;d certainly love to help.</p>

<h2>Extra Credit</h2>

<ul>
<li>Store all the data in the cloud, so its not lost in reformats, and can be shared between computers. Even better, have an interchange format so it can be shared between browsers, and your phone, so you can login to sites from wherever.</li>

<li>An extension to the built-in HTTP Auth methods, something more secure than the MD5 used in Digest Auth. Properly implemented with nonces and cnonces, Digest Auth is still pretty secure, but it will only be a matter of time before MD5 can be brute-forced in a reasonable amount of time. Or maybe just convince everyone that all HTTP should be over SSL, and then we can just use Basic Auth. Once people start using browser authentication managers, no-one will care about styling the login form any more. Maybe the browser could load the favicon, or follow a <code>&lt;link&gt;</code> tag to a logo image for the site being logged in to.</li>
</ul>
	
</p>

<p><a href="http://blog.theamazingrando.com/the-road-to-better-authorization">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/the-road-to-better-authorization#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/the-road-to-better-authorization</feedburner:origLink></item>
    <item>
      <pubDate>Sat, 25 Sep 2010 08:04:00 -0700</pubDate>
      <title>Dear Microsoft: Please Do Pinned Menus Like This</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/2FtO5pL-vR8/pinned-menus-with-the-link-element</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/pinned-menus-with-the-link-element</guid>
      <description>
        <![CDATA[<p>
	<p>With the IE9 betas beginning to come out, Microsoft have introduced an interesting new feature they&rsquo;re calling <a href="http://msdn.microsoft.com/en-us/library/gg131029(VS.85).aspx">pinned sites</a>. For more details about how it works, you can check out the <a href="http://arstechnica.com/microsoft/news/2010/09/inside-internet-explorer-9-redmond-gets-back-in-the-game.ars/4">Ars Technica preview</a>. Essentially, you put several ms-vendor specific <code>meta</code> tags in the html of your header that describe the menu. The example given on the Ars preview uses this markup:</p>
<div class="CodeRay">
  <div class="code"><pre>&lt;meta name=&quot;application-name&quot; content=&quot;Ars Technica&quot;/&gt;
&lt;meta name=&quot;msapplication-starturl&quot; content=&quot;http://arstechnica.com/&quot;/&gt;
&lt;meta name=&quot;msapplication-tooltip&quot; content=&quot;Ars Technica: Serving the technologist for 1.2 decades&quot;/&gt;
&lt;meta name=&quot;msapplication-task&quot; content=&quot;name=News;action-uri=http://arstechnica.com/;icon-uri=http://arstechnica.com/favicon.ico&quot;/&gt;
&lt;meta name=&quot;msapplication-task&quot; content=&quot;name=Features;action-uri=http://arstechnica.com/features/;icon-uri=http://static.arstechnica.net/ie-jump-menu/jump-features.ico&quot;/&gt;
&lt;meta name=&quot;msapplication-task&quot; content=&quot;name=OpenForum;action-uri=http://arstechnica.com/civis/;icon-uri=http://static.arstechnica.net/ie-jump-menu/jump-forum.ico&quot;/&gt;
&lt;meta name=&quot;msapplication-task&quot; content=&quot;name=One Microsoft Way;action-uri=http://arstechnica.com/microsoft/;icon-uri=http://static.arstechnica.net/ie-jump-menu/jump-omw.ico&quot;/&gt;
&lt;meta name=&quot;msapplication-task&quot; content=&quot;name=Subscribe;action-uri=http://arstechnica.com/subscriptions/;icon-uri=http://static.arstechnica.net/ie-jump-menu/jump-subscribe.ico&quot;/&gt;</pre></div>
</div>

<p>&hellip;to produce this Windows 7 &ldquo;pinned menu&rdquo;:</p>
<p><img src="http://static.arstechnica.com/ie-9-beta-1/ie9-ars-jump-list.png" alt="Ars Technica pinned menu" /></p>
<p>Kroc Camen at <a href="http://camendesign.com/">Camen Design</a> has a <a href="http://camendesign.com/blog/stop_this_madnessels">pretty decent rant</a> about how he thinks this is a bad idea. However, aside from the annoying proprietary <code>.ico</code> image format, the way Microsoft chose to use the <code>meta</code> element it isn&rsquo;t nearly as bad as what Mr. Camen proposes in its stead.</p>
<h2>The <code>Meta</code> Element</h2>
<p>I take no issue with Microsoft&rsquo;s use of the <code>meta</code> element. It was always intended to be used by vendors for browser-specific features. From the <a href="http://wiki.whatwg.org/wiki/MetaExtensions">HTML5 working group wiki</a>:</p>
<blockquote class="posterous_medium_quote">
<p>You may add your own values to this list, which makes them legal HTML5 metadata names. We ask that you try to avoid redundancy; if someone has already defined a name that does roughly what you want, please reuse it.</p>
</blockquote>
<p>That said, this implementation is far from ideal. It is extremely verbose, 8 lines and over 1KB of text. Not surprising, as Microsoft and IE have always had issues with <a href="http://www.gethifi.com/blog/browser-rest-http-accept-headers">extreme</a> <a href="http://stackoverflow.com/questions/2838635/ajax-microsoft-com-vs-cookieless-domain-for-cdn">verbosity</a>. This text will have to be sent with every page that a user might possibly want to &ldquo;pin&rdquo; your site from. Every page * every visitor * 1KB = a whole lot of bandwidth.</p>
<p>Camen&rsquo;s proposal is to use the new HTML5 <code>menu</code> element, in the body of the page. Not only does this have the same problems as above, its going to break accessibilty. Even if its it hidden from view by CSS, screen readers and other devices are going to be confused by having a <code>menu</code> stuck in the page, that is only tangentially related to the page&rsquo;s content.</p>
<p>Luckily, there is a perfectly acceptable solution: the <code>link</code> element.</p>
<h2>The <code>Link</code> Element</h2>
<p>You&rsquo;re probably already familiar with <a href="http://dev.w3.org/html5/spec/Overview.html#the-link-element">this element</a>; you use it any time you want to attach a stylesheet to your page.</p>
<div class="CodeRay">
  <div class="code"><pre>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;/style.css&quot;&gt;</pre></div>
</div>

<p>The <code>rel</code> attribute is a space-separated list of keywords that describe what <em>relationship</em> the linked content has to this page. So the IE pinned menu markup above could easily be replaced with:</p>
<div class="CodeRay">
  <div class="code"><pre>&lt;link rel=&quot;ms-pinned-menu&quot; type=&quot;application/xml&quot; href=&quot;/pinned-menu.xml&quot;&gt;</pre></div>
</div>

<p>Then <code>pinned-menu.xml</code> could be simple xml (or HTML5 menu!) describing the menu. By doing it this way, web applications gain all the same benefits as serving linked stylesheets: it can be cached, and hosted as a static file on a CDN. Additionally, its much easier to extend the XML dialect as more browsers want to support Windows 7 pinned menus. Further, its a jumping-point to more integrated browser features, such as Android&rsquo;s &ldquo;Menu&rdquo; button, and single-page browser wrappers like Fluid and Prism.</p>
<p>I know its too late to get Microsoft to fix this in IE9, but hopefully the other browser vendors will be more forward-thinking, and let us developers do this the easy way, without adding kilobytes of additional markup to all our pages.</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/pinned-menus-with-the-link-element">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/pinned-menus-with-the-link-element#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/pinned-menus-with-the-link-element</feedburner:origLink></item>
    <item>
      <pubDate>Thu, 01 Jul 2010 15:18:03 -0700</pubDate>
      <title>About this Blog</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/a2uOzQPbStA/about-this-blog-28</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/about-this-blog-28</guid>
      <description>
        <![CDATA[<p>
	<p>After nearly a year on hiatus, I&#8217;m finally ready to start blogging again. I have several neat projects I&#8217;ve been working on over the last several months, and I need a place to write about them.</p>

<h2>Why I stopped using Wordpress</h2>

<p>My <a href="http://theamazingrando.com/blog">self-hosted Wordpress blog</a> on my Slicehost served me well over the last few years. With a hodge podge of plugins and hacks, I was able to write my posts in markdown. I was still stuck writing them in the textarea of the browser, or copy-pasting them from my real editor to the browser, but it worked well enough. Eventually, though, I was updating Wordpress for security vulnerabilities more often than I was posting, and it was collecting a ton of spam comments. I decided that I didn&#8217;t want to be in charge of that extra stuff any more.</p>

<p>I made several attempts to port my blog over to something else. I had a few simple goals:</p>

<ul>
<li>The canonical place for my posts is git. Version control of the posts is definitely the way to go.</li>

<li>I just want to write content, not moderate spam, or manage plugins.</li>

<li>I don&#8217;t want to maintain blogging software.</li>
</ul>

<p>I looked for several solutions, but nothing really fit the bill. Posterous&#8217;s announcement that they supported markdown got the wheels turning, though. Credit for the final bits go to <a href="http://barelyenough.org/">Peter Williams</a> and <a href="http://twitter.com/spikex">@spikex</a>, who got me started about how to manage drafts that I don&#8217;t want published.</p>

<h2>Importing Wordpress</h2>

<p>First, however, I had to get all my old posts out of Wordpress and into a git repo. I hacked together <a href="http://github.com/paul/blog.theamazingrando.com/blob/master/lib/import.rb">this little script</a> which parsed the Wordpress XML dump. It goes over the posts and creates a branch for each, adds the markdown for the post, then merges the branch into master. I did this so that I could get a bit of metadata about the posts in the git repo. The first commit for a post would be the &#8220;created&#8221; date, and the commit when it was merged into master would be the &#8220;published&#8221; date.</p>

<p>Only after I did all this did I figure out that Posterous only exposed a &#8220;date&#8221;, but this worked well together with another shortcoming: the lack of metadata on the post itself. I originally wanted a way to handle updating existing posts, but I had no metadata to find the post again. So for the post&#8217;s &#8220;date&#8221;, I used the most-recent commit date, at the time of the sync. As long as I keep the post &#8220;Title&#8221; unique, I&#8217;ll be able to find the post again, and update the content, but not the date.</p>

<h2>Syncing with Posterous</h2>

<p>So the official place for all my posts is my own git repo, where I can track changes, and manage it. I get to write using whatever editor I feel like, instead of a textarea in a browser, and I get to write them in markdown. I have a <a href="http://github.com/paul/blog.theamazingrando.com/blob/master/lib/sync.rb">script</a> that I use to publish all my posts to Posterous. The script is rather dumb, and just updates everything that needs updated. I had planned on making it better, but due to some shortcomings in the Posterous API, and in the <a href="http://github.com/twoism/postly">postly</a> ruby gem, I took the lazy way out. You can see in the script where I had to monkey-patch the postly gem to make it even work at all. Posterous also needs to read my last <a href="http://blog.theamazingrando.com/your-web-service-might-not-be-restful-if">blog post</a></p>

<p>I wanted to use Posterous&#8217;s markdown, but it had its own shortcomings, like it couldn&#8217;t handle the metadata, or definition lists, like the <a href="http://maruku.rubyforge.org/">maruku</a> gem can. So just render it myself, and post the html body to Posterous. This means I&#8217;ll eventually have to figure out things like syntax highlighting, but since Posterous supports inline gists, maybe I&#8217;ll just do that.</p>

<h2>Finally</h2>

<p>So, in conclusion, its not perfect, but it&#8217;ll do. I&#8217;ll probably write a follow-up post, about what the Posterous API needs to add, since their own docs say its incomplete, and they don&#8217;t know what to do with it. It also exposed some flaws in the HTTParty gem, which I hadn&#8217;t had exposure to until now. Its not really a bug, but rather a design decision, in that the request method only has two params: <code>post url, options = {}</code>. It tries to be smart about those options, and if you have one called <code>:body</code>, it becomes the body of the request. However, Posterous has a param in their API called <code>&quot;body&quot;</code>, which just confused everybody. Additionally, the postly gem crammed everything in the query parameters, which quickly runs into URL length limits for my admittedly verbose blog posts.</p>

<p>The world would be a better place if everyone would just use <a href="http://github.com/paul/resourceful">Resourceful</a>. <code>&lt;/shameless-plug&gt;</code></p>

<p>Overall, I wrote ~100 lines of Ruby to import my old wordpress blog, and sync the whole thing up to Posterous. I don&#8217;t have to host or maintain anything, so its a definite win. I hope it gives my more time to write about all the cool shit I&#8217;ve been working on over the last few months, and well as my new project, <a href="http://mongomachine.com">MongoMachine</a>. Stay tuned!</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/about-this-blog-28">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/about-this-blog-28#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/about-this-blog-28</feedburner:origLink></item>
    <item>
      <pubDate>Wed, 30 Jun 2010 12:44:00 -0700</pubDate>
      <title>Test Post</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/EOafdxpN-Kk/test-post-tFsba</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/test-post-tFsba</guid>
      <description>
        <![CDATA[<p>
	<p>Testing posterous's Ruby API.  </p>
	
</p>

<p><a href="http://blog.theamazingrando.com/test-post-tFsba">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/test-post-tFsba#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/test-post-tFsba</feedburner:origLink></item>
    <item>
      <pubDate>Sun, 19 Jul 2009 20:11:45 -0700</pubDate>
      <title>Your Web Service Might Not Be RESTful If...</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/OqGUBgMDT7s/your-web-service-might-not-be-restful-if</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/your-web-service-might-not-be-restful-if</guid>
      <description>
        <![CDATA[<p>
	<p>The other day, I gave a brief talk about our HTTP Library, <a href="http://github.com/paul/resourceful">Resourceful</a>. After a few minutes of going over the features, it became apparent to me that very few people have taken the time to appreciate the finer points of HTTP. Everyone who calls themself a web application developer needs to take a few hours to read <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC2616: Hypertext Transfer Protocol &#8211; HTTP/1.1</a>. Its not very long, and increadibly readable for a spec. Print it out, and read a few sections when you go for your morning &#8220;reading library&#8221; break. Unfortunately, a great many people got confused by it, and ended up reimplementing a lot of http in another layer, and thats how we ended up with SOAP and XML-RPC. There&#8217;s a good parable about <a href="http://serialseb.blogspot.com/2009/06/fighting-for-rest-or-tale-of-ice-cream.html">how this all went of the rails for awhile</a>, until some people re-discovered a section in Roy T. Fielding&#8217;s disseration, &#8221;<a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">Representational State Transfer (REST)</a>&#8221;.</p>

<p>Needless to say, REST is making a huge comeback, at least in the agile startup communities. It&#8217;s fast, lightweight, and easy to put together. Ruby on Rails even has excellent support for getting up and running quicky. Sadly, though, it&#8217;s not quite right, and as a result, developers have misconstrued REST yet again, and its making things harder than they really need to be, and also leading them down a path that leads to lots of headaches in the future. If you&#8217;re interested in learning more about REST, there&#8217;s plenty of excellent resources on the <a href="http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage">REST Wiki</a>, particularly <a href="http://rest.blueoxen.net/cgi-bin/wiki.pl?RestInPlainEnglish">REST In Plain English</a>.</p>

<p>For some of my examples, I&#8217;m going to pick on the <a href="http://www.pivotaltracker.com/help/api">Pivotal Tracker &#8220;RESTful&#8221; API</a>. Sorry guys, I needed to pick someone, and I love your product (I use it every day), but you&#8217;re part of the reason for this post. I wanted to write a client for your service, but its really much harder than it needs to be. The service violates many of the constraints of REST, and therefore naming it &#8220;RESTful&#8221; is incorrect. You&#8217;re not the only ones, though, so don&#8217;t feel bad, nearly EVERY API that claims to be RESTful isn&#8217;t. For a look at one that gets it (mostly) right, check out <a href="http://developer.netflix.com/docs">Netflix</a>.</p>

<h1>If Your Web Services Do Any of These Things, You&#8217;re Doing it Wrong</h1>

<ol>
<li>Clients have to read documentation to know the locations of top-level resources.</li>

<li>Clients have to concatenate strings to get to the next resource.</li>

<li>You have an &#8220;API/Key/Token&#8221; in a header or a url.</li>

<li>You have a version string in a url.</li>
</ol>

<h2>1. Have a Minimum of Starting Points</h2>

<p>If you look at the <a href="http://www.pivotaltracker.com/help/api#api_actions">Available Actions on Pivotal Tracker&#8217;s API page</a>, you&#8217;ll see they list several actions that can be performed. This isn&#8217;t REST, this is XML-RPC. Nearly everybody gets this one wrong. Due to the amount of confusion, Roy Fielding <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">published a post</a> to stop people abusing the term &#8220;RESTful&#8221; and to try and clarify what a real RESTful API is. His final point is:</p>

<blockquote class="posterous_medium_quote">
<p>A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API).</p>
</blockquote>

<p>The point here is that there should be only one resource that is the starting point for any interaction with the service. This is called a &#8220;well-known&#8221; resource, and is never, <em>ever</em> allowed to change locations. If it does change, you break every single client out there. By publishing a dozen or more well-known resources in their API docs, Tracker is no longer permitted to change any of them. This increases the maintenance burden, because now they have to maintain all these resources for the lifetime of the application, or deprecate any third-party clients.</p>

<p>If they had instead added a single resource that described the locations of these other resources, they would have much more flexibility in the future. An example of the content of such a resource:</p>

<div class="CodeRay">
  <div class="code"><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;services&gt;
  &lt;service&gt;
    &lt;name&gt;AllProjects&lt;/name&gt;
    &lt;href&gt;http://www.pivotaltracker.com/services/projects&lt;/href&gt;
  &lt;/service&gt;
  &lt;service&gt;
    &lt;name&gt;AllActivities&lt;/name&gt;
    &lt;href&gt;http://www.pivotaltracker.com/services/activites&lt;/href&gt;
  &lt;/service&gt;
&lt;/services&gt;</pre></div>
</div>


<p><em>Note: Yes, they list several other actions on their API. However, each of them violates another one of the REST constraints, so I have ommitted them for the time being.</em></p>

<p>Now every client just needs to know the name of the resource they&#8217;re looking for, eg &#8220;AllActivites&#8221;, and they can continue as before. If, for some perfectly valid reason, Pivotal decides to change the name of &#8220;Activites&#8221; to, say, &#8220;Actions&#8221;, they only have to modify the <code>href</code> of the &#8220;AllActivities&#8221; service description, add a &#8220;AllActions&#8221; service, and every single client using it by the name instead of a hardcoded href continues to work flawlessly, or at least as well as it did before. Less maintenance burden on the service developers, and no burden at all for the developer of a well-written client.</p>

<h2>2. Don&#8217;t Make a Client Construct URIs</h2>

<p>In that very same bullet point, Roy continues&#8230;</p>

<blockquote class="posterous_short_quote">
<p>From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations&#8230;</p>
</blockquote>

<p>If you look at the <a href="http://www.pivotaltracker.com/help/api#api_actions">Tracker API docs Available API Actions</a> for projects, you&#8217;ll see &#8220;Single project&#8221; and &#8220;All my projects&#8221;. We already covered how to handle the &#8220;AllProjects&#8221; resource, an in the example above, we remove the &#8220;Single project&#8221; resource entirely. So how do you get to the resource for a single project? Simple, you follow its link in the &#8220;AllProjects&#8221; resource.</p>

<div class="CodeRay">
  <div class="code"><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
    &lt;projects type=&quot;array&quot;&gt;
      &lt;project&gt;
        &lt;href&gt;http://www.pivotaltracker.com/services/v2/projects/1&lt;/href&gt;

        &lt;id&gt;1&lt;/id&gt;
        &lt;name&gt;Sample Project&lt;/name&gt;
        &lt;iteration_length type=&quot;integer&quot;&gt;2&lt;/iteration_length&gt;
        &lt;week_start_day&gt;Monday&lt;/week_start_day&gt;
        &lt;point_scale&gt;0,1,2,3&lt;/point_scale&gt;

        &lt;stories_href&gt;http://www.pivotaltracker.com/services/v2/projects/1/stories?{-join|&amp;|filter,limit,offset}&lt;/stories_href&gt;
        &lt;iterations_href&gt;http://www.pivotaltracker.com/services/v2/projects/1/iterations&lt;/iterations_href&gt;
        &lt;activities_href&gt;http://www.pivotaltracker.com/services/v2/projects/1/activities&lt;/activities_href&gt;
      &lt;/project&gt;
      &lt;!-- ... --&gt;
    &lt;/projects&gt;</pre></div>
</div>


<p>For a client to find a single project, they would know its name. They would GET the list of services, find &#8220;AllProjects&#8221; by name, GET the &#8220;href&#8221; provided, and look for the project &#8220;Sample Project&#8221; by name. They could then use the href attribute to obtain the single resource for the project. Additionally, we also have links to all the actions in the docs that required a <code>PROJECT_ID</code> in the url. To get the iterations or activities for a project, a client has to only locate the project, and follow the links.</p>

<p>You should also notice the part of the <code>stories_href</code> enclosed in <code>{braces}</code>. This is known as a <a href="http://bitworking.org/projects/URI-Templates/">URI Template</a>, and is very handy. If you noticed in pivotals API docs, they had three ways of getting stories: All stories, stories by a filter, and stories by a limit and offset. I took the liberty of combining these into single href, using the template to describe the query parameters. A ruby client, using the <code>Addressable::URI</code> library, could fill out that uri like this:</p>

<div class="CodeRay">
  <div class="code"><pre>template = Addressable::Template(stories_href)
template.expand({
  &quot;filter&quot; =&gt; 'label:&quot;needs feedback&quot; type:bug'
})</pre></div>
</div>


<p>All these extra requests might seem like a rather long way of going about it, however, the advantages are immense:</p>

<p>Should Tracker become huge, and everybody and their grandmother starts using it to keep track of their development projects, Tracker could outstrip the load of a single database. Since it appears they are using <code>AUTOINCREMENT id</code> columns for the project id, sharding the <code>projects</code> table is going to be hard. However, if they were to start using <code>UUID</code> columns for project ids, then sharding is a whole lot less complicated. However, if they change the project id in the API, everyone&#8217;s clients break. If clients were to instead follow the href, they can do whatever they want to the id, and existing clients will have no trouble at all following.</p>

<p>But wait, it gets better. What happens if the service still isn&#8217;t fast enough, for any number of perfectly plausible reasons? Because they&#8217;re using hrefs, they can put <em>anything they want</em> there. Say they decide to shard the application servers, so every project with an odd-numbered id goes to <code>www1.pivotaltracker.com</code>, and everything even-numbered goes to <code>www2.pivotaltracker.com</code>. They just have to update the links, and everyone&#8217;s client continues working.</p>

<p>If all resources are specified like this, then a client can get to every resource from that one starting point. You are free to move, rename, and add resources as you desire, without making things complicated for your API clients. Less maintenance burden on you, and none on your users.</p>

<h2>Don&#8217;t put an &#8220;API Token&#8221; in a custom header, or in the URIs</h2>

<p>While there&#8217;s nothing technically un-RESTful about this, its still annoying to your clients. And unless you have a full-time security expert on your staff, you probably did it wrong, and its not nearly as secure as you think it is. It&#8217;s also vulnerable to man-in-the-middle attacks and replay attacks, unless you use SSL. And if you <strong>do</strong> use SSL, then you&#8217;ve thrown away one of the major advantages of HTTP, which is caching. Just about every HTTP server and proxy are able to handle caching, and if they operate to spec, they&#8217;re not allowed to cache SSL documents. I&#8217;ll get more into caching in a future blog post, just realize that it can be immensely beneficial to the performance of your application, and you&#8217;re going to want to do everything you can to facilitate that.</p>

<p>Luckily, you have a third option: HTTP Digest Authentication. Its been vetted by security professionals and time, and is almost certainly more secure than some secret key you&#8217;ve come up with. There are many varieties of Digest auth. The one most useful for RESTful web services uses an algorithm of &#8220;MD5-sess&#8221; and Quality of Protextion (qop) of &#8220;auth&#8221;. The MD5-sess algorithm allows for 3rd-party authentication services, and not requiring the server to maintain a plaintext copy of the users&#8217; passwords. A qop of &#8220;auth&#8221; protects against chosen-plaintext cryptanalysis attacks, by having a counter incremented by the client, and a client-generated nonce. For a quick overview, Wikipedia has a <a href="http://en.wikipedia.org/wiki/Digest_access_authentication">good article</a>, and be sure to check out the spec, <a href="http://www.ietf.org/rfc/rfc2617.txt">RFC2617</a>. Here&#8217;s a simple example to see whats going on. Client requests are denoted by <code>&gt;</code>, with server responses <code>&lt;</code>. This obviously isn&#8217;t the whole content, just the interesting bits.</p>

<div class="CodeRay">
  <div class="code"><pre>&gt; GET /

&lt; HTTP/1.1 401 Authorization Required
&lt; WWW-Authenticate: Digest 
                    qop=&quot;auth&quot;, 
                    realm=&quot;My RESTful Application&quot;, 
                    opaque=&quot;55dd3242dd79740cefb67528b983bc8e&quot;, 
                    algorithm=MD5-sess, 
                    nonce=&quot;MjAwOS0wNy0xOSAyMDozMToyOToxODQ2NjA6MjAxZjRiMjVjZjRiYTc0MDEwNWIwY2U2NWIxMGNjNj&quot;

&gt; GET /
&gt; Authorization: Digest 
                 username=&quot;admin&quot;, 
                 qop=&quot;auth&quot;, 
                 realm=&quot;My RESTful Application&quot;, 
                 algorithm=&quot;MD5-sess&quot;,
                 opaque=&quot;55dd3242dd79740cefb67528b983bc8e&quot;, 
                 nonce=&quot;MjAwOS0wNy0xOSAyMDozMToyOToxODQ2NjA6MjAxZjRiMjVjZjRiYTc0MDEwNWIwY2U2NWIxMGNjNj&quot;, 
                 uri=&quot;/&quot;, 
                 nc=00000001, 
                 cnonce=&quot;Mjg5MDIz&quot;, 
                 response=&quot;1b8e5cdcd8d49ca65e3d6142567e44cf&quot;

&lt; HTTP/1.1 200 OK
&lt; Authentication-Info: qop=auth, 
                       nc=00000001, 
                       cnonce=&quot;Mjg5MDIz&quot;, 
                       nextnonce=00000002</pre></div>
</div>


<p>Digest auth works when the client make an initial request without any authentication info. The server responds with a 401, and provides a few parameters to the client in the <code>WWW-Authenticate</code> header. The <code>realm</code> is a string used to identify the application. The client uses MD5 to hash together their <code>username</code>, the <code>realm</code> and their <code>password</code>. This is referred to as <code>HA1</code>. When the user was created, the server did the same, and <code>HA1</code> is what is stored in the database.</p>

<p>The client then generates a random string (the &#8220;client nonce&#8221; or <code>cnonce</code>) and increments a counter (&#8220;nonce counter&#8221; <code>nc</code>). It hashes method as an uppercase string (&#8220;GET&#8221;) and the URI (&#8221;/&#8221;) together to produce <code>HA2</code>. Finally, it hashes <code>HA1</code>, <code>HA2</code>, the <code>nonce</code>, <code>nc</code>, <code>cnonce</code>, and <code>qop</code> all together to arrive at <code>response</code>. It packages this all up into the <code>Authorization</code> header, and makes the request again. The server has all the information it needs (it stored the <code>HA1</code> instead of the plaintext password) to hash the same parameters itself. If it arrives at the same <code>response</code>, then it knows the client knows the password for the user, and allows it to proceed.</p>

<p>Optionally, the server can provide an <code>Authentication-Info</code> header attached to the response. This provides enough information for the client to automatically authenticate for the next request, without having to get a 401 again. An alternative would be to just keep using the same <code>nonce</code> over and over, but this may be subject to replay attacks. The downside of this, though, is that the client cannot pipeline requests.</p>

<h2>Don&#8217;t put the API version in the URI</h2>

<p>Several web services (including Tracker&#8217;s) have uris that look like <code>http://myapp.com/v1/projects</code> or <code>http://myapp.com/projects?v=2</code>. While this is perfectly RESTful, it seems a bit odd. From a pedantically REST-view, <code>/v1/projects/1234</code> and <code>/v2/projects/1234</code> are the locations of totally different resources, when, in fact, they are simply different <strong>representations</strong> of the same resource. From a more practical standpoint, say a client is written when only version one of a service is available, and it stores (&#8220;bookmarks&#8221;) some of these resources. Some time later, the application team decides they need to release some incompatible changes to their API, so they increment the version. Some time after that, the client upgrades to support the new version. However, the upgrade is not as clean as it might be, because they still have the saved locations pointing to the old version. The client either needs to support <em>both</em> versions, or write a tool that does, so it can migrate the url to their new locations. They could munge the urls, but if one of the incompatible changes was going from integer ids to UUIDs, they have no choice.</p>

<p>Luckily, HTTP has a built-in solution to this problem: Content Negotiation. It makes use of two headers, <code>Accept</code> on the client side, and <code>Content-Type</code> on the server side. The Tracker services serve everything back with a <code>Content-Type</code> of <code>application/xml</code>. Its not just any old XML, however, it is a specific form of XML, the schema of which is described in their API docs. This is the situation for which the use of mimetypes is intended. If every form of image out there just used a mime-type of <code>image</code>, we&#8217;d have a much harder time of things. Luckily, there&#8217;s more than that, with <code>image/gif</code>, <code>image/png</code>, and <code>image/jpeg</code>, which all represent different encodings of images. Following the same idea, Tracker could instead use something like <code>application/vnd.pivotal.tracker.v1+xml</code>. Yes, its still XML, but its Pivotal Tracker Version 1 flavor of XML. Then when Pivotal decides its time for incompatible changes, they only have to add an additional content type, <code>application/vnd.pivotal.tracker.v2+xml</code>.</p>

<p>Following this idea, now a project always lives at <code>/projects/1234</code>. This is better, because while <code>v1</code> and <code>v2</code> of a project probably aren&#8217;t different, their representations are. When a client updates versions, their links don&#8217;t break, nor do they have to support two or more versions.</p>

<p>I&#8217;ve only just brushed the surface of this topic. For more, <a href="http://barelyenough.org">Peter Williams</a> has an excellent discussion of it <a href="http://barelyenough.org/blog/2008/05/versioning-rest-web-services/">here</a>, <a href="http://barelyenough.org/blog/2008/05/versioning-rest-web-services-tricks-and-tips/">here</a>, and <a href="http://barelyenough.org/blog/2008/05/resthttp-service-versioning-reponse-to-jean-jacques-dubray/">here</a>. (disclaimer &emdash; Peter is a former coworker and personal friend. This section and his posts are about a solution we came up with for a project.)</p>

<h1>Now You Don&#8217;t Have Any Excuses</h1>

<p>I hope that this post serves as a good description of why you shouldn&#8217;t be designing web services the way every body else does. It seems that everyone is just copying everyone else, without really understanding the pros and cons of the implementations. I hope this sparks some discussion, because I don&#8217;t know that these are even the best way to be doing it, I just know from the experience of writing both applications and consumers, they way everyone is doing it now is much more difficult than it needs to be.</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/your-web-service-might-not-be-restful-if">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/your-web-service-might-not-be-restful-if#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/your-web-service-might-not-be-restful-if</feedburner:origLink></item>
    <item>
      <pubDate>Mon, 30 Mar 2009 12:33:33 -0700</pubDate>
      <title>Writing DataMapper Adapters - A Tutorial</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/fzAfTJt1lTw/writing-datamapper-adapters-a-tutorial</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/writing-datamapper-adapters-a-tutorial</guid>
      <description>
        <![CDATA[<p>
	<h2>Introduction</h2>

<p>The adapter API for DataMapper has been in a bit of flux recently. When I submitted my proposal for a <a href="http://mwrc2009.confreaks.com/14-mar-2009-16-10-writing-adapters-for-datamapper-paul-sadauskas.html">talk at MountainWest</a>, adapters were irritatingly complex to write. You just needed to know too much about DataMapper&#8217;s internals to be able to write one. A week before the conference began, I started a significant effort to re-write the API to make it easier. I succeeded, a little too well; my 30 minute talk only took 15. Since then, I&#8217;ve written a couple more adapters from scratch, and refined the API further. This post will serve as notes on the changes that I&#8217;ve made, and a tutorial on writing adapters.</p>

<p>The API changes are currently only in my branch, but they will be merged into the <a href="http://www.github.com/datamapper/dm-core/tree/next">DataMapper/next</a> branch. For now, you&#8217;ll need to use my <a href="http://www.github.com/paul/dm-core/tree/adapters_1.0">adapters_1.0</a> branch.</p>

<p>This tutorial will follow my process as I make a DataMapper adapter for <a href="http://tokyocabinet.sourceforge.net/index.html">TokyoTyrant</a>. You can grab the code from my github repo, <a href="http://www.github.com/paul/dm-tokyotyrant-adapter">paul/dm-tokyotyrant-adapter</a>.</p>

<h2>Setup</h2>

<p>I&#8217;ll assume you know how to build a gem, and get it all set up using your favorite gem builder, so I&#8217;m going to skip all that. To begin, we only need a couple files. First (of course!), the spec:</p>

<h3>spec/dm-tokyotyrant-adapter_spec.rb</h3>

<div class="CodeRay">
  <div class="code"><pre>require File.dirname(__FILE__) + '/spec_helper'

require 'dm-core/spec/adapter_shared_spec'

describe DataMapper::Adapters::TokyoTyrantAdapter do
  before :all do
    @adapter = DataMapper.setup(:default, :adapter   =&gt; 'tokyo_tyrant',
                                          :hostname  =&gt; 'localhost',
                                          :port      =&gt; 1978)
  end

  it_should_behave_like 'An Adapter'

end</pre></div>
</div>


<p>And thats all there is to it. We make an <code>@adapter</code> instance var, which gets returned from <code>DataMapper.setup</code>, and then run the adapter shared spec. As of now, the shared spec is fairly thorough, but its far from comprehensive. If we run this now, we&#8217;ll get some errors about not finding the <code>TokyoTyrantAdapter</code>. So, lets go make it.</p>

<h2>Initialization</h2>

<h3>lib/dm-tokyotyrant-adapter.rb</h3>

<div class="CodeRay">
  <div class="code"><pre>require 'dm-core'
require 'dm-core/adapters/abstract_adapter'       # 1

require 'tokyotyrant'

module DataMapper::Adapters

  class TokyoTyrantAdapter &lt; AbstractAdapter      # 2
    include TokyoTyrant

    def initialize(name, options)
      super                                       # 3

      @options[:hostname] ||= 'localhost'         # 4
      @options[:port]     ||= 1978

      @db = RDB::new                              
    end
  end

end</pre></div>
</div>


<p>Some of this is pretty TokyoTyrant-specific. Since the Ruby API isn&#8217;t very Rubyish, I&#8217;m going to skip over a lot of it, and just talk about the DataMapper/adapter specific stuff. Referencing the comments in the code above:</p>

<ol>
<li><code>require</code> the abstract adapter explicitly, since its not <code>require</code>&#8216;d as part of requiring dm-core.</li>

<li>Make a class that follows the naming convention <code>#{AdapterName}Adapter</code> so that DataMapper can find it when we use the <code>:adapter =&gt; &#39;adapter_name&#39;</code> option. Inherit from AbstractAdapter as well, as it will provide us with many helpers we&#8217;ll be using.</li>

<li>Make an <code>initialize</code> method, and call super. This will turn any provided options into a Mash (a Hash that can use a string and a symbol as the same key. It handles a little other setup for you, as well.</li>

<li>The rest is Tyrant-specific, but useful to know. We set some default connection options, and initialze a <code>@db</code> object.</li>
</ol>

<p>If we run the spec now, it connects, and we get a bunch of pending specs, saying we need to implment <code>#read</code>, <code>#create</code>, etc&#8230;</p>

<div class="CodeRay">
  <div class="code"><pre>dm-tokyotyrant-adapter/master % rake spec
(in /home/rando/dev/dm-tokyotyrant-adapter)
*****

Pending:

DataMapper::Adapters::TokyoTyrantAdapter needs to support #create (Not Yet Implemented)
/usr/lib/ruby/gems/1.8/gems/dm-core-0.10.0/lib/dm-core/spec/adapter_shared_spec.rb:52

DataMapper::Adapters::TokyoTyrantAdapter needs to support #read (Not Yet Implemented)
/usr/lib/ruby/gems/1.8/gems/dm-core-0.10.0/lib/dm-core/spec/adapter_shared_spec.rb:75

DataMapper::Adapters::TokyoTyrantAdapter needs to support #update (Not Yet Implemented)
/usr/lib/ruby/gems/1.8/gems/dm-core-0.10.0/lib/dm-core/spec/adapter_shared_spec.rb:107

DataMapper::Adapters::TokyoTyrantAdapter needs to support #delete (Not Yet Implemented)
/usr/lib/ruby/gems/1.8/gems/dm-core-0.10.0/lib/dm-core/spec/adapter_shared_spec.rb:129

DataMapper::Adapters::TokyoTyrantAdapter needs to support #read and #create to test query matching (Not Yet Implemented)
/usr/lib/ruby/gems/1.8/gems/dm-core-0.10.0/lib/dm-core/spec/adapter_shared_spec.rb:289

Finished in 0.005982 seconds

5 examples, 0 failures, 5 pending</pre></div>
</div>


<h2>Create</h2>

<div class="CodeRay">
  <div class="code"><pre>def create(resources)                                     # 1
  db do |db|                                              # 2
    resources.each do |resource|                          # 3
      initialize_identity_field(resource, rand(2**32))    # 4
      save(db, key(resource), serialize(resource))        # 5
    end
  end
end</pre></div>
</div>


<ol>
<li><code>resources</code> is an Array of DataMapper Resource objects.</li>

<li><code>#db</code> is a helper to make TokyoTyrant&#8217;s api a little more friendly. It handles connecting to the ttserver, and yields the connection to the block. When finished, it closes the connetion.</li>

<li>Some adapters might be able to support bulk creates, like SQL INSERT. This one doesn&#8217;t, so we&#8217;ll loop over every resource.</li>

<li>We&#8217;ll need to set the identity field. More on this later.</li>

<li>Put the resource into the database. <code>#key</code> and <code>#serialize</code> are helpers, I&#8217;ll explain them in a bit.</li>
</ol>

<p>Something useful to note here: The resources being passed in to this method are the actual resources in use by DataMapper. That means that any modifications you make to them will also be automatically availble to anything using DataMapper. This is extremely useful for any data store that can provide a representation of the created object. If the data store set some fields as a result of creation, eg, a <code>created_at</code> timestamp, or an <code>href</code> linking to the location of the resource, you can update the resource right here, and not have to have DataMapper perform a <code>#read</code> to update the resource object.</p>

<p>If you&#8217;re coming from an RDBMS world, you&#8217;ll be familiar with sequences. Since you&#8217;re here, learning how to write adapters, I&#8217;m going to assume you&#8217;re not going to be talking to a relational database. If thats the case, and you don&#8217;t need to support these kinds of sequences, you should probably use UUIDs or something similar for your identity fields. Sequences are not scalable or distributable, they&#8217;re a relic of the big RDBMSs. I only have this <code>#initialize_identity_field</code> line in there to show how its done. As you can see, I&#8217;m not even picking it sequentially, but choosing a random number, instead, because I don&#8217;t have a resonable way to keep track of sequences. The method won&#8217;t try to overwrite a value if one is already set, so take the opportunity to use a UUID instead, and save everyone involved a bunch of trouble.%lt;/soapbox&gt;</p>

<p>Because TokyoCabinet &amp; Tyrant are key-value stores, I&#8217;ve written a couple helpers to try and coerce resources into a single key and value. First, I choose a key from the model name, and keys in the model, like so:</p>

<div class="CodeRay">
  <div class="code"><pre>def key(resource)
  model = resource.model
  key = resource.key.join('/')
  &quot;#{model}/#{key}&quot;
end</pre></div>
</div>


<p>We get the model, and the keys from the resource. One thing to keep in mind, is that DataMapper assumes composite keys for every model, so even if a model has only a single key, <code>Resource#keys</code> will always return an array. We use that to build a string, like <code>Article/1234</code>. I chose a slash as the delimiter, because TokyoTyrant has a ReSTful interface, and it will make for pretty urls.</p>

<p>We also need to serialze the resource. I chose to serialize it as JSON, because its cross-platform, and lightweight. YAML or even XML would also be ok choices, depending on what you may be interoperating with.</p>

<div class="CodeRay">
  <div class="code"><pre>def serialize(resource)
  resource.attributes(:field).to_json
end</pre></div>
</div>


<p><code>resource#attributes</code> normally returns a Hash of <code>{:property_name =&gt; value}</code> pairs. DataMapper properties also can take an option, <code>:field</code>, which is used to indicate the name of the field used by the data store. Because we&#8217;re writing an adapter to a data-store, thats what we want. <code>#attributes</code> can take an optional argument to indicate what we want to use as keys. Here, I used <code>:field</code>, meaning I want the field attribute of the property. It will then return a Hash of the form <code>{&quot;field_name&quot; =&gt; value}</code> There usually won&#8217;t be a difference, but its important that adapters use the field instead of the name, so that someone writing a model can use the <code>:field</code> option to property correctly.</p>

<p>Let&#8217;s run the spec again, and see how we did:</p>

<div class="CodeRay">
  <div class="code"><pre>dm-tokyotyrant-adapter/master % rake spec
(in /home/rando/dev/dm-tokyotyrant-adapter)
/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/gempackagetask.rb:13:Warning: Gem::manage_gems is deprecated and will be removed on or after March 2009.
****..

Finished in 0.009957 seconds

6 examples, 0 failures, 4 pending</pre></div>
</div>


<h2>Read</h2>

<div class="CodeRay">
  <div class="code"><pre>def read(query)
  model = query.model

  db do |db|
    keys = db.fwmkeys(model.to_s)
    records = []
    keys.each do |key|
      value = db.get(key)
      records &lt;&lt; deserialize(value) if value
    end
    filter_records(records, query)
  end
end</pre></div>
</div>


<p><code>#read</code> takes a DataMapper::Query object, which has everything needed to filter, sort, and limit records. For simple adapters, that don&#8217;t have a native query language, you don&#8217;t need to care. The <code>#filter_records</code> helper in AbstractAdapter will take care of everything for you. All you need to do it provide it an Array of Hashes, using the <code>field</code> name of the property as the key. Since we use json to serialize the value, here we deserialize it back into a hash. We used field names as the keys, so no further translation is needed. TokyoTyrant provides the <code>#fwmkeys</code> method as a way to search for a key prefix, so we pass the model name in, because the model name is the first part of the key we used. We pass all the records we found in to <code>#filter_records</code>, which performs the filtering, and we then return the result.</p>

<h2>Update</h2>

<div class="CodeRay">
  <div class="code"><pre>def update(attributes, collection)                                 # 1
  attributes = attributes_as_fields(attributes)                    # 2
  db do |db|
    collection.each do |resource|                                  # 3
      attributes = resource.attributes(:field).merge(attributes)   # 4
      save(db, key(resource), serialize(resource))                 # 5
    end
  end
end</pre></div>
</div>


<ol>
<li>We take an <code>attributes</code> hash and a DataMapper::Collection. The <code>attributes</code> are in the form of <code>{Property =&gt; value}</code>, using the actual property object. A <code>Collection</code> is a set of resources.</li>

<li>We need to convert the keys in the <code>attributes</code> has from <code>Property</code> objects into <code>:field</code> name. Luckily, AbstractAdapter provides <code>#attributes_as_fields</code>, which does exactly that.</li>

<li>Iterate over every resource in the collection</li>

<li>Update the attributes hash with the combination of the existing attributes, merged with the attributes we wish to update.</li>

<li>Write the whole thing back to the database.</li>
</ol>

<p>You may also want to take a look at how the <a href="http://github.com/paul/dm-core/blob/27a0277c8b00aa9d5be67a25a4113c437e4a6b34/lib/dm-core/adapters/in_memory_adapter.rb">InMemoryAdapter in dm-core</a> accomplishes the same task. It extracts the query used to build the collection, and looks for those records in its data store, using <code>#filter_records</code>. It then updates each record in-place. Either way works fine, and the ease of which may depend upon the adapter. In TokyoTyrant, finding the records is harder than retrieving them, so I opted to just re-save the ones I already had in the collection. An SQL adapter is able to update the records without loading them, so using the query is faster. ( &#8220;UPDATE {attributes} WHERE {query}&#8221; ).</p>

<h2>Delete</h2>

<div class="CodeRay">
  <div class="code"><pre>def delete(collection)
  db do |db|
    collection.each do |resource|
      db.delete(key(resource))
    end
  end
end</pre></div>
</div>


<p>At this point, it should all be self-explainatory. Just iterate over every resource in the colleciton, and delete its key from the db. Yay.</p>

<h2>Conclusion</h2>

<p>And thats all there is to it. 3 hours, 2 beers, and ~100 LOC later, and we have a fully-capable adapter that can be used with DataMapper. I was running the specs at every stage, but left them out for brevity. Here&#8217;s the final run:</p>

<div class="CodeRay">
  <div class="code"><pre>dm-tokyotyrant-adapter/master % rake spec
(in /home/rando/dev/dm-tokyotyrant-adapter)
......................................

Finished in 0.175668 seconds

38 examples, 0 failures</pre></div>
</div>


<p>As I said before, the specs aren&#8217;t exactly comprehensive, but they will be added to over the next few weeks. For now, they&#8217;re good enough that you can be pretty confident your adapter will work for most things.</p>

<p>Thanks for tuning in, leave a comment, or come visit me in #datamapper on freenode if you have any adapter questions.</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/writing-datamapper-adapters-a-tutorial">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/writing-datamapper-adapters-a-tutorial#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/writing-datamapper-adapters-a-tutorial</feedburner:origLink></item>
    <item>
      <pubDate>Mon, 23 Mar 2009 23:44:50 -0700</pubDate>
      <title>I spoke at Mountain West!</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/8RK94ZOWLWI/i-spoke-at-mountain-west</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/i-spoke-at-mountain-west</guid>
      <description>
        <![CDATA[<p>
	<p>Confreaks posted my talk. Everyone go make fun of that huge nerd up there!</p>
<embed allowfullscreen="true" src="http://mwrc2009.confreaks.com/player.swf" allowscriptaccess="always" height="296" flashvars="image=images%2F14-mar-2009-16-10-writing-adapters-for-datamapper-paul-sadauskas-preview.jpg&amp;file=http%3A%2F%2Fmwrc2009.confreaks.com%2Fvideos%2F14-mar-2009-16-10-writing-adapters-for-datamapper-paul-sadauskas-small.mp4&amp;plugins=viral-1" width="500" />
<p>I pushed some of the changes I talked about to my <a href="http://github.com/paul/dm-core/tree/conditions">github branch</a>. This covers the Conditions objects.</p>

<p>Next on my personal roadmap for adapters one-point-oh edition are for Repository to handle turning the responses from adapters into Resource objects, if they aren&#8217;t already.</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/i-spoke-at-mountain-west">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/i-spoke-at-mountain-west#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/i-spoke-at-mountain-west</feedburner:origLink></item>
    <item>
      <pubDate>Wed, 11 Mar 2009 10:45:41 -0700</pubDate>
      <title>DataMapper Echo Adapter</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/KNOik5puQHU/datamapper-echo-adapter</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/datamapper-echo-adapter</guid>
      <description>
        <![CDATA[<p>
	<p>I just wrote a simple adapter that can be used to investigate the DM Adapter API, and debug your own adapter. Its really simple to use:</p>

<div class="CodeRay">
  <div class="code"><pre>DataMapper.setup(:default, 
                 :adapter =&gt; :echo, 
                 :echo =&gt; {:adapter =&gt; :in_memory})</pre></div>
</div>


<p>Set the <code>:echo</code> option to and options hash or connection uri that can initialize the adapter you want to wrap. This will print out the method calls, arguments, and return values to STDOUT.</p>

<div class="CodeRay">
  <div class="code"><pre>#read
query: #&lt;DataMapper::Query @repository=:default 
                           @model=Article 
                           @fields=[#&lt;DataMapper::Property @model=Article @name=:id&gt;, 
                                    #&lt;DataMapper::Property @model=Article @name=:title&gt;] 
                           @links=[] @conditions=[] @order=[] @limit=nil @offset=0 
                           @reload=false @unique=false&gt;
 # =&gt; [#&lt;Article @id=1 @title=&quot;Test&quot; @text=&lt;not loaded&gt;&gt;]</pre></div>
</div>


<p><a href="http://github.com/paul/dm-echo-adapter/tree/master">Its on github</a> <a href="http://gist.github.com/77614">Example output</a></p>
	
</p>

<p><a href="http://blog.theamazingrando.com/datamapper-echo-adapter">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/datamapper-echo-adapter#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/datamapper-echo-adapter</feedburner:origLink></item>
    <item>
      <pubDate>Mon, 02 Mar 2009 11:36:50 -0800</pubDate>
      <title>A Response to "Database Versioning"</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/XkAOwAlbqGw/a-response-to-database-versioning</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/a-response-to-database-versioning</guid>
      <description>
        <![CDATA[<p>
	<p>I was just going to post a comment in reply to <a href="http://adam.blog.heroku.com/past/2009/3/2/database_versioning/">Adam Wiggins&#8217;s Database Versioning post</a>, but it ended up being pretty long, so I&#8217;ll post a response here instead.</p>

<p>I&#8217;m the original author and current maintainer of the migrations plugin for datamapper. I spent a lot of time <a href="http://www.theamazingrando.com/blog/?p=11">thinking about AR migrations</a> before I started writing it. I think that DM migrations have solved a few of the problems he has with AR migrations.</p>

<p>The part about screwing up a migration, and having to re-run it sounds more like a tooling problem. When I write a migration, I drop/create the db, and re-run all the migrations to &#8216;test&#8217; it. (Also, the <a href="http://www.theamazingrando.com/blog/?p=21">DM migration specs</a> should help with this.) Yeah, it blows away all your development data, but you should have fixtures or scripts or something to make it easy to recreate.</p>

<p>There are also long-term plans for a plugin in datamapper to inspect the current database schema, examine the definitions in the models, then &#8220;infer&#8221; the migration that needs to take place. It will be impossible, of course, to guess at what kind of data migration might be needed, but I believe that migrations shouldn&#8217;t touch data. If, given your fullname =&gt; firstname, lastname example, I add the new columns, and run a rake task to handle the data. After a few days/weeks, when I&#8217;m sure that every production server has been upgraded, and that task run, I&#8217;ll write a migration to drop the fullname column.</p>

<p>I do agree that having the database schema living in two different places if very non-dry, but even his suggestion of a schema.yml would duplicate the column definitions that are present in datamapper models.So</p>

<p>I&#8217;ve used these DM migrations in 2 projects now that have been in production for &gt;6 months, and it fits in very well with my workflow. I tend to break up the migration files by table, so I end up with <code>schema/people.rb</code>, <code>schema/articles.rb</code>, <code>schema/comments.rb</code>, with each of those being a table in the db. Then inside one of the files, I list the migrations in version order: <code>1, :create_people_table</code>, <code>2, :add_firstname_lastname</code>, <code>3, :remove_fullname</code>. This lets me see at a glance what version I&#8217;m on for a particular table, and I don&#8217;t have to worry about dependencies. If I do need to modify several tables at once, I have a simple rake task that tells me what the maximum version number is, so I can make one after it.</p>

<p>I think that tryring to use SHAs as version numbers would be even more annoying than epoch timestamps as versions. I do like the idea about the model/application requiring a specific version, and refusing to start otherwise. From a DataMapper POV, it would be easy to add a <code>#requires_db_version(5)</code> method to the model. I&#8217;m already in the habit of not using my models in migrations, by virtue of never writing data migrations. I even just usually write the migrations in raw SQL, it gives me more control over the table stucture when I really care.</p>

<p>So, essentially, DataMapper already provides the solution that Adam outlines in his post; Replace schema.yml with DataMapper model definitions, and have the discipline to not write data migrations. Write specs for your migrations, like everything else, and use DM migrations&#8217; sane versioning, rather than AR&#8217;s irritating one, and you should be fine. There are definitely improvements to be made with DM migrations, to be sure, but I feel like I got the underlying design mostly right.</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/a-response-to-database-versioning">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/a-response-to-database-versioning#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/a-response-to-database-versioning</feedburner:origLink></item>
    <item>
      <pubDate>Sat, 07 Feb 2009 15:58:49 -0800</pubDate>
      <title>I'm speaking at Boulder Ruby Group in 2 weeks</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/AGa5TTYSA6U/im-speaking-at-boulder-ruby-group-in-2-weeks</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/im-speaking-at-boulder-ruby-group-in-2-weeks</guid>
      <description>
        <![CDATA[<p>
	<p>I&#8217;m going to be giving a practice run of the talk I&#8217;ll be giving at <a href="http://mtnwestrubyconf.org/2009/">MountainWest</a> at the <a href="http://boulderruby.org/meetings/2009/01/05/february-2009/">Boulder Ruby Group</a> meeting next Wednesday (18th, 7pm). Come see it and <del>tell me what I'm doing wrong</del> give me some constructive criticism.</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/im-speaking-at-boulder-ruby-group-in-2-weeks">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/im-speaking-at-boulder-ruby-group-in-2-weeks#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/im-speaking-at-boulder-ruby-group-in-2-weeks</feedburner:origLink></item>
    <item>
      <pubDate>Wed, 04 Feb 2009 09:25:38 -0800</pubDate>
      <title>HOWTO - Get a list of a class's subclasses</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/oNo6Y381CAQ/howto-get-a-list-of-a-classs-subclasses</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/howto-get-a-list-of-a-classs-subclasses</guid>
      <description>
        <![CDATA[<p>
	<p>I recently came across a situation where I had an AbstractClass, an I wanted to know all of the classes that had inherited from it. There were lots of implementations on the web, but that weren&#8217;t exactly what I wanted, or they used ObjectSpace to get ALL the classes, and see if the interesting one was in its ancestors.</p>

<p>I only needed it one-level deep, but it would be fairly easy to extend it for more.</p>

<div class="CodeRay">
  <div class="code"><pre>class ParentClass
  def self.subclasses
    @subclasses ||= Set.new
  end

  def self.inherited(subclass)
    subclasses &lt;&lt; subclass
  end
end

class ChildA &lt; ParentClass; end
class ChildB &lt; ParentClass; end

ParentClass.subclasses
# =&gt; #&lt;Set: {ChildA, ChildB}&gt;</pre></div>
</div>
	
</p>

<p><a href="http://blog.theamazingrando.com/howto-get-a-list-of-a-classs-subclasses">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/howto-get-a-list-of-a-classs-subclasses#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/howto-get-a-list-of-a-classs-subclasses</feedburner:origLink></item>
    <item>
      <pubDate>Mon, 19 Jan 2009 11:11:30 -0800</pubDate>
      <title>I'm Speaking at MountainWest!</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/SgxeAfmg4bc/im-speaking-at-mountainwest</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/im-speaking-at-mountainwest</guid>
      <description>
        <![CDATA[<p>
	<p>I&#8217;m going to be giving a talk at <a href="http://mtnwestrubyconf.org/2009/speakers">Mountain West Ruby Conf</a>!</p>

<p>For those of you too lazy to scroll down and find the details of my talk, I&#8217;ll repeat them here:</p>

<blockquote class="posterous_medium_quote">
<p>Some might think of DataMapper as a better, faster, competitor to ActiveRecord. However, they would be missing on of its greatest strengths. At its core, DataMapper provides a uniform interface on top of ANY persistance layer. All thats needed is a simple adapter class that can translate the native persitance into a simple 4-method API for DataMapper to consume. This talk will cover that API, and some best-practices on implementing an adapter. We will explore the YAML Adapter, which I will be writing for the purposes of this talk.</p>
</blockquote>

<p>Wish me luck!</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/im-speaking-at-mountainwest">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/im-speaking-at-mountainwest#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/im-speaking-at-mountainwest</feedburner:origLink></item>
    <item>
      <pubDate>Mon, 19 Jan 2009 10:07:42 -0800</pubDate>
      <title>Ruby Dir.glob bug</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/IzfyECoua9U/ruby-dirglob-bug</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/ruby-dirglob-bug</guid>
      <description>
        <![CDATA[<p>
	<p>To further elaborate on Yehuda&#8217;s <a href="http://twitter.com/wycats/status/1124457823">twit</a>:</p>

<div class="CodeRay">
  <div class="code"><pre>[~/tmp][rando@apollo]
 % mkdir first first/second
[~/tmp][rando@apollo]
 % touch first/second/test.txt
[~/tmp][rando@apollo]
 % chmod -x first
[~/tmp][rando@apollo]
 % ls first/second/*.txt
ls: cannot access first/second/*.txt: Permission denied
[~/tmp][rando@apollo]
 % irb
irb(main):001:0&gt; Dir.glob('first/second/*.txt')
=&gt; []</pre></div>
</div>


<p>If you try to glob some things in a directory that has some ancestor missing the eXecute permission, ruby doesn&#8217;t give any indication of an error.</p>

<p>This took Yehuda and I about 30 minutes to track down why a merb app wasn&#8217;t loading bundled gems under passenger. Apache was running as nobody, and the parent dir of the app was missing the global execute permission.</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/ruby-dirglob-bug">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/ruby-dirglob-bug#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/ruby-dirglob-bug</feedburner:origLink></item>
    <item>
      <pubDate>Wed, 07 Jan 2009 17:15:19 -0800</pubDate>
      <title>Wildfires in Boulder</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/Dtr6CZydxRU/wildfires-in-boulder-0</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/wildfires-in-boulder-0</guid>
      <description>
        <![CDATA[<p>
	<p>Here&#8217;s the view out my kitchen window, most mornings:<br /> <a href="http://picasaweb.google.com/lh/photo/if5JeHUe16PKKCpjWYj44g?feat=embedwebsite"><img src="http://lh6.ggpht.com/_WEBSr9gkXQM/RPsquxnPABI/AAAAAAAAACQ/dbaIpaY55MU/s400/IMG_0096.JPG" /></a></p>

<p>Here&#8217;s what it looks like this fine evening:</p>
<table style=""><tr><td><a href="http://picasaweb.google.com/lh/photo/EVVxym2W0cCXxa3ZSbaGTQ?feat=embedwebsite"><img src="http://lh5.ggpht.com/_WEBSr9gkXQM/SWVQJ4kMFEI/AAAAAAAAEKQ/uKQOKm2LqxM/s400/img_0317.jpg" /></a></td></tr><tr><td style="font-family: arial,sans-serif; font-size: 11px; text-align: right;">From <a href="http://picasaweb.google.com/psadauskas/Fire?feat=embedwebsite">fire</a></td></tr></table>
<p>Click the album link for more. From my porch, I can see parts of the mountainside flashing from the lights of the fire trucks. They&#8217;ve evacuated 11,000 homes, but the wind is blowing the fire the other direction. There have been clouds of smoke all afternoon, but once the sun set, I has able to see the flames.</p>

<p>More details about the fires here: <a href="http://www.dailycamera.com/news/2009/jan/07/i-70-closed-over-vail-pass-avalanche-control/">http://www.dailycamera.com/news/2009/jan/07/i-70-closed-over-vail-pass-avalanche-control/</a></p>
	
</p>

<p><a href="http://blog.theamazingrando.com/wildfires-in-boulder-0">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/wildfires-in-boulder-0#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/wildfires-in-boulder-0</feedburner:origLink></item>
    <item>
      <pubDate>Sat, 15 Nov 2008 19:45:05 -0800</pubDate>
      <title>I boughted a car!</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/AIBxf8bNZfY/i-boughted-a-car-0</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/i-boughted-a-car-0</guid>
      <description>
        <![CDATA[<p>
	<p>Mazda3 5-door. Its pretty:</p>
<a href="http://www.theamazingrando.com/blog/wp-content/uploads/2008/11/cp1_1115081208.jpg"><img class="alignnone size-medium wp-image-65" title="The car" src="http://www.theamazingrando.com/blog/wp-content/uploads/2008/11/cp1_1115081208.jpg" height="157" alt="" width="300" /></a><a href="http://www.theamazingrando.com/blog/wp-content/uploads/2008/11/cp1_1115081245a.jpg"><img class="alignnone size-medium wp-image-66" title="Sexy (Not me, the car)" src="http://www.theamazingrando.com/blog/wp-content/uploads/2008/11/cp1_1115081245a.jpg" height="152" alt="" width="300" /></a>
	
</p>

<p><a href="http://blog.theamazingrando.com/i-boughted-a-car-0">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/i-boughted-a-car-0#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/i-boughted-a-car-0</feedburner:origLink></item>
    <item>
      <pubDate>Sun, 12 Oct 2008 21:00:56 -0700</pubDate>
      <title>Merbcamp</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/ILdlViQxeTU/merbcamp-0</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/merbcamp-0</guid>
      <description>
        <![CDATA[<p>
	<p>Here&#8217;s my own personal store of interesting crap I picked up in merbcamp. I&#8217;ll add to this as the talks go on.</p>

<ul>
<li>carllerche is a pretty cool guy for adding useful stuff to the merb router for me</li>

<li>mauth is pretty sweet</li>

<li>When can I get a 4K tv in my living room?</li>

<li><a href="http://blog.fiveruns.com/2008/10/11/fiveruns-tuneup-for-merb">FiveRuns tuneup for merb</a></li>

<li><a href="http://github.com/brynary/webrat/tree/master">webrat</a> looks to make acceptance specs/stories actually useable</li>

<li>Ruby Language book by Matz is a good read for learning the internals of Ruby</li>
</ul>
	
</p>

<p><a href="http://blog.theamazingrando.com/merbcamp-0">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/merbcamp-0#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/merbcamp-0</feedburner:origLink></item>
    <item>
      <pubDate>Sun, 12 Oct 2008 20:36:47 -0700</pubDate>
      <title>DataMapper 0.9.6 released</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/aYxgINQd4EE/datamapper-096-released-0</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/datamapper-096-released-0</guid>
      <description>
        <![CDATA[<p>
	<p>I just pushed 0.9.6 of dm-core, dm-more and data_objects up to rubyforge, as well as 0.9.8 of extlib. There&#8217;s several bugfixes that were applied in the runup to merbcamp. This is also preparing for the imminent release of merb 1.0RC1.</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/datamapper-096-released-0">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/datamapper-096-released-0#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/datamapper-096-released-0</feedburner:origLink></item>
    <item>
      <pubDate>Thu, 09 Oct 2008 12:43:55 -0700</pubDate>
      <title>HOWTO: Better JSON parsing when POSTing to Merb Apps</title>
      <link>http://feedproxy.google.com/~r/theamazingrando/~3/tgrTAxQkzRU/howto-better-json-parsing-when-posting-to-mer-0</link>
      <guid isPermaLink="false">http://blog.theamazingrando.com/howto-better-json-parsing-when-posting-to-mer-0</guid>
      <description>
        <![CDATA[<p>
	<p>Where I work, we have fairly extensive, JSON-based web services in all out applications. As a quick example, here&#8217;s what you would get if you were to <code>GET</code> <code>http://config.ssbe.example.com/configurations/90</code> with the mime-type <code>application/vnd.absperf.sscj1+json</code>:</p>

<div class="CodeRay">
  <div class="code"><pre>{
  &quot;_type&quot;:                      &quot;Configuration&quot;,
  &quot;href&quot;:                       &quot;http://config.ssbe.localhost/configurations/90&quot;,
  &quot;id&quot;:                         &quot;4c5895f2-28a3-4299-a558-270889e6f065&quot;,
  &quot;name&quot;:                       &quot;lacquered&quot;,
  &quot;notes&quot;:                      &quot;Hosted hundredfold broomstick&quot;,
  &quot;platform&quot;:                   &quot;AIX&quot;,
  &quot;client_href&quot;:                &quot;http://core.ssbe.localhost/clients/jousting&quot;,
  &quot;registered_templates_href&quot;:  &quot;http://config.ssbe.localhost/configurations/90/registered_templates&quot;,
  &quot;parent_configuration_href&quot;:  &quot;http://config.ssbe.localhost/configurations/90&quot;,
  &quot;created_at&quot;:                 &quot;2008-10-07T16:38:29-06:00&quot;,
  &quot;updated_at&quot;:                 &quot;2008-10-08T15:20:51-06:00&quot;
}</pre></div>
</div>


<p>I&#8217;m planning on a bigger post about exactly what our JSON document means, and our mime-types, and everything. For now, a good explaination of the reasoning behind our mime-types can be found <a href="http://barelyenough.org/blog/2008/05/versioning-rest-web-services/">over on Peter&#8217;s blog</a>.</p>

<p>That aside, now that I&#8217;ve <code>GET</code>ed this document, I&#8217;d love to be able to just string-manipulate the one or two things I want to modify, and just <code>PUT</code> it back where I got it, in the same format, with all the same attributes. The problem with that, though, is that several of these attributes are determined server-side, such as <code>_type</code>, <code>href</code>, and <code>id</code>. These values a set by the server, and a few of them aren&#8217;t even properties on the model. I could throw an error back when someone tries to submit a value for an unchangeable attribute, but then I wouldn&#8217;t be able to <code>POST</code> the identical document that I just <code>GET</code>ed. I&#8217;d have to know a fair amount about the document to know which attributes I have to remove from the document before I can give it back. I&#8217;d much prefer the server just ignore it. Now, I could throw an error if someone tries to <em>change</em> one of these attributes, but I&#8217;ll save that for later. In any event, right now, I just want my controller to parse the JSON, and let it ignore the attributes I don&#8217;t care about.</p>

<p>To that end, I implemented a custom JSON parser in a before filter in my Application controller:</p>

<div class="CodeRay">
  <div class="code"><pre>class Application &lt; Merb::Controller
  before :parse_supplied_sscj1, :if =&gt; :has_sscj1_content         #[1]

  def has_sscj1_content
    request.content_type == 'application/vnd.absperf.sscj1+json'  #[2]
  end

  def parse_supplied_sscj1
    begin 
      jobj = JSON.parse(request.raw_post)                         #[3]
      raise UnprocessableEntity unless jobj.is_a?(Hash)           #[4]

      model_class = jobj[&quot;_type&quot;].snake_case                      #[5]

      params[model_class] = jobj
    rescue JSON::ParserError =&gt; e
      raise BadRequest.new(e.message)                             #[6]
    end
  end
end</pre></div>
</div>


<p>A brief description of what all this means:</p>

<ol>
<li>Set up the before filter to do the parsing, but only under the right conditions.</li>

<li>Those conditions are merely if somebody set the <code>Content-Type</code> header on the request to my <code>sscj1</code> mime-type.</li>

<li>JSON parse the body of the request. Request#raw_post is how you get to the raw data that was <code>POST</code>ed (and <code>PUT</code>, too)</li>

<li>I expect every JSON document i get to be parsed into a Hash object, so throw a standard HTTP error if its not.</li>

<li>Because I have the <code>_type</code> attribute in my document, I can use that to put the parsed attributes in the right place. From the example above, I end up with <code>params = {&quot;configuration&quot; =&gt; {&quot;name&quot; =&gt; &quot;lacquered&quot;, ...}, ...}</code></li>

<li>Oh, and if we got an invalid (unparseable) JSON document, raise a 400 Bad Request error.</li>
</ol>

<p>So that takes care of the JSON parsing. Its a little better than the one built-in to merb, because of the error handling, and putting the attributes into a useable place in the form. Now, what do we do about the attributes we want to ignore? I added a couple class methods to Controller for handling that.</p>

<div class="CodeRay">
  <div class="code"><pre>class Application &lt; Merb::Controller
  class &lt;&lt; self
    attr_accessor :attributes_to_ignore

    def ignore_attributes(*attrs)
      @attributes_to_ignore = attrs
    end

  end

  def attributes_to_ignore
    %w[_type href id created_at updated_at] + self.class.attributes_to_ignore
  end

end

class Configurations &lt; Application
  provides :sscj1

  ignore_attributes 'registered_templates_href'

  # ...
end</pre></div>
</div>


<p>This is all pretty simple. Essentially, I just added a <code>#ignore_attributes</code> class method to my controllers, so I can provide a list of attributes to be ignored, specific to each controller. The <code>#attributes_to_ignore</code> method lists the default ones, and in this case, I want my configurations to ignore <code>registered_templates_href</code> in addition to those. Now I can just delete those from the parsed JSON object in my <code>#parse_supplied_sscj1</code> method:</p>

<div class="CodeRay">
  <div class="code"><pre>attributes_to_ignore.each do |key|
    jobj.delete(key)
  end</pre></div>
</div>


<p>Simple!</p>

<p>Now, I have that pesky <code>parent_configuration_href</code> attribute still coming in. I dont want to ignore it, but I do need a <code>parent_id</code> attribute in my configuration model, representing a self-referential join. To do that, I&#8217;d love to be able to run the given uri through merb&#8217;s router and parse out the <code>id</code>, but unfortunetly, thats not part of the public API (yet). I&#8217;ll just have to write my own simple regex parser to pull it out, and have a nice clever way to set that in my Configurations controller. So on to the code:</p>

<div class="CodeRay">
  <div class="code"><pre>class Application &lt; Merb::Controller
  class &lt;&lt; self
    attr_accessor :attributes_to_alter
    def alter_attribute(attribute, &amp;block)
      @attributes_to_alter ||= {}
      @attributes_to_alter[attribute] = block
    end
  end
  def attributes_to_alter
    Merb.logger.info self.class.attributes_to_alter.inspect
    self.class.attributes_to_alter || {}
  end

end

class Configurations &lt; Application
  provides :sscj1

  alter_attribute 'parent_configuration_href' do |_,uri|
    {'parent_id' =&gt; extract_configuration_id(uri)}
  end

  def self.extract_configuration_id(uri)
    return nil unless uri
    %r{/configurations/(\d+)}.match(uri)
    $1
  end

end</pre></div>
</div>


<p>So, here we have something similar to the <code>#ignore_attributes</code>, except now we have a block to be called on the attribute we want to change. In this case, I match the <code>configurations</code> part of the URI, and capture the <code>id</code>. Then , in my <code>#parse_supplied_sscj1</code> method, I replace the old value with the new one:</p>

<div class="CodeRay">
  <div class="code"><pre>def parse_supplied_sscj1
  begin 
    jobj = JSON.parse(request.raw_post)
    raise UnprocessableEntity unless jobj.is_a?(Hash)

    model_class = jobj[&quot;_type&quot;].snake_case

    attributes_to_ignore.each do |key|
      jobj.delete(key)
    end

    attributes_to_alter.each do |attribute, block|
      new_attrs = block.call(attribute, jobj.delete(attribute))
      jobj.merge!(new_attrs)
    end

    params[model_class] = jobj
  rescue JSON::ParserError =&gt; e
    raise BadRequest.new(e.message)
  end
end</pre></div>
</div>


<p>Thats the entire method that I&#8217;m using right now. I hope to package this all up as a merb plugin soon, keep and eye on my github, and I&#8217;ll probably post something about it here, soon.</p>
	
</p>

<p><a href="http://blog.theamazingrando.com/howto-better-json-parsing-when-posting-to-mer-0">Permalink</a> 

	| <a href="http://blog.theamazingrando.com/howto-better-json-parsing-when-posting-to-mer-0#comment">Leave a comment&nbsp;&nbsp;&raquo;</a>

</p>]]>
      </description>
      <posterous:author>
        <posterous:userImage>http://files.posterous.com/user_profile_pics/619240/me.jpg</posterous:userImage>
        <posterous:profileUrl>http://posterous.com/users/3sIQeAeZgiKB</posterous:profileUrl>
        <posterous:firstName>Paul</posterous:firstName>
        <posterous:lastName>Sadauskas</posterous:lastName>
        <posterous:nickName>Paul</posterous:nickName>
        <posterous:displayName>Paul Sadauskas</posterous:displayName>
      </posterous:author>
    <feedburner:origLink>http://blog.theamazingrando.com/howto-better-json-parsing-when-posting-to-mer-0</feedburner:origLink></item>
  </channel>
</rss>

