<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	>

<channel>
	<title>The Amazing Blog</title>
	<atom:link href="http://www.theamazingrando.com/blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.theamazingrando.com/blog</link>
	<description>Rando's Random Ramblings</description>
	<pubDate>Thu, 01 Jul 2010 03:46:05 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Moving!</title>
		<link>http://www.theamazingrando.com/blog/?p=112</link>
		<comments>http://www.theamazingrando.com/blog/?p=112#comments</comments>
		<pubDate>Wed, 30 Jun 2010 23:19:04 +0000</pubDate>
		<dc:creator>Paul Sadauskas</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[Meta]]></category>

		<guid isPermaLink="false">http://www.theamazingrando.com/blog/?p=112</guid>
		<description><![CDATA[I&#8217;m tired of updating wordpress every 3 weeks for security failures, so I&#8217;m moving this blog over to posterous, so its their problem now. Please update your links and RSS feeds to http://blog.theamazingrando.com. I imported all the posts from here to a github repo, http://github.com/paul/blog.theamazingrando.com. I plan to write a blog post on how I [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m tired of updating wordpress every 3 weeks for security failures, so I&#8217;m moving this blog over to posterous, so its their problem now. Please update your links and RSS feeds to <a href="http://blog.theamazingrando.com">http://blog.theamazingrando.com</a>. I imported all the posts from here to a github repo, <a href="http://github.com/paul/blog.theamazingrando.com" onclick="javascript:pageTracker._trackPageview ('/outbound/github.com');">http://github.com/paul/blog.theamazingrando.com</a>. I plan to write a blog post on how I exported all the posts with markdown and html from wordpress into the repo and Posterous in the next couple days, so stay tuned.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.theamazingrando.com/blog/?feed=rss2&amp;p=112</wfw:commentRss>
		</item>
		<item>
		<title>Your Web Service Might Not Be RESTful If&#8230;</title>
		<link>http://www.theamazingrando.com/blog/?p=107</link>
		<comments>http://www.theamazingrando.com/blog/?p=107#comments</comments>
		<pubDate>Mon, 20 Jul 2009 04:11:45 +0000</pubDate>
		<dc:creator>Paul Sadauskas</dc:creator>
		
		<category><![CDATA[Web Services]]></category>

		<category><![CDATA[http rest]]></category>

		<guid isPermaLink="false">http://www.theamazingrando.com/blog/?p=107</guid>
		<description><![CDATA[The other day, I gave a brief talk about our HTTP Library, Resourceful. 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 [...]]]></description>
			<content:encoded><![CDATA[<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 &#8212; 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, &#8220;<a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">Representational State Transfer (REST)</a>&#8220;.</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>
  <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>

<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&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;
</code></pre>

<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>
  <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>

<pre><code>    &lt;?xml version="1.0" encoding="UTF-8"?&gt;
    &lt;projects type="array"&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="integer"&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;
</code></pre>

<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>

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

<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, [RFC2617]. 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>

<pre><code>&gt; GET /

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

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

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

<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 (&#8221;nonce counter&#8221; <code>nc</code>).
It hashes method as an uppercase string (&#8221;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 (&#8221;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>
]]></content:encoded>
			<wfw:commentRss>http://www.theamazingrando.com/blog/?feed=rss2&amp;p=107</wfw:commentRss>
		</item>
		<item>
		<title>Writing DataMapper Adapters - A Tutorial</title>
		<link>http://www.theamazingrando.com/blog/?p=95</link>
		<comments>http://www.theamazingrando.com/blog/?p=95#comments</comments>
		<pubDate>Mon, 30 Mar 2009 21:33:33 +0000</pubDate>
		<dc:creator>Paul Sadauskas</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.theamazingrando.com/blog/?p=95</guid>
		<description><![CDATA[Introduction

The adapter API for DataMapper has been in a bit of flux recently. When I submitted
my proposal for a talk at MountainWest, 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 [...]]]></description>
			<content:encoded><![CDATA[<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>

<pre><code>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
</code></pre>

<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>

<pre><code>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
</code></pre>

<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; 'adapter_name'</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>

<pre><code>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
</code></pre>

<h2>Create</h2>

<pre><code>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
</code></pre>

<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></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>

<pre><code>def key(resource)
  model = resource.model
  key = resource.key.join('/')
  "#{model}/#{key}"
end
</code></pre>

<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>

<pre><code>def serialize(resource)
  resource.attributes(:field).to_json
end
</code></pre>

<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>{"field_name" =&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>

<pre><code>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
</code></pre>

<h2>Read</h2>

<pre><code>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
</code></pre>

<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>

<pre><code>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
</code></pre>

<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>

<pre><code>def delete(collection)
  db do |db|
    collection.each do |resource|
      db.delete(key(resource))
    end
  end
end
</code></pre>

<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>

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

Finished in 0.175668 seconds

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

<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>
]]></content:encoded>
			<wfw:commentRss>http://www.theamazingrando.com/blog/?feed=rss2&amp;p=95</wfw:commentRss>
		</item>
		<item>
		<title>I spoke at Mountain West!</title>
		<link>http://www.theamazingrando.com/blog/?p=93</link>
		<comments>http://www.theamazingrando.com/blog/?p=93#comments</comments>
		<pubDate>Tue, 24 Mar 2009 01:44:50 +0000</pubDate>
		<dc:creator>Paul Sadauskas</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.theamazingrando.com/blog/?p=93</guid>
		<description><![CDATA[Confreaks posted my talk. Everyone go make fun of that huge nerd up there!



I pushed some of the changes I talked about to my github branch. This covers the Conditions objects.

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 [...]]]></description>
			<content:encoded><![CDATA[<p>Confreaks posted my talk. Everyone go make fun of that huge nerd up there!</p>

<p><embed src='http://mwrc2009.confreaks.com/player.swf' height='380' width='640' allowscriptaccess='always' allowfullscreen='true' flashvars='image=images%2F14-mar-2009-16-10-writing-adapters-for-datamapper-paul-sadauskas-preview.jpg&#038;file=http%3A%2F%2Fmwrc2009.confreaks.com%2Fvideos%2F14-mar-2009-16-10-writing-adapters-for-datamapper-paul-sadauskas-small.mp4&#038;plugins=viral-1'/></p>

<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>
]]></content:encoded>
			<wfw:commentRss>http://www.theamazingrando.com/blog/?feed=rss2&amp;p=93</wfw:commentRss>
		</item>
		<item>
		<title>DataMapper Echo Adapter</title>
		<link>http://www.theamazingrando.com/blog/?p=91</link>
		<comments>http://www.theamazingrando.com/blog/?p=91#comments</comments>
		<pubDate>Wed, 11 Mar 2009 19:45:41 +0000</pubDate>
		<dc:creator>Paul Sadauskas</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.theamazingrando.com/blog/?p=91</guid>
		<description><![CDATA[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:

DataMapper.setup(:default, 
                 :adapter =&#62; :echo, 
         [...]]]></description>
			<content:encoded><![CDATA[<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>

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

<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>

<pre><code>#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="Test" @text=&lt;not loaded&gt;&gt;]
</code></pre>

<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>
]]></content:encoded>
			<wfw:commentRss>http://www.theamazingrando.com/blog/?feed=rss2&amp;p=91</wfw:commentRss>
		</item>
		<item>
		<title>A Response to &#8220;Database Versioning&#8221;</title>
		<link>http://www.theamazingrando.com/blog/?p=86</link>
		<comments>http://www.theamazingrando.com/blog/?p=86#comments</comments>
		<pubDate>Mon, 02 Mar 2009 19:36:50 +0000</pubDate>
		<dc:creator>Paul Sadauskas</dc:creator>
		
		<category><![CDATA[Datamapper]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[Migrations]]></category>

		<guid isPermaLink="false">http://www.theamazingrando.com/blog/?p=86</guid>
		<description><![CDATA[I was just going to post a comment in reply to Adam Wiggins&#8217;s Database Versioning post, but it ended up being pretty long, so I&#8217;ll post a response here instead.

I&#8217;m the original author and current maintainer of the migrations plugin for datamapper. I spent a lot of time thinking about AR migrations before I started [...]]]></description>
			<content:encoded><![CDATA[<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 => 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 >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>
]]></content:encoded>
			<wfw:commentRss>http://www.theamazingrando.com/blog/?feed=rss2&amp;p=86</wfw:commentRss>
		</item>
		<item>
		<title>I&#8217;m speaking at Boulder Ruby Group in 2 weeks</title>
		<link>http://www.theamazingrando.com/blog/?p=84</link>
		<comments>http://www.theamazingrando.com/blog/?p=84#comments</comments>
		<pubDate>Sat, 07 Feb 2009 23:58:49 +0000</pubDate>
		<dc:creator>Paul Sadauskas</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.theamazingrando.com/blog/?p=84</guid>
		<description><![CDATA[I&#8217;m going to be giving a practice run of the talk I&#8217;ll be giving at MountainWest at the Boulder Ruby Group meeting next Wednesday (18th, 7pm). Come see it and tell me what I&#8217;m doing wrong give me some constructive criticism.
]]></description>
			<content:encoded><![CDATA[<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&#8217;m doing wrong</del> give me some constructive criticism.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.theamazingrando.com/blog/?feed=rss2&amp;p=84</wfw:commentRss>
		</item>
		<item>
		<title>HOWTO - Get a list of a class&#8217;s subclasses</title>
		<link>http://www.theamazingrando.com/blog/?p=82</link>
		<comments>http://www.theamazingrando.com/blog/?p=82#comments</comments>
		<pubDate>Wed, 04 Feb 2009 17:25:38 +0000</pubDate>
		<dc:creator>Paul Sadauskas</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.theamazingrando.com/blog/?p=82</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<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>

<pre><code>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;
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.theamazingrando.com/blog/?feed=rss2&amp;p=82</wfw:commentRss>
		</item>
		<item>
		<title>I&#8217;m Speaking at MountainWest!</title>
		<link>http://www.theamazingrando.com/blog/?p=80</link>
		<comments>http://www.theamazingrando.com/blog/?p=80#comments</comments>
		<pubDate>Mon, 19 Jan 2009 19:11:30 +0000</pubDate>
		<dc:creator>Paul Sadauskas</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.theamazingrando.com/blog/?p=80</guid>
		<description><![CDATA[I&#8217;m going to be giving a talk at Mountain West Ruby Conf!

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


  Some might think of DataMapper as a better, faster, competitor to ActiveRecord. However, they would be missing on of its greatest strengths. At [...]]]></description>
			<content:encoded><![CDATA[<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>
  <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>
]]></content:encoded>
			<wfw:commentRss>http://www.theamazingrando.com/blog/?feed=rss2&amp;p=80</wfw:commentRss>
		</item>
		<item>
		<title>Ruby Dir.glob bug</title>
		<link>http://www.theamazingrando.com/blog/?p=77</link>
		<comments>http://www.theamazingrando.com/blog/?p=77#comments</comments>
		<pubDate>Mon, 19 Jan 2009 18:07:42 +0000</pubDate>
		<dc:creator>Paul Sadauskas</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.theamazingrando.com/blog/?p=77</guid>
		<description><![CDATA[To further elaborate on Yehuda&#8217;s twit:

[~/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&#62; Dir.glob('first/second/*.txt')
=&#62; []


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.

This took [...]]]></description>
			<content:encoded><![CDATA[<p>To further elaborate on Yehuda&#8217;s <a href="http://twitter.com/wycats/status/1124457823">twit</a>:</p>

<pre><code>[~/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; []
</code></pre>

<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>
]]></content:encoded>
			<wfw:commentRss>http://www.theamazingrando.com/blog/?feed=rss2&amp;p=77</wfw:commentRss>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.800 seconds -->
<!-- Cached page served by WP-Cache -->
