<?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/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Push cx &#187; Ruby</title>
	<atom:link href="http://push.cx/tag/ruby/feed" rel="self" type="application/rss+xml" />
	<link>http://push.cx</link>
	<description>A traveling geek&#039;s blog on development, games, and the web</description>
	<lastBuildDate>Fri, 14 Oct 2011 10:24:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Rewriting My Competitors</title>
		<link>http://push.cx/2011/rewriting-my-competitors</link>
		<comments>http://push.cx/2011/rewriting-my-competitors#comments</comments>
		<pubDate>Sat, 09 Jul 2011 10:48:23 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Allabrilyn]]></category>
		<category><![CDATA[code smells]]></category>
		<category><![CDATA[Fantasy Adventure]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[sessions]]></category>
		<category><![CDATA[so play we all]]></category>

		<guid isPermaLink="false">http://push.cx/?p=1811</guid>
		<description><![CDATA[It&#8217;s really clear that the polls So Play We All are measuring progress. When we have a quiet week, there&#8217;s a lot fewer votes. This week, there were 4, evenly split between Luke and I. The SPWA site doesn&#8217;t have code to handle ties so it highligted me as winning, which I guess means the [...]]]></description>
			<content:encoded><![CDATA[<p>
  It&#8217;s really clear that the polls <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NvcGxheXdlYWxsLmNvbQ==">So Play We All</a> are measuring progress. When we have a quiet week, there&#8217;s a lot fewer votes. This week, there were 4, evenly split between Luke and I. The SPWA site doesn&#8217;t have code to handle ties so it highligted me as winning, which I guess means the bugfix is not <em>my</em> problem. :)
</p>

<p>
  Luke <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Jsb2cuZmFudGFzeWFkdmVudHVyZWdhbWUuY29tLzIwMTEvMDcvMDYvYS1zcHJpbmctYnViYmxlcy11cC8=">laid down code</a> for cards. I know I&#8217;m helping the enemy, but I&#8217;ve got to tweak it. His code is:
</p>

<pre>&nbsp;
class CardController &lt; ApplicationController
  def play
    play_sym = <span style="color: #ff0000;">"play_#{@card}"</span>.<span style="">intern</span> <span style="color: #808080; font-style: italic;"># PH: this should be .to_sym</span>
    self.<span style="">send</span><span style="color: #66cc66;">&#40;</span>play_sym<span style="color: #66cc66;">&#41;</span>
    render :action =&gt; play_sym <span style="color: #b1b100;">and</span> <span style="color: #000066;">return</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  def pocket
    pocket_sym = <span style="color: #ff0000;">"pocket_#{@card}"</span>.<span style="">intern</span>
    self.<span style="">send</span><span style="color: #66cc66;">&#40;</span>pocket_sym<span style="color: #66cc66;">&#41;</span>
  <span style="color: #b1b100;">end</span> <span style="color: #808080; font-style: italic;"># PH: no explicit render here? Feels like a paste error</span>
&nbsp;
  protected
&nbsp;
  <span style="color: #808080; font-style: italic;"># plays</span>
  def play_roland
    <span style="color: #808080; font-style: italic;"># Play the game to see what happens when you play the Roland card!</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  def play_water
    <span style="color: #808080; font-style: italic;"># Play the game to see what happens when you play the Water card!</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  <span style="color: #808080; font-style: italic;"># pockets</span>
  def pocket_roland
    <span style="color: #808080; font-style: italic;"># Play the game to see what happens when you pocket the Roland card!</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  def pocket_water
    <span style="color: #808080; font-style: italic;"># Play the game to see what happens when you pocket the Water card!</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
<span style="color: #b1b100;">end</span></pre>

I&#8217;d write this code as:

<pre>&nbsp;
class CardController &lt; ApplicationController
  <span style="color: #808080; font-style: italic;"># I'm guessing from usage above @card is just the name for a card as a string</span>
  <span style="color: #808080; font-style: italic;"># and that it's loaded from the url by a filter, note that I use it differently.</span>
  before_filter :load_card
  after_filter :default_render_card
  
  def play
    <span style="color: #0000ff;">@card</span>.<span style="">play</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  def pocket
    <span style="color: #0000ff;">@card</span>.<span style="">pocket</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  protected
&nbsp;
  def load_card
    <span style="color: #0000ff;">@name</span> = params<span style="color: #66cc66;">&#91;</span>:card<span style="color: #66cc66;">&#93;</span>
    <span style="color: #0000ff;">@card</span> = <span style="color: #ff0000;">"card/#{@name}"</span>.<span style="">camelize</span>.<span style="">constantize</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  def default_render_card
    render :template =&gt; <span style="color: #ff0000;">"cards/#{request.action}/#{@name}"</span> <span style="color: #b1b100;">unless</span> performed?
  <span style="color: #b1b100;">end</span>
end
&nbsp;
<span style="color: #808080; font-style: italic;"># add in config/application.rb:</span>
module Oaqn
  class Application &lt; Rails::<span style="color: #006600;">Application</span>
    config.<span style="">autoload_paths</span> += <span style="color: #0000ff;">%W</span><span style="color: #66cc66;">&#40;</span><span style="color: #808080; font-style: italic;">#{config.root}/app/cards)</span>
  <span style="color: #b1b100;">end</span>
end
&nbsp;
<span style="color: #808080; font-style: italic;"># and then create app/cards/roland.rb:</span>
module Card
  module Roland
    def pocket
      <span style="color: #808080; font-style: italic;"># code for pocketing</span>
    <span style="color: #b1b100;">end</span>
&nbsp;
    def play
      <span style="color: #808080; font-style: italic;"># code for playing</span>
    <span style="color: #b1b100;">end</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
  So now the cards each get a source file to themselves, templates have their own per-action dirs (better swapped to per-card dirs, if there are more actions), there&#8217;s less duplicated code, and it&#8217;s far easier to test these smaller pieces. The only thing missing from this example is the fact that Luke may have to pass some game state into the methods. As long as there&#8217;s not too much it&#8217;s probably worth being explicit about.
</p>

<p class="update">
2011-07-09: Luke actually used this code and found it didn&#8217;t work as written. I found <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3F1ZXN0aW9ucy80MDc0ODMwL2FkZGluZy1saWItdG8tY29uZmlnLWF1dG9sb2FkLXBhdGhzLWkNCm4tcmFpbHMtMy1kb2VzLW5vdC1hdXRvbG9hZC1teS1tb2R1bGU=">an explanation</a>; either add &#8216;app&#8217; to <kbd>autoload_paths</kbd> instead of &#8216;app/cards&#8217;, or drop the Card wrapper.
</p>

<p>
  Meanwhile, in the past, Jim <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Jsb2cuYWxsYWJyaWx5bi5jb20vY29udGVudC9jbGFzcy1zZXNzaW9u">wrote some PHP</a>, and I&#8217;m not touching that language.
</p>

<p>
  No, in seriousness, Jim talked about why he has some identifiers surrounded by __ (which I&#8217;d called <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAxMS9zbWFsbC1zdGVwcw==">python poisoning</a>). I haven&#8217;t dug into his code (again, PHP), but it looks like it might be an <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2MyLmNvbS9jZ2kvd2lraT9JbkJhbmRTaWduYWw=">InBandSignal</a> to reuse Events as framework steps.
</p>

<p>
  And then he talks about session fixation attacks, which are have been protected against out-of-the-box on PHP with the <kbd>session.use_only_cookies</kbd> setting for a while. I was a bit confused, I&#8217;m pretty sure he&#8217;s actually describing session capture attacks. Oh, and there was some other stuff about writing code to store sessions in the database. If you&#8217;re curious, Jim, here&#8217;s the code for a Rails app to do that, which appears commented-out in the stock config file for your editing convenience:
</p>

<pre>&nbsp;
  Oaqn::<span style="color: #006600;">Application</span>.<span style="">config</span>.<span style="">session_store</span> :active_record_store</pre>

<p>
  It includes support out of the box for keeping sessions in cookies (encrypted, of course), your SQL database via ActiveRecord, or Memcached. I&#8217;m curious, how much of your budget did you spend storing sessions?
</p>
 <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1811" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2011/rewriting-my-competitors/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>From Fixtures to Factories</title>
		<link>http://push.cx/2010/from-fixtures-to-factories</link>
		<comments>http://push.cx/2010/from-fixtures-to-factories#comments</comments>
		<pubDate>Tue, 06 Jul 2010 19:33:02 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[factories]]></category>
		<category><![CDATA[factory_girl]]></category>
		<category><![CDATA[fixtures]]></category>
		<category><![CDATA[Mocha]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://push.cx/?p=1428</guid>
		<description><![CDATA[Automated tests need example data, and it&#8217;s a pain to have to construct a complete object in every test, especially when there are a lot of non-optional fields. The standard improvement is to use fixtures, a file with some example data, that your tests can load by giving the name of a fixture. Here&#8217;s one [...]]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=L3RhZy90ZXN0aW5n">Automated tests</a> need example data, and it&#8217;s a pain to have to construct a complete object in every test, especially when there are a lot of non-optional fields.
</p>

<p>
The standard improvement is to use fixtures, a file with some example data,
that your tests can load by giving the name of a fixture. Here&#8217;s one of the
fixtures for a <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20=">gamer</a>:
</p>

<pre>
alice: # alice is heavily involved
  id: 1
  mail: alice@example.com
  handle: alice
  password: red queen
  teaser: Follow the white rabbit.
  profile: Not so plain, after all.
  homepage: http://www.example.com
  jabber: alice@example.org
  location_id: 3
  last_login: 2006-10-30 11:56:08
  created_at: 2006-10-30 11:56:08
  location_at: 2006-10-30 11:56:08
  tag_text: dnd, wod
  mail_on_message: true
  mail_on_nearby_discussion: true
</pre>

<p>
This is straightforward, but <kbd>location_id</kbd> is the id of another fixture in another file. As you can imagine it&#8217;s pretty easy to get them out-of-sync and break some tests. I end up leaving little <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2MyLmNvbS9jZ2kvd2lraT9Ub05lZWRDb21tZW50cw==">comments</a> in the YAML to remind myself of the cross-reference.
</p>

<p>
It&#8217;s awfully tempting to reuse fixtures from test to test. Maybe Alice was written to test logging in with a username and password and next I&#8217;m writing the test of logging in with an email address and a password. I could copy and paste Alice to another fixture to reuse in that test, but as a programmer I have a pathological aversion to copy and paste. Alice is going to get reused (most of those fields are optional and were used by very different tests), and after this happens a few times it&#8217;s hard to change a fixture without breaking an unrelated test.
</p>

<p>
I&#8217;ve gotten a lot of use out of fixtures as I&#8217;ve developed the habit of <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwOS93aHktaS13cml0ZS10ZXN0cw==">testing all my code</a>, but reuse has made my tests somewhat brittle. After a bit of research, I&#8217;ve moved over to using factories.
</p>

<p>
Here&#8217;s the factory for a gamer:
</p>

<pre>&nbsp;
Factory.<span style="">sequence</span> :handle <span style="color: #66cc66;">&#123;</span> |n| <span style="color: #ff0000;">"Gamer_#{n}"</span> <span style="color: #66cc66;">&#125;</span>
&nbsp;
Factory.<span style="">define</span> :gamer <span style="color: #b1b100;">do</span> |g|
  g.<span style="">handle</span> <span style="color: #66cc66;">&#123;</span> Factory.<span style="">next</span> :handle <span style="color: #66cc66;">&#125;</span>
  g.<span style="">mail</span> <span style="color: #66cc66;">&#123;</span> |m| <span style="color: #ff0000;">"#{m.handle}@example.com"</span> <span style="color: #66cc66;">&#125;</span>
  g.<span style="">password</span> <span style="color: #ff0000;">'secret'</span>
<span style="color: #b1b100;">end</span></pre>

<p>
Only the essential, required fields are listed. Using this simple template, the tests themselves specify the values of the fields they&#8217;ll be testing.
</p>

<pre>&nbsp;
def test_login_with_valid_username_and_password
  gamer = Gamer.<span style="">create</span> :handle =&gt; <span style="color: #ff0000;">'Alice'</span>, :password =&gt; <span style="color: #ff0000;">'red queen'</span>
  ...
<span style="color: #b1b100;">end</span>
def test_login_with_valid_email_and_password
  gamer = Gamer.<span style="">create</span> :mail =&gt; <span style="color: #ff0000;">'alice@example.com'</span>, :password =&gt; <span style="color: #ff0000;">'red queen'</span>
  ...
<span style="color: #b1b100;">end</span></pre>

<p>
Ideally, changing a fixture wouldn&#8217;t break any tests at all. And <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2dpdGh1Yi5jb20vdGhvdWdodGJvdC9mYWN0b3J5X2dpcmw=">factory_girl</a> (what I&#8217;m using for factories in Rails) makes associations easy:
</p>

<pre>&nbsp;
Factory.<span style="">define</span> :post <span style="color: #b1b100;">do</span> |p|
  p.<span style="">association</span> :discussion, :factory =&gt; :discussion
  p.<span style="">association</span> :poster, :factory =&gt; :gamer
  p.<span style="">created_at</span> Time.<span style="">now</span>.<span style="">utc</span>
  p.<span style="">body</span> <span style="color: #ff0000;">"Post Body"</span>
<span style="color: #b1b100;">end</span></pre>

<p>
Now my tests include the specific data they care about, making them easier to understand and improve. And they don&#8217;t interrelate, so they&#8217;re much more reliable. I do still use fixtures, but now they&#8217;re exclusively for tests that need to deal with real-world examples.
</p>
 <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1428" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2010/from-fixtures-to-factories/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Small Plans</title>
		<link>http://push.cx/2009/small-plans</link>
		<comments>http://push.cx/2009/small-plans#comments</comments>
		<pubDate>Wed, 11 Feb 2009 19:57:39 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Biz]]></category>
		<category><![CDATA[gems]]></category>
		<category><![CDATA[ListLibrary.net]]></category>
		<category><![CDATA[mailing lists]]></category>
		<category><![CDATA[RailsRumble]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://push.cx/?p=663</guid>
		<description><![CDATA[My last day at the Post is Feb 20, and I&#8217;m headed to Chicago on the 22nd. I&#8217;ll be helping a family member recover from surgery, so my schedule (both day-to-day and how long I&#8217;ll be in town) is pretty vague, but I&#8217;ll be around at least a few weeks before returning to DC. I [...]]]></description>
			<content:encoded><![CDATA[<p>
My <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=LzIwMDkvZ2l2aW5nLW5vdGljZQ==">last day at the Post is Feb 20</a>, and I&#8217;m headed to Chicago on the 22nd. I&#8217;ll be helping a family member recover from surgery, so my schedule (both day-to-day and how long I&#8217;ll be in town) is pretty vague, but I&#8217;ll be around at least a few weeks before returning to DC.
</p>

<p>
I have three smallish website projects I plan to finish in this time. They&#8217;re in various stages of completion now.
</p>

<p>
The first is a mailing list archive. I&#8217;ve been tinkering with it on and off for about 18 months, and it&#8217;s the closest to a finished state. I really enjoy reading mailing lists, but haven&#8217;t been impressed with any of the sites out there. Often each message is its own page and threads are broken up. So I&#8217;ve done a lot of work on threading above and beyond the basic In-Reply-To and Re: matching, and the site is designed to show a thread per-page with lots of keyboard controls to make it easy to skim. Depending on free time this weekend, I may actually launch this before I leave town.
</p>

<p>
Second is a site cataloging Ruby gems. When I was <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=LzIwMDkvcmFpbHMtZm9ydW0tcm91bmR1cA==">searching out Rails forums</a> I realized there&#8217;s a related problem in finding libraries that I could address. I&#8217;ve done the work to collect basic info on gems, it remains to collect news and blog posts and combine it into a nice presentation.
</p>

<p>
The last small project is my <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwOC9yYWlsc3J1bWJsaW5n">RailsRumble</a> project (which I <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwOC9yYWlsc3J1bWJsZS1wb3N0bW9ydGVt">didn&#8217;t finish</a>): a site for collaboratively producing transcripts of conference presentations. I&#8217;ve let this one simmer in the back of my mind in the four months since that failure and I&#8217;ve given it a better name and planned which features to finish, redesign, or drop. It needs a few days of solid development, a graphic design, and some seed content.
</p>

<p>
I plan to finish and launch these three projects by the end of March, and I&#8217;ll post more as I work on them.
</p>

<p>
The commonality in these three projects is that once I&#8217;ve launched them they require minimal ongoing attention from me and can grow at their own paces. I&#8217;m doing them first because small and well-defined projects fit well with the interrupted and distracted time I&#8217;ll have. I&#8217;d also want to make sure I start out with some successes.
</p>

<p>
Next posts: <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=LzIwMDkvbmVhcmJ5Z2FtZXJzLXRvLWRvLWxpc3Q=">NearbyGamers</a> and <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=LzIwMDkvd2ViLWdhbWU=">The Big Project That I Really Need To Name Already</a>.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=663" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2009/small-plans/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Twitter and Ruby&#8217;s Open Classes</title>
		<link>http://push.cx/2009/twitter-and-rubys-open-classes</link>
		<comments>http://push.cx/2009/twitter-and-rubys-open-classes#comments</comments>
		<pubDate>Mon, 12 Jan 2009 13:19:43 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Habber]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[open classes]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Twitter]]></category>

		<guid isPermaLink="false">http://push.cx/?p=416</guid>
		<description><![CDATA[For a few years I&#8217;ve been using weird, funny, outrageous, bizarre, or just offensive quotes as IM status messages. They used to appear at the bottom of this site, but the Jabber bot that fetched them has been offline for a while. I hooked them up to a Twitter account with a short Ruby script, [...]]]></description>
			<content:encoded><![CDATA[<p>
For a few years I&#8217;ve been using weird, funny, outrageous, bizarre, or just offensive quotes as IM status messages. They used to <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvamFiYmVyLXN0YXR1cw==">appear at the bottom</a> of this site, but the Jabber bot that fetched them has been offline for a while. I hooked them up to a <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3R3aXR0ZXIuY29tL2RvdGZvcnR1bmVyYw==">Twitter account</a> with a short Ruby script, and I wanted to talk about it a little.
</p>

<pre>&nbsp;
<span style="color: #808080; font-style: italic;">#!/usr/bin/ruby</span>
&nbsp;
FILE_FORTUNE = <span style="color: #ff0000;">'/path/to/.fortunerc'</span>
FILE_USED = <span style="color: #ff0000;">'/path/to/.used-fortunes'</span>
TWITTER_USERNAME = <span style="color: #ff0000;">'username'</span>
TWITTER_PASSWORD = <span style="color: #ff0000;">'seekrit password'</span>
GAP = <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span> * <span style="color: #cc66cc;">60</span><span style="color: #66cc66;">&#41;</span>..<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">26</span> * <span style="color: #cc66cc;">60</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;"># gap between tweets in minutes:</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># A cron job runs the script every minute with the word 'cron' </span>
<span style="color: #808080; font-style: italic;"># as an argument. It exits immediately unless enough time has passed</span>
<span style="color: #000066;">exit</span> <span style="color: #b1b100;">if</span> ARGV<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span> == <span style="color: #ff0000;">"cron"</span> <span style="color: #b1b100;">and</span> Time.<span style="">now</span> &lt; File.<span style="">mtime</span><span style="color: #66cc66;">&#40;</span>FILE_USED<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #000066;">require</span> <span style="color: #ff0000;">'rubygems'</span>
<span style="color: #000066;">require</span> <span style="color: #ff0000;">'digest/sha1'</span>
<span style="color: #000066;">require</span> <span style="color: #ff0000;">'twitter'</span>
<span style="color: #000066;">require</span> <span style="color: #ff0000;">'yaml'</span>
&nbsp;
&nbsp;
class Array
  def <span style="color: #000066;">rand</span>
    self<span style="color: #66cc66;">&#91;</span>Kernel.<span style="">rand</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066;">length</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span>
  <span style="color: #b1b100;">end</span>
end
&nbsp;
class Range
  def <span style="color: #000066;">rand</span>
    Kernel.<span style="">rand</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">last</span> - first<span style="color: #66cc66;">&#41;</span> + first
  <span style="color: #b1b100;">end</span>
end
&nbsp;
class String
  def sha1
    Digest::<span style="color: #006600;">SHA1</span>.<span style="">hexdigest</span><span style="color: #66cc66;">&#40;</span>self<span style="color: #66cc66;">&#41;</span>
  <span style="color: #b1b100;">end</span>
end
&nbsp;
module YAML
  def self.<span style="">save_file</span> filename, obj
    File.<span style="">open</span><span style="color: #66cc66;">&#40;</span>filename, <span style="color: #ff0000;">'w'</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> |f| f.<span style="">write</span><span style="color: #66cc66;">&#40;</span>obj.<span style="">to_yaml</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#125;</span>
  <span style="color: #b1b100;">end</span>
end
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;"># load fortunes, loop to pick one randomly</span>
fortune = nil
used = YAML::<span style="color: #006600;">load_file</span><span style="color: #66cc66;">&#40;</span>FILE_USED<span style="color: #66cc66;">&#41;</span>
fortunes = <span style="color: #000066;">open</span><span style="color: #66cc66;">&#40;</span>FILE_FORTUNE<span style="color: #66cc66;">&#41;</span>.<span style="">read</span>.<span style="">split</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"<span style="color: #000099; font-weight: bold;">\n</span>%<span style="color: #000099; font-weight: bold;">\n</span>"</span><span style="color: #66cc66;">&#41;</span>
loop <span style="color: #b1b100;">do</span>
  fortune = fortunes.<span style="">rand</span>
  break <span style="color: #b1b100;">if</span> fortune.<span style="">length</span> &lt;= <span style="color: #cc66cc;">140</span> <span style="color: #b1b100;">and</span> !used.<span style="">include</span>? fortune.<span style="">sha1</span>
<span style="color: #b1b100;">end</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># post it to Twitter</span>
Twitter::<span style="color: #006600;">Base</span>.<span style="">new</span><span style="color: #66cc66;">&#40;</span>TWITTER_USERNAME, TWITTER_PASSWORD<span style="color: #66cc66;">&#41;</span>.<span style="">post</span><span style="color: #66cc66;">&#40;</span>fortune<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># save that this fortune was used</span>
used<span style="color: #66cc66;">&#91;</span>fortune.<span style="">sha1</span><span style="color: #66cc66;">&#93;</span> = Time.<span style="">now</span>
YAML::<span style="color: #006600;">save_file</span><span style="color: #66cc66;">&#40;</span>FILE_USED, used<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># set time of next tweet</span>
next_tweet_at = Time.<span style="">now</span> + GAP.<span style="">rand</span> * <span style="color: #cc66cc;">60</span>
File.<span style="">utime</span><span style="color: #66cc66;">&#40;</span>next_tweet_at, next_tweet_at, FILE_USED<span style="color: #66cc66;">&#41;</span></pre>

<p>
A short, single-purpose script like this doesn&#8217;t cry out for seemingly-fancy techniques like adding to builtin classes. But when you get to the core of the script, it&#8217;s obvious. Instead of the noise of a procedural calls for randomness and generating sha1s, the intention is the implementation. The reusable bits of the code are already explicitly extracted, making them easier to reuse.
</p>

<p>
Now that I&#8217;ve been doing this sort of thing in Ruby for a while I keep wishing I could do it in Python. With open classes I can add to the Strings and Arrays that other code returns to mine. I can&#8217;t subclass objects I don&#8217;t instantiate, the best I could do is write a delegating wrapper class.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=416" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2009/twitter-and-rubys-open-classes/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Not A Good Day for Ruby</title>
		<link>http://push.cx/2008/not-a-good-day-for-ruby</link>
		<comments>http://push.cx/2008/not-a-good-day-for-ruby#comments</comments>
		<pubDate>Sun, 22 Jun 2008 23:44:11 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[core dump]]></category>
		<category><![CDATA[crash]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://push.cx/?p=323</guid>
		<description><![CDATA[*** glibc detected *** /usr/bin/ruby: double free or corruption (out): 0x299b2b08 *** ======= Backtrace: ========= /lib/tls/i686/cmov/libc.so.6[0xb7d40d65] /lib/tls/i686/cmov/libc.so.6(cfree+0x90)[0xb7d44800] /usr/lib/libruby1.8.so.1.8[0xb7ed5d79] /usr/lib/libruby1.8.so.1.8(ruby_xmalloc+0x85)[0xb7ed60c5] /usr/lib/libruby1.8.so.1.8(rb_str_buf_new+0x50)[0xb7f25b80] /usr/lib/libruby1.8.so.1.8[0xb7ef157e] /usr/lib/libruby1.8.so.1.8[0xb7eb733a] /usr/lib/libruby1.8.so.1.8[0xb7ebee8e] /usr/lib/libruby1.8.so.1.8[0xb7ebfbc8] /usr/lib/libruby1.8.so.1.8[0xb7ec797e] /usr/lib/libruby1.8.so.1.8[0xb7ec78fc] /usr/lib/libruby1.8.so.1.8[0xb7ebf766] /usr/lib/libruby1.8.so.1.8[0xb7ebfbc8] /usr/lib/libruby1.8.so.1.8[0xb7ec797e] /usr/lib/libruby1.8.so.1.8[0xb7ebf766] /usr/lib/libruby1.8.so.1.8[0xb7ebfbc8] /usr/lib/libruby1.8.so.1.8[0xb7ec797e] /usr/lib/libruby1.8.so.1.8[0xb7ebf766] /usr/lib/libruby1.8.so.1.8[0xb7ebfbc8] /usr/lib/libruby1.8.so.1.8[0xb7ec797e] /usr/lib/libruby1.8.so.1.8[0xb7eca68a] /usr/lib/libruby1.8.so.1.8(rb_yield+0x21)[0xb7ecbad1] /usr/lib/libruby1.8.so.1.8(rb_ary_each+0x31)[0xb7ea41a1] /usr/lib/libruby1.8.so.1.8[0xb7eb7345] /usr/lib/libruby1.8.so.1.8[0xb7ebee8e] /usr/lib/libruby1.8.so.1.8[0xb7ebfbc8] /usr/lib/libruby1.8.so.1.8[0xb7ec797e] /usr/lib/libruby1.8.so.1.8[0xb7ec953d] /usr/lib/libruby1.8.so.1.8[0xb7ec6d64] /usr/lib/libruby1.8.so.1.8[0xb7ebf766] /usr/lib/libruby1.8.so.1.8[0xb7ebfbc8] /usr/lib/libruby1.8.so.1.8[0xb7ec797e] /usr/lib/libruby1.8.so.1.8[0xb7ec8d9f] /usr/lib/libruby1.8.so.1.8[0xb7eca68a] /usr/lib/libruby1.8.so.1.8[0xb7ec771d] /usr/lib/libruby1.8.so.1.8[0xb7ec87d3] /usr/lib/libruby1.8.so.1.8[0xb7ebf766] /usr/lib/libruby1.8.so.1.8[0xb7ebfbc8] /usr/lib/libruby1.8.so.1.8[0xb7ec797e] /usr/lib/libruby1.8.so.1.8[0xb7ec8d9f] [...]]]></description>
			<content:encoded><![CDATA[<pre><blockquote>
*** glibc detected *** /usr/bin/ruby: double free or corruption (out): 0x299b2b08 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6[0xb7d40d65]
/lib/tls/i686/cmov/libc.so.6(cfree+0x90)[0xb7d44800]
/usr/lib/libruby1.8.so.1.8[0xb7ed5d79]
/usr/lib/libruby1.8.so.1.8(ruby_xmalloc+0x85)[0xb7ed60c5]
/usr/lib/libruby1.8.so.1.8(rb_str_buf_new+0x50)[0xb7f25b80]
/usr/lib/libruby1.8.so.1.8[0xb7ef157e]
/usr/lib/libruby1.8.so.1.8[0xb7eb733a]
/usr/lib/libruby1.8.so.1.8[0xb7ebee8e]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec797e]
/usr/lib/libruby1.8.so.1.8[0xb7ec78fc]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec797e]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec797e]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec797e]
/usr/lib/libruby1.8.so.1.8[0xb7eca68a]
/usr/lib/libruby1.8.so.1.8(rb_yield+0x21)[0xb7ecbad1]
/usr/lib/libruby1.8.so.1.8(rb_ary_each+0x31)[0xb7ea41a1]
/usr/lib/libruby1.8.so.1.8[0xb7eb7345]
/usr/lib/libruby1.8.so.1.8[0xb7ebee8e]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec797e]
/usr/lib/libruby1.8.so.1.8[0xb7ec953d]
/usr/lib/libruby1.8.so.1.8[0xb7ec6d64]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec797e]
/usr/lib/libruby1.8.so.1.8[0xb7ec8d9f]
/usr/lib/libruby1.8.so.1.8[0xb7eca68a]
/usr/lib/libruby1.8.so.1.8[0xb7ec771d]
/usr/lib/libruby1.8.so.1.8[0xb7ec87d3]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec797e]
/usr/lib/libruby1.8.so.1.8[0xb7ec8d9f]
/usr/lib/libruby1.8.so.1.8[0xb7eca68a]
/usr/lib/libruby1.8.so.1.8[0xb7ec771d]
/usr/lib/libruby1.8.so.1.8[0xb7ec7d91]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec7aa4]
/usr/lib/libruby1.8.so.1.8[0xb7ec8d9f]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec797e]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec766a]
/usr/lib/libruby1.8.so.1.8[0xb7ec76ce]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec766a]
/usr/lib/libruby1.8.so.1.8[0xb7ec76ce]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
/usr/lib/libruby1.8.so.1.8[0xb7ebfbc8]
/usr/lib/libruby1.8.so.1.8[0xb7ec766a]
/usr/lib/libruby1.8.so.1.8[0xb7ec76ce]
/usr/lib/libruby1.8.so.1.8[0xb7ebf766]
======= Memory map: ========
08048000-08049000 r-xp 00000000 08:03 1704787    /usr/bin/ruby1.8
08049000-0804a000 rw-p 00000000 08:03 1704787    /usr/bin/ruby1.8
0804a000-2af12000 rw-p 0804a000 00:00 0          [heap]
b5f00000-b5f21000 rw-p b5f00000 00:00 0
b5f21000-b6000000 ---p b5f21000 00:00 0
b6055000-b605f000 r-xp 00000000 08:03 1802307    /lib/libgcc_s.so.1
b605f000-b6060000 rw-p 0000a000 08:03 1802307    /lib/libgcc_s.so.1
b6060000-b7626000 rw-p b6060000 00:00 0
b7626000-b765e000 r-xp 00000000 08:03 737293     /usr/lib/ruby/1.8/i486-linux/nkf.so
b765e000-b7661000 rw-p 00037000 08:03 737293     /usr/lib/ruby/1.8/i486-linux/nkf.so
b7661000-b7662000 rw-p b7661000 00:00 0
b7662000-b7675000 r-xp 00000000 08:03 737288     /usr/lib/ruby/1.8/i486-linux/dl.so
b7675000-b7676000 rw-p 00012000 08:03 737288     /usr/lib/ruby/1.8/i486-linux/dl.so
b7676000-b77a1000 r-xp 00000000 08:03 1671348    /usr/lib/i686/cmov/libcrypto.so.0.9.8
b77a1000-b77b6000 rw-p 0012a000 08:03 1671348    /usr/lib/i686/cmov/libcrypto.so.0.9.8
b77b6000-b77b9000 rw-p b77b6000 00:00 0
b77b9000-b77f6000 r-xp 00000000 08:03 1671350    /usr/lib/i686/cmov/libssl.so.0.9.8
b77f6000-b77fa000 rw-p 0003c000 08:03 1671350    /usr/lib/i686/cmov/libssl.so.0.9.8
b7804000-b7807000 r-xp 00000000 08:03 819234     /usr/lib/ruby/1.8/i486-linux/digest/sha1.so
b7807000-b7808000 rw-p 00002000 08:03 819234     /usr/lib/ruby/1.8/i486-linux/digest/sha1.so
b7808000-b780b000 r-xp 00000000 08:03 737287     /usr/lib/ruby/1.8/i486-linux/digest.so
b780b000-b780c000 rw-p 00002000 08:03 737287     /usr/lib/ruby/1.8/i486-linux/digest.so
b780c000-b7842000 r-xp 00000000 08:03 2297548    /usr/lib/ruby/1.8/i486-linux/openssl.so
b7842000-b7844000 rw-p 00035000 08:03 2297548    /usr/lib/ruby/1.8/i486-linux/openssl.so
b7844000-b7a45000 rw-p b7844000 00:00 0
b7a45000-b7a59000 r-xp 00000000 08:03 1640498    /usr/lib/libz.so.1.2.3.3
b7a59000-b7a5a000 rw-p 00013000 08:03 1640498    /usr/lib/libz.so.1.2.3.3
b7a5b000-b7a5c000 rw-p b7a5b000 00:00 0
b7a5c000-b7a60000 r-xp 00000000 08:03 737298     /usr/lib/ruby/1.8/i486-linux/strscan.so
b7a60000-b7a61000 rw-p 00003000 08:03 737298     /usr/lib/ruby/1.8/i486-linux/strscan.so
b7a61000-b7a6b000 r-xp 00000000 08:03 737296     /usr/lib/ruby/1.8/i486-linux/socket.so
b7a6b000-b7a6c000 rw-p 00009000 08:03 737296     /usr/lib/ruby/1.8/i486-linux/socket.so
b7a6c000-b7a74000 r-xp 00000000 08:03 737323     /usr/lib/ruby/1.8/i486-linux/zlib.so
b7a74000-b7a75000 rw-p 00007000 08:03 737323     /usr/lib/ruby/1.8/i486-linux/zlib.so
b7a75000-b7a8f000 r-xp 00000000 08:03 737299     /usr/lib/ruby/1.8/i486-linux/syck.so
b7a8f000-b7a90000 rw-p 0001a000 08:03 737299     /usr/lib/ruby/1.8/i486-linux/syck.so
b7a90000-b7cd7000 rw-p b7a90000 00:00 0
b7cd7000-b7e1b000 r-xp 00000000 08:03 1838871    /lib/tls/i686/cmov/libc-2.6.1.so
b7e1b000-b7e1c000 r--p 00143000 08:03 1838871    /lib/tls/i686/cmov/libc-2.6.1.so
b7e1c000-b7e1e000 rw-p 00144000 08:03 1838871    /lib/tls/i686/cmov/libc-2.6.1.so
b7e1e000-b7e21000 rw-p b7e1e000 00:00 0
b7e21000-b7e44000 r-xp 00000000 08:03 1838875    /lib/tls/i686/cmov/libm-2.6.1.so
b7e44000-b7e46000 rw-p 00023000 08:03 1838875    /lib/tls/i686/cmov/libm-2.6.1.so
b7e46000-b7e4b000 r-xp 00000000 08:03 1838873    /lib/tls/i686/cmov/libcrypt-2.6.1.so
b7e4b000-b7e4d000 rw-p 00004000 08:03 1838873    /lib/tls/i686/cmov/libcrypt-2.6.1.so
b7e4d000-b7e74000 rw-p b7e4d000 00:00 0
b7e74000-b7e76000 r-xp 00000000 08:03 1838874    /lib/tls/i686/cmov/libdl-2.6.1.so
b7e76000-b7e78000 rw-p 00001000 08:03 1838874    /lib/tls/i686/cmov/libdl-2.6.1.so
b7e78000-b7e79000 rw-p b7e78000 00:00 0
b7e79000-b7e8d000 r-xp 00000000 08:03 1838885    /lib/tls/i686/cmov/libpthread-2.6.1.so
b7e8d000-b7e8f000 rw-p 00013000 08:03 1838885    /lib/tls/i686/cmov/libpthread-2.6.1.so
b7e8f000-b7e91000 rw-p b7e8f000 00:00 0
b7e91000-b7f4f000 r-xp 00000000 08:03 1755193    /usr/lib/libruby1.8.so.1.8.6
b7f4f000-b7f52000 rw-p 000bd000 08:03 1755193    /usr/lib/libruby1.8.so.1.8.6
b7f52000-b7f62000 rw-p b7f52000 00:00 0
b7f62000-b7f64000 r-xp 00000000 08:03 819232     /usr/lib/ruby/1.8/i486-linux/digest/md5.so
b7f64000-b7f65000 rw-p 00001000 08:03 819232     /usr/lib/ruby/1.8/i486-linux/digest/md5.so
b7f65000-b7f66000 r-xp 00000000 08:03 737291     /usr/lib/ruby/1.8/i486-linux/fcntl.so
b7f66000-b7f67000 rw-p 00000000 08:03 737291     /usr/lib/ruby/1.8/i486-linux/fcntl.so
b7f67000-b7f6b000 r-xp 00000000 08:03 737297     /usr/lib/ruby/1.8/i486-linux/stringio.so
b7f6b000-b7f6c000 rw-p 00003000 08:03 737297     /usr/lib/ruby/1.8/i486-linux/stringio.so
b7f6c000-b7f6e000 r-xp 00000000 08:03 737290     /usr/lib/ruby/1.8/i486-linux/etc.so
b7f6e000-b7f6f000 rw-p 00001000 08:03 737290     /usr/lib/ruby/1.8/i486-linux/etc.so
b7f6f000-b7f72000 r-xp 00000000 08:03 737301     /usr/lib/ruby/1.8/i486-linux/thread.so
b7f72000-b7f73000 rw-p 00002000 08:03 737301     /usr/lib/ruby/1.8/i486-linux/thread.so
b7f73000-b7f75000 rw-p b7f73000 00:00 0
b7f75000-b7f8f000 r-xp 00000000 08:03 1808831    /lib/ld-2.6.1.so
b7f8f000-b7f91000 rw-p 00019000 08:03 1808831    /lib/ld-2.6.1.so
bfef7000-bff1c000 rw-p bfef7000 00:00 0          [stack]
ffffe000-fffff000 r-xp 00000000 00:00 0          [vdso]
Aborted (core dumped)
</blockquote></pre>

<p>
The output of one of the four crashes I earned from the Ruby interpreter today. It&#8217;s likely the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3J1Ynl6aXAuc291cmNlZm9yZ2UubmV0Lw==">rubyzip</a> library being flaky, but ouch. I&#8217;ve got some long jobs pushing around ~12G (uncompressed) for a project I&#8217;ll show off later this week and it&#8217;s hard to get finished when I have to babysit jobs.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=323" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2008/not-a-good-day-for-ruby/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Caching Dictionaries in Python vs. Ruby</title>
		<link>http://push.cx/2008/caching-dictionaries-in-python-vs-ruby</link>
		<comments>http://push.cx/2008/caching-dictionaries-in-python-vs-ruby#comments</comments>
		<pubDate>Sat, 02 Feb 2008 17:01:52 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[dictionaries]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://push.cx/2008/caching-dictionaries-in-python-vs-ruby</guid>
		<description><![CDATA[A while ago I made a slightly-underinformed post (see the corrections in the comments) trying to draw a difference between Python and Ruby. I&#8217;ve finally got a decent example and can explain what I&#8217;m getting at. I&#8217;m processing all the items in a big list, and part of that is performing some expensive calculation on [...]]]></description>
			<content:encoded><![CDATA[<p>
A while ago I made <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9hbi1hY2FkZW1pYy1pbmNvbnZlbmllbmNlLW9mLXB5dGhvbg==">a slightly-underinformed post</a> (see the corrections in the comments) trying to draw a difference between Python and Ruby. I&#8217;ve finally got a decent example and can explain what I&#8217;m getting at.
</p>

<p>
I&#8217;m processing all the items in a big list, and part of that is performing some expensive calculation on an item attribute. There are only a few dozen values for the attribute, so I cache them: 
</p>

<pre>&nbsp;
results = <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">for</span> item <span style="color: #b1b100;">in</span> really_big_list:
    <span style="color: #b1b100;">if</span> item.<span style="color: #202020;">attribute</span> <span style="color: #b1b100;">in</span> results:
        result = results<span style="color: #66cc66;">&#91;</span>item.<span style="color: #202020;">attribute</span><span style="color: #66cc66;">&#93;</span>
    <span style="color: #b1b100;">else</span>:
        result = expensive_calculation<span style="color: #66cc66;">&#40;</span>item.<span style="color: #202020;">attribute</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #808080; font-style: italic;"># ... do something useful with item and result</span></pre>

<p>
It&#8217;s simple and readable, but it&#8217;s also lengthy. If I&#8217;m doing several expensive calculations on different attributes (and I am), my actual work gets lost in the noise. So I defined a dictionary that can do the heavy operation and cache the result:
</p>

<pre>&nbsp;
<span style="color: #b1b100;">class</span> LambdaDict<span style="color: #66cc66;">&#40;</span>dict<span style="color: #66cc66;">&#41;</span>:
    <span style="color: #b1b100;">def</span> <span style="color: #b1b100;">__init__</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">self</span>, l<span style="color: #66cc66;">&#41;</span>:                                                                                                                       
        super<span style="color: #66cc66;">&#40;</span>LambdaDict, <span style="color: #b1b100;">self</span><span style="color: #66cc66;">&#41;</span>.__init__<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #b1b100;">self</span>.<span style="color: #202020;">l</span> = l
&nbsp;
    <span style="color: #b1b100;">def</span> <span style="color: #b1b100;">__getitem__</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">self</span>, key<span style="color: #66cc66;">&#41;</span>:                                                                                                                  
        <span style="color: #b1b100;">if</span> key <span style="color: #b1b100;">in</span> <span style="color: #b1b100;">self</span>:
            <span style="color: #b1b100;">return</span> <span style="color: #b1b100;">self</span>.<span style="color: #202020;">get</span><span style="color: #66cc66;">&#40;</span>key<span style="color: #66cc66;">&#41;</span>
        <span style="color: #b1b100;">else</span>:
            <span style="color: #b1b100;">self</span>.__setitem__<span style="color: #66cc66;">&#40;</span>key, <span style="color: #b1b100;">self</span>.<span style="color: #202020;">l</span><span style="color: #66cc66;">&#40;</span>key<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
            <span style="color: #b1b100;">return</span> <span style="color: #b1b100;">self</span>.<span style="color: #202020;">get</span><span style="color: #66cc66;">&#40;</span>key<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># and now my code becomes</span>
&nbsp;
results = LambdaDict<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span>  key:expensive_calculation<span style="color: #66cc66;">&#40;</span>key<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #b1b100;">for</span> item <span style="color: #b1b100;">in</span> really_big_list:
    result = results<span style="color: #66cc66;">&#91;</span>item.<span style="color: #202020;">attribute</span><span style="color: #66cc66;">&#93;</span>
    <span style="color: #808080; font-style: italic;"># ... do something useful with item and result</span>
&nbsp;</pre>

<p>
That&#8217;s really nice, clean code that I&#8217;m satisfied with. The difference in Python and Ruby here is that Ruby hashes (the equivalent of dicts) include this behavior by default, just pass a block (lambda) when constructing the hash and it&#8217;ll be called for every missing key.
</p>

<p>
I&#8217;ll have the same behavior in Python or Ruby, it&#8217;s just that the default Python object doesn&#8217;t give me a handy method for building a dictionary that might perform some arbitrary expensive method on a simple lookup. Ruby is in favor of implicit magic, so it holds out the hook. This is the difference I was trying to get at: Python&#8217;s builtin objects have fewer methods and convenient hooks for me to do weird and useful things than Ruby&#8217;s, and Ruby will even let me tinker with them. Ruby has open classes, so I can extend both the builtin and defined classes with my own methods:
</p>

<pre>&nbsp;
module Enumerable <span style="color: #808080; font-style: italic;"># included by Arrays and similar objects</span>
  def sum
    inject<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> |x, y| x + <span style="color: #000066;">y</span> <span style="color: #66cc66;">&#125;</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
This adds a sum() method every Array in my program, whether I construct it (like I created my own <kbd>results</kbd> dict) or get it from some library code. In Python I&#8217;d have to define my own Array type and I&#8217;d be out of luck if I&#8217;m getting back arrays from a library. <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9Nb25rZXlfcGF0Y2g=">Monkey patching</a> is Python&#8217;s (deliberately clunky) name for adding a method to a single object at runtime. I&#8217;d have to monkey patch every object as it&#8217;s returned from the library rather than just being able to declare that every object of that class should have my method.
</p>

<p>
If this is the first time you&#8217;ve seen open classes: yes, when I first saw it I felt exactly the same way you do. Dangerous unreliable hackery, a recipe for disaster. But I&#8217;ve seen a lot of useful things happen in Rails because of it, and my Ruby projects have benefited from being able to add a method to an existing library&#8217;s objects, to overwrite (or just chain my code before or after) another method.
</p>

<p>
It&#8217;s something of a last resort that lets me build the cleanest object system I can as I interface with builtin objects and library code. I don&#8217;t have any utility methods floating around or have to tweak each object as I get it back from an API call. As I cook, Ruby&#8217;s metaprogramming is the garnish that finishes the dish. I called Python academically inconvenient because it feels like there&#8217;s an academic designer at my shoulder saying, &#8220;No, you don&#8217;t want to do that, it&#8217;d be messy and might be be abused. Pedagogically unsound.&#8221; I love that Python pushes me to build an explicit and obvious code, but I find myself wanting to tuck in one little bit of magic to make the code perfect.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=299" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2008/caching-dictionaries-in-python-vs-ruby/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Painless Upgrade to Rails 2.0</title>
		<link>http://push.cx/2007/painless-upgrade-to-rails-20</link>
		<comments>http://push.cx/2007/painless-upgrade-to-rails-20#comments</comments>
		<pubDate>Thu, 13 Dec 2007 12:10:20 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[ActiveResource]]></category>
		<category><![CDATA[NearbyGamers]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Rails 2.0]]></category>
		<category><![CDATA[routing]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[upgrade]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://push.cx/2007/painless-upgrade-to-rails-20</guid>
		<description><![CDATA[I spent a dead-easy 2.5 hours last night updating NearbyGamers to Rails 2.0. My svn commit message read (with links added here for convenience): Updated to Rails 2.0.1 rm&#8217;d lib/slash_urls.rb: Rails switched from ; to / to separate actions rm&#8217;d lib/resource_requirements.rb: now included in ActiveResources rm&#8217;d app/helpers/tags_helper.rb and gamers_helper.rb that had old controller names and [...]]]></description>
			<content:encoded><![CDATA[<p>
I spent a dead-easy 2.5 hours last night updating <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20=">NearbyGamers</a> to Rails 2.0. My svn commit message read (with links added here for convenience):
</p>

<blockquote>
Updated to Rails 2.0.1

<ul>
<li>rm&#8217;d <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9yYWlscy1zZW1pY29sb25zLW91dC1zbGFzaGVzLWlu">lib/slash_urls.rb</a>: Rails switched from ; to / to separate actions</li>
<li>rm&#8217;d <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Rldi5ydWJ5b25yYWlscy5vcmcvdGlja2V0Lzc2MzMgd2l0aA0KCmh0dHA6Ly9wdXNoLmN4LzIwMDcvcmFpbHMtc2VtaWNvbG9ucy1vdXQtc2xhc2hlcy1pbgoK">lib/resource_requirements.rb</a>: now included in ActiveResources</li>
<li>rm&#8217;d app/helpers/tags_helper.rb and gamers_helper.rb that had old controller names and were unused anyways</li>
<li>app/controllers/gamers_controller.rb: documented and fixed raw post variable extraction</li><li>updated post_path linkers in many views, controllers, and tests</li>
<li>renamed discussion_anchor_post_path to anchor_discussion_post_path to match the new ordering for nested resource urls</li>
<li>fix tag sorting on <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20vdGFncw==">tag index</a></li>
<li>move tags from /tags/Board+Games to <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20vdGFncy9Cb2FyZF9HYW1lcw==">/tags/Board_Games</a>, as Rails fixed the bug that encoded &#8216; &#8216; as &#8216;+&#8217; in non-get variable parts of the URL</li>
</ul>
</blockquote>

<h2>The Details</h2>

<p>
The first two files I deleted were my patches to URL generation that Rails now includes. The next two helper files I never used, but had had old (singular noun) names.
</p>

<p>
The bit about documentation: the way to get at raw post variables changed, so I tweaked code and left myself a reminder of why I&#8217;m doing it (I had to look at the changelog, which means it wasn&#8217;t self-evident).
</p>

<p>
Nested resources (I have nested <kbd>map.resources :discussions { |d| d.resources :posts }</kbd>) changed from <kbd>discussion_edit_post_url</kbd> to <kbd>edit_discussion_post_url</kbd>, so there was a bunch of places to change that. The next change about anchor is me following this convention with my own convenience method.
</p>

<p>
Tag sorting on the index page was a bug that Snarky pointed out to me. When I made some performance tweaks to that page I forgot to keep sorting tags as they came out of the database. This arguably should&#8217;ve been a revision of its own as it&#8217;s unrelated to the upgrade, but it was an easy one-line bugfix so I let it in.
</p>

<p>
Last, I renamed the tag pages. The tag model&#8217;s <kbd>to_param</kbd> just returns <kbd>self.name</kbd> and Rails would turn &#8220;Board Games&#8221; into &#8220;Board+Games&#8221;. It&#8217;s common but technically incorrect, as + only means space in encoded GET/POST variables. The proper encoding of &#8220;Board%20Games&#8221; was really noisy, so I took a page from Wikipedia&#8217;s pagebook and use underscores instead, like &#8220;Board_Games&#8221;. Was one line in the <kbd>to_param</kbd> and one line in the controller&#8217;s <kbd>load_tag</kbd> before_filter, a dozen lines of tweaking old tests, and seven lines of new tests. Eeeeeasy. 
</p>

<h2>The Verdict</h2>

<p>
Tests, tests, tests. If I didn&#8217;t have a solid test suite, I&#8217;d be noticing bugs two months from now in the least-frequently-exercised bits of code. Not only would I not have remembered to test some of the functionality, I wouldn&#8217;t have remembered the corner cases &#8212; or maybe I&#8217;d just have gotten bored of clicking through pages over and over and ignored the corner cases.
</p>

<p>
None of these were hard fixes and none were frustrating. I&#8217;d probably have finished even sooner if I hadn&#8217;t also been poking <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2ljYW5oYXNjaGVlemJ1cmdlci5jb20vMjAwNy8xMi8xMS9taXRvc2lzLw==">lolcats</a> and chatting with friends. And now I have a big list of shiny new Rails 2.0 features I can put to work in <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20=">NearbyGamers</a>.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=292" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/painless-upgrade-to-rails-20/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Keep Ruby Gems in Your Home Directory</title>
		<link>http://push.cx/2007/keep-ruby-gems-in-your-home-directory</link>
		<comments>http://push.cx/2007/keep-ruby-gems-in-your-home-directory#comments</comments>
		<pubDate>Mon, 05 Nov 2007 16:00:44 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[gems]]></category>
		<category><![CDATA[install]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[RubyGems]]></category>
		<category><![CDATA[shared hosting]]></category>

		<guid isPermaLink="false">http://push.cx/2007/keep-ruby-gems-in-your-home-directory</guid>
		<description><![CDATA[I like keeping my Ruby Gems in my home directory. I don&#8217;t have to type sudo in front of every gem command, it&#8217;s easier to remember the path to them when I want to read their source, and I don&#8217;t have to worry about a sysadmin on a shared host updating a gem before I [...]]]></description>
			<content:encoded><![CDATA[<p>
I like keeping my Ruby Gems in my home directory. I don&#8217;t have to type <kbd>sudo</kbd> in front of every <kbd>gem</kbd> command, it&#8217;s easier to remember the path to them when I want to read their source, and I don&#8217;t have to worry about a sysadmin on a shared host updating a gem before I test it. Here&#8217;s how to make those benefits yours:
</p>

<p>
Create or edit your <kbd>.gemrc</kbd> to read:
</p>

<pre>
gemhome: /home/&lt;i&gt;your username&lt;/i&gt;/.gems
gempath:
- /home/&lt;i&gt;your username&lt;/i&gt;/.gems
- /usr/lib/ruby/gems/1.8
</pre>

<p>
Next, set up your login environment. Add these lines to the end of your <kbd>.bashrc</kbd>, <kbd>.bash_profile</kbd>, or <kbd>.profile</kbd> (whichever file you happen to already have &mdash; if you use another shell, you should already know what file is the equivalent).
</p>

<pre>&nbsp;
<span style="color: #000066;">export</span> <span style="color: #0000ff;">PATH=</span>~/bin:~/.gems/bin:<span style="color: #0000ff;">$PATH</span>
<span style="color: #000066;">export</span> <span style="color: #0000ff;">GEM_HOME=</span>/home/&lt;i&gt;your username&lt;/i&gt;/.gems
<span style="color: #000066;">export</span> <span style="color: #0000ff;">GEM_PATH=</span>/home/&lt;i&gt;your username&lt;/i&gt;/.gems:/usr/lib/ruby/gems1.<span style="color: #cc66cc;">8</span></pre>

<p>
Last, add the following to your <kbd>.ssh/environment</kbd> so that gems work properly when you&#8217;re executing commands over ssh (for example, with capistrano).
</p>

<pre>&nbsp;
<span style="color: #0000ff;">PATH=</span>~/bin:~/.gems/bin:/bin:/usr/bin:/usr/<span style="color: #000066;">local</span>/bin:/sbin:/usr/sbin:/usr/<span style="color: #000066;">local</span>/sbin
<span style="color: #0000ff;">GEM_HOME=</span>/home/&lt;i&gt;your username&lt;/i&gt;/.gems
<span style="color: #0000ff;">GEM_PATH=</span>/home/&lt;i&gt;your username&lt;/i&gt;/.gems:/usr/lib/ruby/gems1.<span style="color: #cc66cc;">8</span></pre>

<p>
You&#8217;ll need to log out and back in to update your login environment, and then you&#8217;ll be able to run <kbd>gem</kbd> normally. All the files get stored in the directory <kbd>~/.gems</kbd> if you want to look around.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=270" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/keep-ruby-gems-in-your-home-directory/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mocha</title>
		<link>http://push.cx/2007/mocha</link>
		<comments>http://push.cx/2007/mocha#comments</comments>
		<pubDate>Sat, 18 Aug 2007 19:41:31 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Mocha]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>

		<guid isPermaLink="false">http://push.cx/2007/mocha</guid>
		<description><![CDATA[I posted yesterday that I was dropping my own little custom mocking code and considering Mocha. A few hours later I made a pass at it and was blown away. It took very little time to convert my ~600 lines of tests to use Mocha and I spent most of that time just cleaning out [...]]]></description>
			<content:encoded><![CDATA[<p>
I <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9zaW1wbGUtcnVieS1tb2NraW5n">posted yesterday</a> that I was dropping my own little custom mocking code and considering Mocha. A few hours later I made a pass at it and was blown away. It took very little time to convert my ~600 lines of tests to use Mocha and I spent most of that time just cleaning out the cruft that my mocking code had engendered.
</p>

<p>
I&#8217;m now a big fan of Mocha like I am <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9yYWlscy0xMjEtaW1wcmVzc2lvbg==">of Rails</a>. Ruby has a way of allowing coders to write magically polished libraries.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=254" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/mocha/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Simple Ruby Mocking</title>
		<link>http://push.cx/2007/simple-ruby-mocking</link>
		<comments>http://push.cx/2007/simple-ruby-mocking#comments</comments>
		<pubDate>Fri, 17 Aug 2007 20:15:29 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[unit tests]]></category>

		<guid isPermaLink="false">http://push.cx/2007/simple-ruby-mocking</guid>
		<description><![CDATA[I mentioned at the end of my last post on testing that I wrote some code to do mocking for my unit tests in Ruby. Writing a small mock library was very much reinventing the wheel, but I needed to do it to earn a deeper understanding of mocks. I&#8217;m writing some code (&#8220;Fetcher&#8221;) to [...]]]></description>
			<content:encoded><![CDATA[<p>
I mentioned at the end of my <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9maXh0dXJlcy1pbi1ydWJ5LXVuaXQtdGVzdHM=">last post on testing</a> that I wrote some code to do mocking for my unit tests in Ruby. Writing a small mock library was very much reinventing the wheel, but I needed to do it to earn a deeper understanding of mocks. 
</p>

<p>
I&#8217;m writing some code (&#8220;Fetcher&#8221;) to talk to a POP3 server, fetch mail, and pass it off to another process. One of the tests deals with what happens when the POP3 server is down or otherwise unreachable.
</p>

<pre>&nbsp;
def test_setup_server_down
  pop3 = Mock.<span style="">new</span>
  pop3.<span style="">expect</span><span style="color: #66cc66;">&#40;</span>:<span style="color: #000000; font-weight: bold;">new</span>, <span style="color: #66cc66;">&#91;</span>MAIL_SERVER, MAIL_POP3_PORT<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span> raise Timeout::<span style="color: #006600;">Error</span>.<span style="">new</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"execution expired"</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#125;</span>
  f = Fetcher.<span style="">new</span><span style="color: #66cc66;">&#40;</span>pop3<span style="color: #66cc66;">&#41;</span>
  <span style="color: #808080; font-style: italic;"># further assertions that f acts correctly</span>
<span style="color: #b1b100;">end</span></pre>

<p>
This says that the Mock object expects a call to the new method with the given arguments, and when the call happens it runs the block. The block could return anything, but in this case it raises the same error as <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5ydWJ5LWRvYy5vcmcvc3RkbGliL2xpYmRvYy9uZXQvcG9wL3Jkb2MvY2xhc3Nlcy9OZXQvUE9QMy5odG1s">Net::Pop3</a> does when it can&#8217;t contact the server. After that the test can go on to make whatever assertions it needs to verify that the exception was handled properly.
</p>

<p>
The Mock object has a list of <kbd>calls</kbd> it expects to see and keeps a list of how it&#8217;s been <kbd>called</kbd> (yes, this could just be one list with an index but I thought it was mentally simpler this way). The test sets up what calls it should <kbd>expect</kbd> to see with what arguments (or blank for any) and block to run (or blank for none). When a method is called on the mock object, <kbd>method_missing</kbd> logs the call and executes the given block (raising a fuss if the call didn&#8217;t match what it expected). 
</p>

<pre>&nbsp;
class Mock
  attr_reader :calls, :called
&nbsp;
  <span style="color: #808080; font-style: italic;"># the stub arg makes it just record all calls</span>
  def initialize
    <span style="color: #0000ff;">@calls</span> = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
    <span style="color: #0000ff;">@called</span> = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  <span style="color: #808080; font-style: italic;"># Pass nil for args to ignore the actual args in the call.</span>
  <span style="color: #808080; font-style: italic;"># Proc is optional; default is empty proc returning nil.</span>
  def expect<span style="color: #66cc66;">&#40;</span>method, *args, &amp;proc<span style="color: #66cc66;">&#41;</span>
    <span style="color: #0000ff;">@calls</span> &lt;&lt; <span style="color: #66cc66;">&#123;</span>:method =&gt; method, :args =&gt; args.<span style="">first</span>, :proc =&gt; <span style="color: #66cc66;">&#40;</span>proc <span style="color: #b1b100;">or</span> Proc.<span style="">new</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#125;</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  def method_missing<span style="color: #66cc66;">&#40;</span>method, *args<span style="color: #66cc66;">&#41;</span>
    <span style="color: #0000ff;">@called</span> &lt;&lt; <span style="color: #66cc66;">&#123;</span>:method =&gt; method, :args =&gt; args<span style="color: #66cc66;">&#125;</span>
&nbsp;
    expect = <span style="color: #0000ff;">@calls</span>.<span style="">shift</span>
    raise <span style="color: #ff0000;">"Unexpected mock call #{method.to_s}(#{args.join(', ')})"</span> <span style="color: #b1b100;">if</span> expect.<span style="">nil</span>?
    raise <span style="color: #ff0000;">"Wrong mock call #{method.to_s}(#{args.join(', ')}); expected #{expect[:method]}(#{expect[:args].join(', ')})"</span> <span style="color: #b1b100;">if</span> method != expect<span style="color: #66cc66;">&#91;</span>:method<span style="color: #66cc66;">&#93;</span> <span style="color: #b1b100;">or</span> <span style="color: #66cc66;">&#40;</span>expect<span style="color: #66cc66;">&#91;</span>:args<span style="color: #66cc66;">&#93;</span> != nil <span style="color: #b1b100;">and</span> args != expect<span style="color: #66cc66;">&#91;</span>:args<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>
    expect<span style="color: #66cc66;">&#91;</span>:proc<span style="color: #66cc66;">&#93;</span>.<span style="">call</span><span style="color: #66cc66;">&#40;</span>*args<span style="color: #66cc66;">&#41;</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
It&#8217;s a straightforward little object, and I also added some code to raise a fuss if expected calls weren&#8217;t made. This does have the downside that any tests defining their own <kbd>teardown</kbd> need to call <kbd>super</kbd>.
</p>

<pre>&nbsp;
class Mock
  def fail_if_not_empty
    <span style="color: #808080; font-style: italic;"># Empty the call stack so that this obj doesn't throw errors for</span>
    <span style="color: #808080; font-style: italic;"># every later test between now and this object getting gc'd</span>
    calls, <span style="color: #0000ff;">@calls</span> = <span style="color: #0000ff;">@calls</span>, <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
    raise <span style="color: #ff0000;">"Mock calls uncalled: n"</span> + calls.<span style="">collect</span> <span style="color: #66cc66;">&#123;</span> |call| <span style="color: #ff0000;">"#{call[:method]}(#{call[:args]} { #{call[:proc] })"</span> <span style="color: #66cc66;">&#125;</span>.<span style="">join</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">" "</span><span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">unless</span> calls.<span style="">empty</span>?
  <span style="color: #b1b100;">end</span>
end
&nbsp;
class Test::<span style="color: #006600;">Unit</span>::<span style="color: #006600;">TestCase</span>
  def teardown
    finish_mocks
  <span style="color: #b1b100;">end</span>
&nbsp;
  def finish_mocks
    ObjectSpace.<span style="">each_object</span><span style="color: #66cc66;">&#40;</span>Mock<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">do</span> |m|
      <span style="color: #000066;">m</span>.<span style="">fail_if_not_empty</span>
    <span style="color: #b1b100;">end</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
This has been a handy piece of code to test the code I&#8217;ve written in the last two weeks, but it&#8217;s not good enough. I have to use a technique called dependency injection to test <kbd>Fetcher.new</kbd>, where the outside code passes it a POP3 object instead of its <kbd>initialize</kbd> just using Net::POP3. Useful for testing, but my code is badly repetitive when all the instantiation calls have to do this exact same setup. (As an aside, Jacob Proffitt recently started an interesting conversation on <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NjcnVmZnlsb29raW5nY2F0aGVyZGVyLmNvbS9hcmNoaXZlLzIwMDcvMDgvMDcvZGVwZW5kZW5jeS1pbmplY3Rpb24uYXNweA==">dependency injection</a>, took <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NjcnVmZnlsb29raW5nY2F0aGVyZGVyLmNvbS9hcmNoaXZlLzIwMDcvMDgvMTUvcmlwcGluZy1vbi1kaS5hc3B4">criticism</a>, and <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NjcnVmZnlsb29raW5nY2F0aGVyZGVyLmNvbS9hcmNoaXZlLzIwMDcvMDgvMTYvdGlsdGluZy1hdC13aW5kbWlsbHMuYXNweA==">responded</a>. Good reading.)
</p>

<p>
I was pondering how to extend the Mock object to let me mock class methods (eg a call to <kbd>Net::POP3.new</kbd>) when I realized I&#8217;d gone as far as I should down the do-it-yourself road. I&#8217;d heard of <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21vY2hhLnJ1Ynlmb3JnZS5vcmcv">Mocha</a> and it took me all of ten minutes to think to look at its <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2NoZWF0LmVycnRoZWJsb2cuY29tL3MvbW9jaGEv">cheat sheet</a> where that&#8217;s the first example.
</p>

<p>
After spending two hours or so writing and tweaking this code, the best thing for it is to be thrown away. I&#8217;ve learned about mocking by doing it and I&#8217;m better-prepared to understand someone else&#8217;s larger and better library.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=253" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/simple-ruby-mocking/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Fixtures in Ruby Unit Tests</title>
		<link>http://push.cx/2007/fixtures-in-ruby-unit-tests</link>
		<comments>http://push.cx/2007/fixtures-in-ruby-unit-tests#comments</comments>
		<pubDate>Thu, 12 Jul 2007 21:45:47 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[fixtures]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[unit tests]]></category>

		<guid isPermaLink="false">http://push.cx/2007/fixtures-in-ruby-unit-tests</guid>
		<description><![CDATA[I&#8217;m writing some Ruby scripts that sort and store lots of small files. After a day or two of hacking I had the basic code working, ran through a few thousand files, and a malformed file blew up the sorter. That was OK, the sorter was intentionally naive and lacking in error handling; I wanted [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;m writing some Ruby scripts that sort and store lots of small files. After a day or two of hacking I had the basic code working, ran through a few thousand files, and a malformed file blew up the sorter. That was OK, the sorter was intentionally naive and lacking in error handling; I wanted it to hack it together and try out a few approaches before committing to serious development.
</p>

<p>
Now it&#8217;s time to treat it as real code, which means getting it under test. Tests are especially useful for ensuring tricky edge cases like malformed input don&#8217;t quietly break during other changes. When I started writing unit tests for the sorter I wanted fixtures similar to the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21hbnVhbHMucnVieW9ucmFpbHMuY29tL3JlYWQvY2hhcHRlci8yNg==">Rails fixtures</a> so I could write:
</p>

<pre>&nbsp;
<span style="color: #000066;">require</span> File.<span style="">dirname</span><span style="color: #66cc66;">&#40;</span>__FILE__<span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">'/../test_helper'</span>
<span style="color: #000066;">require</span> <span style="color: #ff0000;">'message'</span>
&nbsp;
class MessageTest &lt; Test::<span style="color: #006600;">Unit</span>::<span style="color: #006600;">TestCase</span>
  fixtures :message
&nbsp;
  def test_initialization
    f = Message.<span style="">new</span> message<span style="color: #66cc66;">&#40;</span>:good<span style="color: #66cc66;">&#41;</span>
    <span style="color: #808080; font-style: italic;"># assert the object was parsed correctly, etc.</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
The basic usage is <kbd>fixtures :type</kbd> to load the data and create the named function (in this case, <kbd>message</kbd>)  for fetching data. First, I wrote some <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3lhbWwub3JnL3N0YXJ0Lmh0bWw=">YAML</a> fixtures for my data and put them in <kbd>test/fixtures/message.yaml</kbd>. You can see the <kbd>:good</kbd> key in use here:
</p>

<pre>
good: |
  [the body of a good message here]
missing_header: |
  [more text]
bad_checksum: |
  [more text]
</pre>

<p>
Because I&#8217;m parsing textfiles my fixtures look pretty simple, but the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5ydWJ5LWRvYy5vcmcvc3RkbGliL2xpYmRvYy95YW1sL3Jkb2MvaW5kZXguaHRtbA==">YAML library</a> for Ruby makes serialization of any very easy.
</p>

<p>
So here&#8217;s the code I put in <kbd>test/test_helper.rb</kbd> to set this up. I really like the <kbd>[list].flatten.each</kbd> idiom so the call from the unit test class can cleanly pass one or more types, eg: <kbd>fixtures :message</kbd> and <kbd>fixtures :message, :user</kbd>.
</p>

<pre>&nbsp;
class Test::<span style="color: #006600;">Unit</span>::<span style="color: #006600;">TestCase</span>
  <span style="color: #0000ff;">@@fixtures</span> = <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
  def self.<span style="">fixtures</span> list
    <span style="color: #66cc66;">&#91;</span>list<span style="color: #66cc66;">&#93;</span>.<span style="">flatten</span>.<span style="">each</span> <span style="color: #b1b100;">do</span> |fixture|
      self.<span style="">class_eval</span> <span style="color: #b1b100;">do</span>
        <span style="color: #808080; font-style: italic;"># add a method name for this fixture type</span>
        define_method<span style="color: #66cc66;">&#40;</span>fixture<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">do</span> |item|
          <span style="color: #808080; font-style: italic;"># load and cache the YAML</span>
          <span style="color: #0000ff;">@@fixtures</span><span style="color: #66cc66;">&#91;</span>fixture<span style="color: #66cc66;">&#93;</span> ||= YAML::<span style="color: #006600;">load_file</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"test/fixtures/#{fixture.to_s}.yaml"</span><span style="color: #66cc66;">&#41;</span>
          <span style="color: #0000ff;">@@fixtures</span><span style="color: #66cc66;">&#91;</span>fixture<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#91;</span>item.<span style="">to_s</span><span style="color: #66cc66;">&#93;</span>
        <span style="color: #b1b100;">end</span>
      <span style="color: #b1b100;">end</span>
    <span style="color: #b1b100;">end</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
(Note to Rails coders: I deliberately left out the pluralization, I like having the File class in <kbd>file.rb</kbd> with the fixtures in <kbd>text/fixtures/file.rb</kbd> and the database table named <kbd>file</kbd> and so on. I don&#8217;t mind Rails&#8217; convention of pluralizing to &#8220;files&#8221; in the latter two examples, but I&#8217;d rather have a single identifier.)
</p>

<p>
Last night at the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3J1ZG9scGhoZXJpbmdzb2NpZXR5Lm9yZy9pbmRleC5waHA/dGl0bGU9TWFpbl9QYWdl">Rudolph Hering Society</a> meeting <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Jsb2cuaWFuYmlja2luZy5vcmc=">Ian Bicking</a> and <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3Blb3BsZS5jcy51Y2hpY2Fnby5lZHUvfnZhcm1hYS8=">Atul Varma</a> explained mocking to me. I wrote a (very) little Ruby this morning to do mocking and I&#8217;ll post that in a day or two when I&#8217;m sure I didn&#8217;t do it too badly.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=250" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/fixtures-in-ruby-unit-tests/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Discussion URLs: Opaque, Usable, and Readable</title>
		<link>http://push.cx/2007/discussion-urls-opaque-usable-and-readable</link>
		<comments>http://push.cx/2007/discussion-urls-opaque-usable-and-readable#comments</comments>
		<pubDate>Thu, 05 Apr 2007 13:03:30 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[ActiveResource]]></category>
		<category><![CDATA[human-readable]]></category>
		<category><![CDATA[named routes]]></category>
		<category><![CDATA[nested routes]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[resources]]></category>
		<category><![CDATA[RESTful]]></category>
		<category><![CDATA[routes]]></category>
		<category><![CDATA[routing]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[URLs]]></category>

		<guid isPermaLink="false">http://push.cx/2007/discussion-urls-opaque-usable-and-readable</guid>
		<description><![CDATA[I just wrote about Human-Readable ActiveResource URLs, and now I want to examine one example of them more in-depth. Discussion forum URLs have several conflicting goals: human-readable I should get some idea of what the discussion&#8217;s about when I hover over a link permanent bookmarks, incoming links, and search engines all need reliable URLs editable [...]]]></description>
			<content:encoded><![CDATA[<p>
I just wrote about <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9odW1hbi1yZWFkYWJsZS1hY3RpdmVyZXNvdXJjZS11cmxz">Human-Readable ActiveResource URLs</a>, and now I want to examine one example of them more in-depth. Discussion forum URLs have several conflicting goals:
</p>

<dl>
  <dt>human-readable</dt> <dd>I should get some idea of what the discussion&#8217;s about when I hover over a link</dd>
  <dt>permanent</dt> <dd>bookmarks, incoming links, and search engines all need reliable URLs</dd>
  <dt>editable</dt> <dd>If a discussion drifts, it needs a new subject, which means it needs a new URL</dd>
  <dt>opaque</dt> <dd>I&#8217;d rather not roll out the carpet for someone to scrape all the discussions</dd>
</dl>

<p>
After a bit of pondering, I decided that URLs should look like this:
</p>

<p>
http://nearbygamers.com/discussions/<b>{slug}</b>-<b>{post count}</b>-<b>{subject}</b>
</p>

<dl>
  <dt>slug</dt> <dd>An unchanging random 5-character string.</dd>
  <dt>post count</dt> <dd>The number of posts in this discussion, so that when you look at the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL25lYXJ5YmdhbWVycy5jb20vZGlzY3Vzc2lvbnM=">discussions index</a> you know at a glance if you&#8217;ve read a thread because your browser colors visited links. I snagged this off <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5qb2Vsb25zb2Z0d2FyZS5jb20vYXJ0aWNsZXMvQnVpbGRpbmdDb21tdW5pdGllc3dpdGhTby5odG1s">the Joel</a>.</dd>
  <dt>subject</dt> <dd>Just the alphanumerics, <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5tYXR0Y3V0dHMuY29tL2Jsb2cvZGFzaGVzLXZzLXVuZGVyc2NvcmVzLw==">dash-separated</a>, updated as the subject is edited</dd>
</dl>

<p>
So two parts (post count and subject) on a discussion can change, and the controller uses the slug to load the discussion and redirect to the correct URL if either has changed. Bookmarks and search engines can update, and outside links never stop working.
</p>

<h3>The Code</h3>

<p>
First, a little snippet of code to generate slugs lives in <kbd>lib/slug.rb</kbd>:
</p>

<pre>&nbsp;
def random_slug<span style="color: #66cc66;">&#40;</span><span style="color: #000066;">length</span>=<span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#41;</span>
  chars = <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"a"</span>..<span style="color: #ff0000;">"z"</span><span style="color: #66cc66;">&#41;</span>.<span style="">to_a</span> + <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"A"</span>..<span style="color: #ff0000;">"Z"</span><span style="color: #66cc66;">&#41;</span>.<span style="">to_a</span> + <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"1"</span>..<span style="color: #ff0000;">"9"</span><span style="color: #66cc66;">&#41;</span>.<span style="">to_a</span>
  Array.<span style="">new</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066;">length</span>, <span style="color: #ff0000;">''</span><span style="color: #66cc66;">&#41;</span>.<span style="">collect</span><span style="color: #66cc66;">&#123;</span>chars<span style="color: #66cc66;">&#91;</span><span style="color: #000066;">rand</span><span style="color: #66cc66;">&#40;</span>chars.<span style="">size</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#125;</span>.<span style="">join</span>
<span style="color: #b1b100;">end</span></pre>

<p>
The Discussion model uses this to set a slug on itself if it doesn&#8217;t have one yet, and then uses that slug to generate URLs (note that I remove multiple and leading/trailing hyphens from the subjects):
</p>

<pre>&nbsp;
<span style="color: #000066;">require</span> <span style="color: #ff0000;">'slug'</span>
&nbsp;
class Discussion &lt; ActiveRecord::<span style="color: #006600;">Base</span>
  def to_param
    <span style="color: #ff0000;">"#{slug}-#{posts.count}-#{subject.gsub(/[^[:alnum:]]+/i, '-').gsub(/-+/, '-').gsub(/^-|-$/, '')}"</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  protected
  def before_validation
    <span style="color: #b1b100;">if</span> self.<span style="">slug</span>.<span style="">empty</span>?
      begin
        self.<span style="">slug</span> = random_slug
      <span style="color: #b1b100;">end</span> <span style="color: #b1b100;">while</span><span style="color: #66cc66;">&#40;</span>Discussion.<span style="">count</span><span style="color: #66cc66;">&#40;</span>:conditions =&gt; <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'slug = ?'</span>, self.<span style="">slug</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> &gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #b1b100;">end</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
Finally, the DiscussionsController loads discussion objects, throws 404 errors, and redirects appropriately:
</p>

<pre>&nbsp;
class DiscussionsController &lt; ApplicationController
  before_filter :load_discussion, :except =&gt; <span style="color: #66cc66;">&#91;</span> :<span style="color: #000066;">index</span> <span style="color: #66cc66;">&#93;</span>
&nbsp;
  private
  def load_discussion
    slug = params<span style="color: #66cc66;">&#91;</span>:id<span style="color: #66cc66;">&#93;</span>.<span style="">split</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'-'</span><span style="color: #66cc66;">&#41;</span>.<span style="">first</span> <span style="color: #b1b100;">if</span> params<span style="color: #66cc66;">&#91;</span>:id<span style="color: #66cc66;">&#93;</span>
    <span style="color: #0000ff;">@discussion</span> = Discussion.<span style="">find_by_slug</span><span style="color: #66cc66;">&#40;</span>slug<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">if</span> slug
    raise ::<span style="color: #006600;">ActionController</span>::<span style="color: #006600;">RoutingError</span>, <span style="color: #ff0000;">"Recognition failed for #{request.path}"</span> <span style="color: #b1b100;">if</span> <span style="color: #0000ff;">@discussion</span>.<span style="">nil</span>?
    redirect_to discussion_path<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">@discussion</span><span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">and</span> <span style="color: #000066;">return</span> <span style="color: #b1b100;">if</span> <span style="color: #0000ff;">@discussion</span>.<span style="">to_param</span> != params<span style="color: #66cc66;">&#91;</span>:id<span style="color: #66cc66;">&#93;</span>
  <span style="color: #b1b100;">end</span></pre> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=233" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/discussion-urls-opaque-usable-and-readable/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Add Feed Discovery Links Easily</title>
		<link>http://push.cx/2007/add-feed-discovery-links-easily</link>
		<comments>http://push.cx/2007/add-feed-discovery-links-easily#comments</comments>
		<pubDate>Thu, 08 Mar 2007 12:39:34 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[atom]]></category>
		<category><![CDATA[auto_discovery_link_tag]]></category>
		<category><![CDATA[feeds]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://push.cx/2007/add-feed-discovery-links-easily</guid>
		<description><![CDATA[I&#8217;m working on discussion forums for NearbyGamers and I&#8217;m building the first feeds into the site. I worked up a clean way to add them from my controllers similar to my tidy stylesheets code. Here&#8217;s how to do it. In the &#60;head&#62; of your app/views/layouts/application.rhtml call the auto_discovery_link_tag to print the tags: &#160; &#60;%- @feeds.each [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;m working on discussion forums for <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL25lYXJieWdhbWVycy5jb20=">NearbyGamers</a> and I&#8217;m building the first feeds into the site. I worked up a clean way to add them from my controllers similar to my <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=ZWRpdGVkIA==">tidy stylesheets</a> code. Here&#8217;s how to do it.
</p>

<p>
In the &lt;head&gt; of your <kbd>app/views/layouts/application.rhtml</kbd> call the <kbd>auto_discovery_link_tag</kbd> to print the tags:
</p>

<pre>&nbsp;
  &lt;%- <span style="color: #0000ff;">@feeds</span>.<span style="">each</span> <span style="color: #b1b100;">do</span> |feed| -%&gt;
    &lt;%= auto_discovery_link_tag<span style="color: #66cc66;">&#40;</span>:atom, *feed<span style="color: #66cc66;">&#41;</span> %&gt;
  &lt;%- <span style="color: #b1b100;">end</span> -%&gt;</pre>

<p>
In <kbd>app/controllers/application.rb</kbd>:
</p>

<pre>&nbsp;
  def initialize
    <span style="color: #0000ff;">@feeds</span> = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  def add_feed title, options=<span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
    <span style="color: #0000ff;">@feeds</span> &lt;&lt; <span style="color: #66cc66;">&#91;</span> <span style="color: #66cc66;">&#123;</span> 
      :controller =&gt; self.<span style="">controller_name</span>, 
      :action =&gt; self.<span style="">action_name</span>, 
      :<span style="color: #000066;">format</span> =&gt; <span style="color: #ff0000;">'atom'</span> 
    <span style="color: #66cc66;">&#125;</span>.<span style="">update</span><span style="color: #66cc66;">&#40;</span>options<span style="color: #66cc66;">&#41;</span>, <span style="color: #66cc66;">&#123;</span> :title =&gt; title <span style="color: #66cc66;">&#125;</span> <span style="color: #66cc66;">&#93;</span> 
  <span style="color: #b1b100;">end</span></pre>

<p>
And you&#8217;re all set up. Where you want an action to present feeds, call <kbd>add_feed</kbd>. After title, it takes options for url construction.
</p>

<pre>&nbsp;
  add_feed <span style="color: #ff0000;">'New discussions'</span>
  add_feed <span style="color: #ff0000;">'New posts'</span>, :action =&gt; <span style="color: #ff0000;">'posts'</span>, :sort_by =&gt; <span style="color: #ff0000;">'new'</span></pre>

<p>
It defaults to the current action with a format of &#8216;atom&#8217; so you can add feed code to your <kbd>respond_to</kbd> block. I&#8217;ll post again soon with code integrate <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Rldi5ydWJ5b25yYWlscy5vcmcvYnJvd3Nlci9wbHVnaW5zL3Jlc291cmNlX2ZlZWRlcj9yZXY9NTA5OA==">resource_feeder</a> to do this.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=229" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/add-feed-discovery-links-easily/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Colorizing Rails Test Output</title>
		<link>http://push.cx/2007/colorizing-rails-test-output</link>
		<comments>http://push.cx/2007/colorizing-rails-test-output#comments</comments>
		<pubDate>Tue, 06 Mar 2007 18:59:43 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[color]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[redgreen]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://push.cx/2007/colorizing-rails-test-output</guid>
		<description><![CDATA[I love making things easier to read, to skim, to take in at a glance. At last night&#8217;s the ChiRb presentation on rspec I noticed the output was nicely colorized. Hey, of course that&#8217;s easier to read. It&#8217;s also dead easy to add to your existing tests thanks to a gem by Pat Eyler, whether [...]]]></description>
			<content:encoded><![CDATA[<p>
I love making things easier to read, to skim, to take in at a glance. At <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2NoaXJiLm9yZy9ldmVudC9zaG93LzEz">last night&#8217;s</a> the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3J1Ynlmb3JnZS5vcmcvbWFpbG1hbi9saXN0aW5mby9jaGljYWdvZ3JvdXAtbWVtYmVycy1saXN0">ChiRb</a> presentation on <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3JzcGVjLnJ1Ynlmb3JnZS5vcmcv">rspec</a> I noticed the output was nicely colorized.
</p>

<p>
Hey, of course that&#8217;s easier to read. It&#8217;s also dead easy to add to your existing tests thanks to <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL29uLXJ1YnkuYmxvZ3Nwb3QuY29tLzIwMDYvMDYvbW9yZS1mdW4td2l0aC1yZWRncmVlbi5odG1s">a gem by Pat Eyler</a>, whether you call then with <kbd>rake test</kbd>, <kbd>rake test:units</kbd>, or <kbd>ruby test/functional/application_controller_test.rb</kbd>.
</p>

<pre>&nbsp;
$ sudo gem install redgreen</pre>

<p>
Edit your <kbd>test/test_helper.rb</kbd> and add <kbd>require 'redgreen'</kbd> after the other requires, and you&#8217;re done. If you run your tests, you&#8217;ll see something like:
</p>

<img class="important" src="http://push.cx/wp-content/uploads/2007/03/color_tests.png" alt="colorized test output" />

<p>
Passes are green, fails are red, errors are yellow. Here&#8217;s hoping you just see lots of green.
</p>

<p>
And rspec looks like good stuff, I&#8217;m going to add it to my test suite for <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20=">NearbyGamers</a>. The ability to test controllers without testing views (and vice-versa) will be a win.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=225" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/colorizing-rails-test-output/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Announcing NearbyGamers</title>
		<link>http://push.cx/2007/announcing-nearbygamers</link>
		<comments>http://push.cx/2007/announcing-nearbygamers#comments</comments>
		<pubDate>Mon, 22 Jan 2007 04:11:06 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Biz]]></category>
		<category><![CDATA[Barking Stapler]]></category>
		<category><![CDATA[NearbyGamers]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://push.cx/2007/announcing-nearbygamers</guid>
		<description><![CDATA[I&#8217;d like to invite you all to check out my newest project, NearbyGamers, a service for tabletop gamers to find other players. (As I mentioned earlier, it&#8217;s a Rails site.) It&#8217;s for people who play RPGs, CCGs, TCGs, wargames, board games &#8212; basically any game where you need to have a live human on the [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;d like to invite you all to check out my newest project, <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL05lYXJieUdhbWVycy5jb20=">NearbyGamers</a>, a service for tabletop gamers to find other players. (As I <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNi9tYWtpbmctdmFsaWQteGh0bWwtZWFzaWVy">mentioned earlier</a>, it&#8217;s a Rails site.) It&#8217;s for people who play RPGs, CCGs, TCGs, wargames, board games &#8212; basically any game where you need to have a live human on the other side of a table if you want to play.
</p>

<img class="content" src="http://push.cx/wp-content/uploads/2007/01/NG-map.png" alt="NearbyGamers map screenshot" />

<p>
Basically it&#8217;s the mashup of a wiki and Google Maps, and I plan to add forums (there are very few things gamers like more than arguing online). I&#8217;ve been hacking at it on and off for a couple months now, and it&#8217;s finally worth talking about. NG is my first large Rails project, and it&#8217;s been a lot of fun. Almost all the time the code is quite dense and beautiful, but several times I&#8217;ve worked up some fairly ugly hackish code I&#8217;m not particularly happy with. And then a few days later an nice, friendly little solution will pop into my head, and it&#8217;s easy to hack in because I have comprehensive tests. (Having tests has really saved my life. I&#8217;ll be posting more about it, but for now I&#8217;ll just say that I couldn&#8217;t have built NG without automated tests.)
</p>

<p>
Some of the early beta testers are computer game fans, so there&#8217;s a fair number of computer games listed on NearbyGamers right now &#8212; heck, <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL25lYXJieWdhbWVycy5jb20vdGFnL1dvcmxkK29mK1dhcmNyYWZ0">World of Warcraft</a> is the most popular tag. I don&#8217;t see what folks will get out of it, but I&#8217;d rather build a pretty open system and let folks find new uses.
</p>

<p>
So check it out, let me know what you think. I&#8217;ve got a <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL25lYXJieWdhbWVycy5jb20vdG9kby55bWw=">todo list</a> online for the curious, and I&#8217;m always taking suggestions.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=197" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/announcing-nearbygamers/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Making Valid XHTML Easier</title>
		<link>http://push.cx/2006/making-valid-xhtml-easier</link>
		<comments>http://push.cx/2006/making-valid-xhtml-easier#comments</comments>
		<pubDate>Tue, 14 Nov 2006 23:14:19 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[xhtml]]></category>

		<guid isPermaLink="false">http://push.cx/2006/making-valid-xhtml-easier</guid>
		<description><![CDATA[I&#8217;m working on a Rails site in my Copious Free Time and I wanted to share a little way that Ruby made my life easier. I&#8217;m making my pages valid XHTML 1.0 Transitional because it makes life easier to find bugs and it just feels good to know I&#8217;m meeting the spec. The W3C Validator [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;m working on a Rails site in my <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2NhdGIub3JnL2phcmdvbi9odG1sL0MvY29waW91cy1mcmVlLXRpbWUuaHRtbA==">Copious Free Time</a> and I wanted to share a little way that Ruby made my life easier. I&#8217;m making my pages valid XHTML 1.0 Transitional because it makes life easier to find bugs and it just feels <i>good</i> to know I&#8217;m meeting the spec.
<p>

<p>
The <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3ZhbGlkYXRvci53My5vcmcv">W3C Validator</a> complained that I didn&#8217;t have the <kbd>rows</kbd> and <kbd>cols</kbd> attributes on my <kbd>&lt;textarea&gt;</kbd> tags. My code for them looked like:
</p>

<pre>&nbsp;
&lt;%= text_area_tag :message, params<span style="color: #66cc66;">&#91;</span>:message<span style="color: #66cc66;">&#93;</span> %&gt;</pre>

<p>
And I don&#8217;t want to add the <kbd>:size</kbd> option because I use CSS to style all of them, it&#8217;d be confusing to see an unused size there. So I extended the <kbd>text_area_tag</kbd> method in my <kbd>app/helpers/application_helper.rb</kbd> to fill in a default:
</p>

<pre>&nbsp;
module ApplicationHelper
  def text_area_tag<span style="color: #66cc66;">&#40;</span>name, content=nil, options=<span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>
    super<span style="color: #66cc66;">&#40;</span>name, content, <span style="color: #66cc66;">&#123;</span> :size =&gt; <span style="color: #ff0000;">"40x10"</span> <span style="color: #66cc66;">&#125;</span>.<span style="">update</span><span style="color: #66cc66;">&#40;</span>options<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
And it was that easy to start having valid tags. I&#8217;ll be posting more Rails snippets and tips as I work on my project, and I&#8217;ll definitely announce here when it&#8217;s ready for wide release.
</p>

<p>
(This snippet owes thanks to &#8216;leethal&#8217; in #rubyonrails on <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2ZyZWVub2RlLm5ldA==">irc.freenode.net</a> for straightening out how I was trying to override the method.)
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=190" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2006/making-valid-xhtml-easier/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tidy Stylesheets in Rails</title>
		<link>http://push.cx/2006/tidy-stylesheets-in-rails</link>
		<comments>http://push.cx/2006/tidy-stylesheets-in-rails#comments</comments>
		<pubDate>Sat, 28 Oct 2006 03:06:06 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[maintainability]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://push.cx/2006/tidy-stylesheets-in-rails</guid>
		<description><![CDATA[It&#8217;s very easy for a site&#8217;s CSS to grow a single giant, brittle stylesheet. It becomes impossible to change anything because of bizarre interactions between elements, unexpected interactions, and simply because it&#8217;s just too big for anyone to understand. Much of programming is managing complexity, and I&#8217;ll share a nice technique in that vein. I [...]]]></description>
			<content:encoded><![CDATA[<p>
It&#8217;s very easy for a site&#8217;s CSS to grow a single giant, brittle stylesheet. It becomes impossible to change anything because of bizarre interactions between elements, unexpected interactions, and simply because it&#8217;s just too big for anyone to understand. Much of programming is managing complexity, and I&#8217;ll share a nice technique in that vein.
</p>

<p>
I like to break down stylesheets so there&#8217;s a site-wide stylesheet with global stylings like fonts, the site&#8217;s template, and common elements. This is the file that metastasizes on you.
</p>

<p>
My solution is to break down stylesheets by controller and action, and Rails makes this quite easy:
</p>

<pre>&nbsp;
<span style="color: #808080; font-style: italic;"># app/views/layout/application.rb</span>
&lt;%= stylesheet_link_tag *<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'global'</span><span style="color: #66cc66;">&#93;</span> + <span style="color: #0000ff;">@stylesheets</span><span style="color: #66cc66;">&#41;</span> %&gt;</pre>

<pre>&nbsp;
<span style="color: #808080; font-style: italic;"># app/controllers/application.rb</span>
class ApplicationController &lt; ActionController::<span style="color: #006600;">Base</span>
  before_filter :add_stylesheets
&nbsp;
  def initialize
    <span style="color: #0000ff;">@stylesheets</span> = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  def add_stylesheets
    <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">"#{controller_name}/_controller"</span>, <span style="color: #ff0000;">"#{controller_name}/#{action_name}"</span><span style="color: #66cc66;">&#93;</span>.<span style="">each</span> <span style="color: #b1b100;">do</span> |stylesheet|
      <span style="color: #0000ff;">@stylesheets</span> &lt;&lt; stylesheet <span style="color: #b1b100;">if</span> File.<span style="">exists</span>? <span style="color: #ff0000;">"#{Dir.pwd}/stylesheets/#{stylesheet}.css"</span>
    <span style="color: #b1b100;">end</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
This code automatically loads stylesheets for the controller and the action if they exist. The subdivision allows you to make them as compact and specific as possible. If a partial needs its own code, write at the top:
</p>

<pre>&nbsp;
&lt;% <span style="color: #0000ff;">@styleshets</span> &lt;&lt; <span style="color: #ff0000;">"controller/_partial_name"</span> %&gt;</pre>

<p>
Nice and tidy.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=186" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2006/tidy-stylesheets-in-rails/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Strings are a Domain-Specific Language</title>
		<link>http://push.cx/2006/strings-are-a-domain-specific-language</link>
		<comments>http://push.cx/2006/strings-are-a-domain-specific-language#comments</comments>
		<pubDate>Sat, 27 May 2006 23:11:26 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[assembly]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://push.cx/2006/strings-are-a-domain-specific-language</guid>
		<description><![CDATA[Question: Isn&#8217;t a domain-specific language just the same thing as a library? Source: Pretty much everyone the first time they hear of DSLs. Answer: No, a DSL is much more than a library, and I have an example that won&#8217;t make you say, &#8220;Well, sure, if you&#8217;re doing something that esoteric&#8230;&#8221; My example of a [...]]]></description>
			<content:encoded><![CDATA[<blockquote>
Question: Isn&#8217;t a domain-specific language just the same thing as a library?
<p style="font-size: 75%; text-align: right">Source: Pretty much everyone the first time they hear of DSLs.</p>
</blockquote>

<p>
Answer: No, a DSL is much more than a library, and I have an example that won&#8217;t make you say, &#8220;Well, sure, if you&#8217;re doing something <i>that</i> esoteric&#8230;&#8221;
</p>

<p>
My example of a domain-specific language is strings. No, seriously. Let&#8217;s figure out the length of a string in <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5pbnQ4MGgub3JnL3N0cmxlbi8=">x86 assembly</a>:
</p>

<pre>&nbsp;
strlen:
	<span style="color: #00007f;">push</span>	<span style="color: #46aa03; font-weight:bold;">edi</span>
	<span style="color: #00007f;">sub</span>	<span style="color: #46aa03; font-weight:bold;">ecx</span>, <span style="color: #46aa03; font-weight:bold;">ecx</span>
	<span style="color: #00007f;">mov</span>	<span style="color: #46aa03; font-weight:bold;">edi</span>, <span style="color: #66cc66;">&#91;</span><span style="color: #46aa03; font-weight:bold;">esp</span>+<span style="color: #ff0000;">8</span><span style="color: #66cc66;">&#93;</span>
	<span style="color: #00007f;">not</span>	<span style="color: #46aa03; font-weight:bold;">ecx</span>
	<span style="color: #00007f;">sub</span>	<span style="color: #46aa03; font-weight:bold;">al</span>, <span style="color: #46aa03; font-weight:bold;">al</span>
	<span style="color: #00007f;">cld</span>
<span style="color: #00007f;">repne</span>	<span style="color: #00007f;">scasb</span>
	<span style="color: #00007f;">not</span>	<span style="color: #46aa03; font-weight:bold;">ecx</span>
	<span style="color: #00007f;">pop</span>	<span style="color: #46aa03; font-weight:bold;">edi</span>
	<span style="color: #00007f;">lea</span>	<span style="color: #46aa03; font-weight:bold;">eax</span>, <span style="color: #66cc66;">&#91;</span>ecx-<span style="color: #ff0000;">1</span><span style="color: #66cc66;">&#93;</span>
	<span style="color: #00007f;">ret</span></pre>

<p>
Computer memory is one big linear stream of bytes we can scan through, looking for the null that terminates our string. Boy, is that some fast code &#8212; we might even call it efficient, if we ignore the fact that we&#8217;ll reach the eventual heat death of the universe before we finish our <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5jZXJhZG8uY29tL3dlYjIwcXVpei5odG0=">web 2.0</a> app.
</p>

<p>
So we move up in abstraction to C, which has arrays. And you can pretend a string is an array and walk it looking for that null terminator:
</p>

<pre>&nbsp;
<span style="color: #993333;">static</span> <span style="color: #993333;">int</span> my_strlen<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">const</span> <span style="color: #993333;">char</span> *c<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #993333;">int</span> l = <span style="color: #cc66cc;">0</span>;
    <span style="color: #b1b100;">while</span> <span style="color: #66cc66;">&#40;</span>*c++<span style="color: #66cc66;">&#41;</span> l++;
    <span style="color: #b1b100;">return</span> l;
<span style="color: #66cc66;">&#125;</span></pre>

<p>
This code is basically the same as in assembly, but it must be nicer to read because it uses all that stylish punctuation. Well, it&#8217;s not really nicer, maybe a string isn&#8217;t really just an array. So let&#8217;s look at Python:
</p>

<pre>&nbsp;
<span style="color: #b1b100;">len</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"Hello, world!"</span><span style="color: #66cc66;">&#41;</span></pre>

<p>
Now that&#8217;s downright human-readable. And I&#8217;ll admit I&#8217;m fudging here by just calling the built-in <kbd>len()</kbd> instead of writing one, but it just works and there&#8217;s none of this messing around with null bytes.
</p>

<p>
Well, maybe there&#8217;s messing around with null bytes. I don&#8217;t have to know how Python implements <kbd>len()</kbd> and, more importantly, I don&#8217;t have to pretend a string is only an array or a small bit of sequentially-addressed memory.
</p>

<p>
To continue the example let&#8217;s look at regular expressions, a powerful way to search strings. We&#8217;ll write a pirate detector in Python:
</p>

<pre>&nbsp;
<span style="color: #b1b100;">import</span> re
matches = re.<span style="color: #202020;">search</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"ar+g+h"</span>, <span style="color: #ff0000;">"Oim a poirate, arrrgh!"</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">if</span> matches:
    <span style="color: #b1b100;">print</span> <span style="color: #ff0000;">"There must be a pirate, I heard someone say '%s'."</span> % matches.<span style="color: #202020;">group</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">else</span>:
    <span style="color: #b1b100;">print</span> <span style="color: #ff0000;">"No pirates detected."</span></pre>

<p>
This is important code, as pirates hide <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL29zdGVlbGUuY29tL2FyY2hpdmVzLzIwMDUvMTIvYWFyZ2g=">all over the web</a>. But it&#8217;s pretty clunky, we have to import a library and call functions and evaluating responses and save objects&#8230; It&#8217;d sure be handy if regular expressions were part of the language like in Ruby:
</p>

<pre>&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #ff0000;">"Oim a poirate, arrrgh!"</span> =~ /ar+g+h/ <span style="color: #b1b100;">then</span>
  puts <span style="color: #ff0000;">"There must be a pirate, I heard someone say '#{$&amp;}'."</span>
<span style="color: #b1b100;">else</span>
  puts <span style="color: #ff0000;">"No pirates detected."</span>
<span style="color: #b1b100;">end</span></pre>

<p>
This code is even nicer, our regexp is a first-class type and tightly integrated into the language. The increase in stylish puncutation might make for a higher learning curve, but we can express ourselves much more naturally.
</p>

<p>
A DSL is all about moving up in abstraction until your code directly reflects the high-level concepts you&#8217;re working in. You don&#8217;t have to peer through a haze of bits and pointers, your actions become synonymous with your intentions.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=110" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2006/strings-are-a-domain-specific-language/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby Blocks and Blocks</title>
		<link>http://push.cx/2006/ruby-blocks-and-blocks</link>
		<comments>http://push.cx/2006/ruby-blocks-and-blocks#comments</comments>
		<pubDate>Fri, 28 Apr 2006 21:32:13 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://push.cx/2006/ruby-blocks-and-blocks</guid>
		<description><![CDATA[I&#8217;m reading Programming Ruby: 2nd Ed. and an example on page 57 has captured my attention. (Code slightly modified for brevity) &#160; "3 4\n5 6\n7 8".each do &#124;line&#124; v1, v2 = line.split print Integer&#40;v1&#41; + Integer&#40;v2&#41;, " " end The book is just explaining to Perl coders that you have to call Integer() to convert [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;m reading <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3ByYWdtYXRpY3Byb2dyYW1tZXIuY29tL3RpdGxlcy9ydWJ5L2luZGV4Lmh0bWw=">Programming Ruby: 2nd Ed.</a> and an example on page 57 has captured my attention. (Code slightly modified for brevity)
</p>

<pre>&nbsp;
<span style="color: #ff0000;">"3 4<span style="color: #000099; font-weight: bold;">\n</span>5 6<span style="color: #000099; font-weight: bold;">\n</span>7 8"</span>.<span style="">each</span> <span style="color: #b1b100;">do</span> |line|
  v1, v2 = line.<span style="">split</span>
  <span style="color: #000066;">print</span> Integer<span style="color: #66cc66;">&#40;</span>v1<span style="color: #66cc66;">&#41;</span> + Integer<span style="color: #66cc66;">&#40;</span>v2<span style="color: #66cc66;">&#41;</span>, <span style="color: #ff0000;">" "</span>
<span style="color: #b1b100;">end</span></pre>

<p>
The book is just explaining to Perl coders that you have to call Integer() to convert strings to ints, but I see an interesting opportunity to restructure the code.
</p>

<pre>&nbsp;
<span style="color: #ff0000;">"3 4<span style="color: #000099; font-weight: bold;">\n</span>5 6<span style="color: #000099; font-weight: bold;">\n</span>7 8"</span>.<span style="">collect</span> <span style="color: #b1b100;">do</span> |line|
  line.<span style="">split</span>
<span style="color: #b1b100;">end</span>.<span style="">each</span> <span style="color: #b1b100;">do</span> |a, b|
  <span style="color: #000066;">print</span> Integer<span style="color: #66cc66;">&#40;</span>a<span style="color: #66cc66;">&#41;</span> + Integer<span style="color: #66cc66;">&#40;</span>b<span style="color: #66cc66;">&#41;</span>, <span style="color: #ff0000;">" "</span>
<span style="color: #b1b100;">end</span></pre>

<p>
My brain is nagging me that there&#8217;s a fundamental concept at work in this change, but I can&#8217;t quite put my finger on it. It&#8217;s not just that I&#8217;m building an array in the middle or that it evaluates differently (after producing identical output), it&#8217;s that it looks something like nested fuction calls. It feels like a more a functional style of programming, but that&#8217;s not quite all.
</p>

<p>
I&#8217;m compelled to write this as a block yielding to a block, though it doesn&#8217;t compile:
</p>

<pre>&nbsp;
<span style="color: #ff0000;">"3 4<span style="color: #000099; font-weight: bold;">\n</span>5 6<span style="color: #000099; font-weight: bold;">\n</span>7 8"</span>.<span style="">collect</span> <span style="color: #66cc66;">&#123;</span> |line| yield line.<span style="">split</span> <span style="color: #66cc66;">&#125;</span> <span style="color: #66cc66;">&#123;</span> |a, b| <span style="color: #000066;">print</span> Integer<span style="color: #66cc66;">&#40;</span>a<span style="color: #66cc66;">&#41;</span> + Integer<span style="color: #66cc66;">&#40;</span>b<span style="color: #66cc66;">&#41;</span>, <span style="color: #ff0000;">" "</span> <span style="color: #66cc66;">&#125;</span></pre>

<p>
Any thoughts? Am I just being weird, or can anyone put better words to it?
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=99" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2006/ruby-blocks-and-blocks/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

