<?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>P is for Programming</title>
	<atom:link href="http://www.jacopretorius.net/feed" rel="self" type="application/rss+xml" />
	<link>http://www.jacopretorius.net</link>
	<description></description>
	<lastBuildDate>Fri, 03 Feb 2012 15:00:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Scopes in Rails</title>
		<link>http://www.jacopretorius.net/2012/02/scopes-in-rails.html</link>
		<comments>http://www.jacopretorius.net/2012/02/scopes-in-rails.html#comments</comments>
		<pubDate>Fri, 03 Feb 2012 15:00:08 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=479</guid>
		<description><![CDATA[Scopes is one of the features in Rails that I only learned about through reading The Rails 3 Way. It doesn&#8217;t seem to be a feature that&#8217;s used very often, but I think it can make your code a lot neater if it&#8217;s used correctly. I&#8217;m going to illustrate how scopes can be used with [...]]]></description>
			<content:encoded><![CDATA[<p>Scopes is one of the features in Rails that I only learned about through reading <a href="http://www.jacopretorius.net/2012/01/book-review-the-rails-3-way.html">The Rails 3 Way</a>.  It doesn&rsquo;t seem to be a feature that&rsquo;s used very often, but I think it can make your code a lot neater if it&rsquo;s used correctly.</p>
<p>I&rsquo;m going to illustrate how scopes can be used with a simple example.</p>
<h4>A Product Application</h4>
<p>I&rsquo;ve created a very simple application to manage products.  All the basic functionality is there &ndash; view/create/edit/delete.</p>
<p><img src="https://lh5.googleusercontent.com/-Ld6mfHo8qxE/TyMC_USwZEI/AAAAAAAAAlc/StxKRloepak/s800/Screen%2520Shot%25202012-01-27%2520at%25203.02.35%2520PM.png" alt="List of Products" class="white-shadow" /></p>
<p>The controller code for viewing the list of products is <em>very</em> simple.</p>
<pre class="brush: ruby;">
def index
  @products = Product.all
end
</pre>
<p>You&rsquo;ll notice (in the screenshot) that each product has a status &ndash; &lsquo;Available&rsquo; or &lsquo;Coming Soon&rsquo;.  Let&rsquo;s imagine that the user wants to be able to view all Available products.  How might we accomplish that?</p>
<p>The easiest way to do this would be to add a separate route and action which simply filters the products to only those with the correct status.  First, let&rsquo;s add the route.</p>
<pre class="brush: ruby;">
get 'products/available' => 'products#available', :as => 'available_products'
</pre>
<p>Now we only need to add the controller action.</p>
<pre class="brush: ruby;">
def available
  @products = Product.where(:status => 'Available')
  render 'index'
end
</pre>
<p>This certainly works, but there&rsquo;s a cleaner way of doing this.</p>
<h4>Using a named scope</h4>
<p>Instead of using the <em>where</em> method in the controller, we can move the behavior to the controller.  We could create a class method to expose this filter, but Rails has a much nicer way &ndash; <a href="http://apidock.com/rails/ActiveRecord/NamedScope/ClassMethods/scope">named scopes</a>.  Let&rsquo;s see what that looks like.</p>
<pre class="brush: ruby;">
class Product &lt; ActiveRecord::Base
  scope :available, where(:status =&gt; 'Available')
end
</pre>
<p>Now our controller code is much cleaner and easier to read.</p>
<pre class="brush: ruby;">
def available
  @products = Product.available
  render 'index'
end
</pre>
<p>And everything still works exactly as before.  Hurrah!</p>
<h4>Using default scope</h4>
<p>As I mentioned, we also have the functionality to delete a product.  However, we might not want to delete the record out of the database &ndash; we simply want to mark it as deleted.  (There are a number of reasons why we might choose to do this &ndash; for example, we might have transactions linked to a product)</p>
<p>Here&rsquo;s the code for deleting a product.</p>
<pre class="brush: ruby;">
def destroy
  @product = Product.find(params[:id])
  @product.update_attribute(:deleted, true)
  redirect_to products_path
end
</pre>
<p>Let&rsquo;s take another look at our list of products.</p>
<p><img src="https://lh4.googleusercontent.com/-PROjxIA9uTo/TyMNlyi99ZI/AAAAAAAAAlo/-ma9zYNflvI/s800/Screen%2520Shot%25202012-01-27%2520at%25203.48.01%2520PM.png" alt="List containing Deleted Products" class="white-shadow" /></p>
<p>The deleted products are showing up in our regular list!  While this makes sense (since we&rsquo;re simply flagging them as deleted &ndash; not actually deleting them), this is definitely not what we want.  So how do we fix that?  One way would be to update all our queries to include <strong>:deleted => false</strong>.  As you probably guessed, Rails has a neater way of doing this &ndash; using default scope.</p>
<pre class="brush: ruby;">
class Product < ActiveRecord::Base
  default_scope where(:deleted => false)
  scope :available, where(:status => 'Available')
end
</pre>
<p>As the name implies, <strong>default_scope</strong> changes the default list of products being returned.  Our list of products no longer shows deleted products.  For example, <strong>Product.all</strong> will exclude deleted products.  Pretty neat.</p>
<p>What if we want to bypass the default scope and actually get <em>all</em> products?  For example, I might want to have an admin function that lists all unavailable products &ndash; meaning products which have their status set to something other than <strong>Available</strong>.  We can do that by using the <strong>unscoped</strong> method.</p>
<pre class="brush: ruby;">
def unavailable
  @products = Product.unscoped.where('status <> ?', 'Available')
  render 'index'
end
</pre>
<p>Pretty cool.</p>
<h4>Conclusion</h4>
<p>This is one of those pieces of functionality that you probably won&rsquo;t miss until you know it&rsquo;s around.  It can definitely clean up your code and make it a bit more readable.  I would probably be wary of using default_scope, but in certain scenarios it probably makes sense.</p>
<p>If you would like to play around with this code you can find it <a href="https://github.com/Jaco-Pretorius/Scopes">on Github</a>.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/02/scopes-in-rails.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Design vs User Experience</title>
		<link>http://www.jacopretorius.net/2012/02/design-vs-user-experience.html</link>
		<comments>http://www.jacopretorius.net/2012/02/design-vs-user-experience.html#comments</comments>
		<pubDate>Thu, 02 Feb 2012 15:00:20 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Design]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=473</guid>
		<description><![CDATA[One of the topics that keeps popping up around the office is that of design vs user experience. At first glance you might consider them to be the same issue &#8211; both involve presenting data and actions to the user in a way that they find appealing and easy to use. While they address the [...]]]></description>
			<content:encoded><![CDATA[<p>One of the topics that keeps popping up around the office is that of design vs user experience.  At first glance you might consider them to be the same issue &ndash; both involve presenting data and actions to the user in a way that they find appealing and easy to use.  While they address the same issue, I think that these practices do so with a similar, yet different, goal in mind.  The best differentiation might be to say that design is focusing on making the application visually appealing while user experience focuses on making the application easy to use.</p>
<p>There is a <em>massive</em> amount of overlap between these two approaches &ndash; they&rsquo;re implicitly linked.  A large part of making something easy to use is to make it visually appealing, and a large part of making something visually appealing is to make it easy to use!  I try to think of it as two different targets within user interface design.  Design tends to focus on the visual appeal as the end goal, while user experience tends to focus on ease-of-use as the end goal.  The key word here is <em>focus</em> &ndash; I&rsquo;m not saying that design doesn&rsquo;t consider ease-of-use and vice versa.</p>
<p>Why is this distinction important?  While these two approaches have a very similar goal in mind, they follow very different development cycles.  Most design firms will happily create the entire design up front, before the application is anywhere near completion.  User experience &ndash; on the other hand &ndash; can&rsquo;t guarantee the design up front and will evolve the design over time.  The design will evolve as the user experience is refined and improved.</p>
<h4>Case in Point</h4>
<p>The <a href="http://www.sylion.com/flightcard/">Flight Card iPhone app</a> is a good example of this distinction.  It&rsquo;s one of the best-looking apps out there.  Just look at it &ndash; absolutely stunning.  The fonts, colors, layout &ndash; everything is just perfect.  You would think this would be one of the top-selling apps out there.</p>
<p><a href="http://itunes.apple.com/us/app/flight-card/id454594653?mt=8">Not quite</a>.  A mere three stars out of 20 reviews?  What went wrong?  Let&rsquo;s take a look at some of the reviews.</p>
<blockquote><p>This app is quite visually appealing, but it has some issues that make it harder to use.  You cannot add trips more than 3 days in the future (hard when you want to put an literary in).  You can&rsquo;t swipe between flights.</p>
</blockquote>
<blockquote><p>First, the app is stunningly beautiful.  It&rsquo;s simply a joy to look at.  But it&rsquo;s missing some basic functionality.  First, there is no way to swipe between cards.  You need to menu back to list view and choose the next card.  Not so big a deal except for the page dots at the top.  You can tap the dots and they will change as if you&rsquo;re changing cards, but you don&rsquo;t change cards.  And the dots are maddeningly hard to hit.</p>
</blockquote>
<p>It seems that while the visual design is off the charts, the user experience is terrible.  (I haven&rsquo;t used the app, I&rsquo;m only going on what the reviews say)  This is perhaps an extreme example, but I&rsquo;m trying to point out that a bad user experience means a bad app.</p>
<h4>Guarantees</h4>
<p>At the moment the popular approach is the design approach.  No doubt about it.  I think from a client&rsquo;s point of view this is regarded as the &lsquo;safe&rsquo; approach.  Because we start out with the design and do pretty much the entire design up front it&rsquo;s <em>guaranteed</em> &ndash; we have a good idea of what the final application will look like, even though we don&rsquo;t know exactly how it will work.</p>
<p>The user experience approach is perhaps considered to be the &lsquo;risky&rsquo; approach.  We don&rsquo;t have a good idea of what the application will look like &ndash; we only know that we will get much more input into the design <em>and</em> the user experience as the application is built.  We&rsquo;re almost <em>guaranteed</em> to end up with a better user experience, but because we don&rsquo;t have a good idea of what the final application will look like, it feels like we&rsquo;re taking a risk.</p>
<h4>History repeating itself?</h4>
<p>I think we&rsquo;re facing a similar challenge to the one we faced 10 to 15 years ago &ndash; when agile started being introduced.  Clients felt <em>safe</em> with the waterfall approach &ndash; all the planning being done up front meant that we had a very good idea of what the software would look like in the end.  Then agile came along and suggested that the initial idea is less important, and we should rather focus on refining this idea as we go along.</p>
<p>Selling agile 10 years ago was probably similar to selling the user experience today.  I do think that approaching the user interface from a user experience point of view is inevitable &ndash; it simply makes the most sense from both the user&rsquo;s and the client&rsquo;s perspective.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/02/design-vs-user-experience.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Keeping your routes RESTful</title>
		<link>http://www.jacopretorius.net/2012/02/keeping-your-routes-restful.html</link>
		<comments>http://www.jacopretorius.net/2012/02/keeping-your-routes-restful.html#comments</comments>
		<pubDate>Wed, 01 Feb 2012 15:00:57 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Routing]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=456</guid>
		<description><![CDATA[A while ago I blogged about RESTful routing in Rails. While Rails does help us in getting started with RESTful routing, it&#8217;s still very easy to lose your way and make a real mess of your routes. To illustrate this, I&#8217;m going to recreate a problem I recently came across when working on RapidFTR &#8211; [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago I blogged about <a href="http://www.jacopretorius.net/2012/01/restful-routing-in-rails-3.html">RESTful routing in Rails</a>.  While Rails does help us in getting started with RESTful routing, it&rsquo;s still very easy to lose your way and make a real mess of your routes.</p>
<p>To illustrate this, I&rsquo;m going to recreate a problem I recently came across when working on <a href="http://rapidftr.com/">RapidFTR</a> &ndash; one of the social projects I&rsquo;m involved in at ThoughtWorks.</p>
<h4>Let&rsquo;s see some code</h4>
<p>To start off, I&rsquo;m going to extend the example I was using in my <a href="http://www.jacopretorius.net/2012/01/restful-routing-in-rails-3.html">last post</a> about routing.  I&rsquo;m basically managing products &ndash; I&rsquo;ve created a Product model, a Products controller and I have a single entry in my routes configuration.</p>
<pre class="brush: ruby;">
resources :products
</pre>
<p>When I run <strong>rake routes</strong> I get the following list of routes.</p>
<p><img src="https://lh3.googleusercontent.com/-7ysoPpSraCA/TyF0lig_H1I/AAAAAAAAAk0/bIO_rbRQKko/s800/Screen%252520Shot%2525202012-01-26%252520at%25252010.42.17%252520AM.png" alt="List of routes" class="shadow" /></p>
<p>Right, now we have a new requirement &ndash; we need to be able to mark a product as a duplicate.  We might have 2 admin users adding products and somehow we end up adding the same product twice.  We don&rsquo;t want to delete it (since some users might have bought the duplicate, etc) so we&rsquo;re only going to mark it as a duplicate and link it to the non-duplicate product.</p>
<p>At the moment I can perform two actions on each product &ndash; <em>view</em> and <em>edit</em>.  So I now want an additional action &ndash; <em>mark as duplicate</em>.  This should take me to a page where I can select the non-duplicate version of the product.</p>
<h4>Doing it the wrong way</h4>
<p>Sounds easy enough &ndash; I&rsquo;m probably going to need two additional actions on my controller &ndash; one to view the page and one to handle the page being submitted.  To get started, let&rsquo;s add 2 new routes.</p>
<pre class="brush: ruby;">
get 'products/duplicate/:id' =&gt; 'products#new_duplicate', :as =&gt; 'new_duplicate'
post 'products/duplicate/:id' =&gt; 'products#create_duplicate'
</pre>
<p>Running <strong>rake routes</strong> reveals that we now have two additional routes.</p>
<p><img src="https://lh3.googleusercontent.com/-zNp_CkRWK2Q/TyGG56dm-7I/AAAAAAAAAlA/61NMIH7QrNY/s800/Screen%252520Shot%2525202012-01-26%252520at%25252012.00.51%252520PM.png" alt="Two Additional Routes" class="shadow" /></p>
<p>Now I just need to add two method to my Products controller.  This could be done better (moving some of the functionality into the Product model, for example) &ndash; I put all the code into the controller to make it clear what&rsquo;s going on.</p>
<pre class="brush: ruby;"">
  def new_duplicate
    @product = Product.find(params[:id])
    @all_products = Product.where(['id &lt;&gt; ?', params[:id]])
  end

  def create_duplicate
    @product = Product.find(params[:id])
    @duplicate_of = Product.find(params[:duplicate_of_id])
    @product.duplicate = true
    @product.duplicate_of = @duplicate_of.id
    if @product.save
      redirect_to products_path
    else
      render 'new_duplicate'
    end
  end
</pre>
<p>We can mark a product as duplicate!  Hurrah!  Are we done?</p>
<h4>Doing it the right way</h4>
<p>While this code certainly works, I don&rsquo;t think it&rsquo;s really the Rails way of doing it.  It&rsquo;s actually quite easy to end up with too many methods on your controllers &ndash; to avoid this, it helps to think in terms of <em>resources</em>, rather than models and controllers.</p>
<p>In this case, we can think of duplicates as being an additional resource.  So instead of marking an existing product as a duplicate, we&rsquo;re creating a new duplicate resource.  As you&rsquo;ll see, this enables us to use the regular REST verbs &ndash; new, create, edit, update, etc.  Enough talking, let&rsquo;s see how this would actually work!</p>
<p>I&rsquo;m going to start off by changing the routes.  Here I&rsquo;m using a nested resource.</p>
<pre class="brush: ruby;">
resources :products do
  resource :duplicate, :controller =&gt; 'duplicates', &#58;only =&gt; [&#58;new, &#58;create]
end
</pre>
<p>Now our routes look a bit nicer.</p>
<p><img src="https://lh5.googleusercontent.com/-Eed5wwm-Wz0/TyGMkZXy4WI/AAAAAAAAAlQ/S1xmz6ZraOs/s800/Screen%252520Shot%2525202012-01-26%252520at%25252012.25.04%252520PM.png" alt="Nicer routes" class="shadow" /></p>
<p>You&rsquo;ll notice that our route now includes the <strong>:product_id</strong>, instead of just adding an id at the end of the route.  This enforces the idea of a duplicate resource, which is available on product resources.</p>
<p>Now I only need to move my two actions to the newly created Duplicates controller.</p>
<pre class="brush: ruby;">
class DuplicatesController &lt; ApplicationController
  def new
    # same code as before
  end

  def create
    # same code as before
  end
end
</pre>
<h4>More Examples</h4>
<p>I first came across this concept in <a href="http://www.jacopretorius.net/2012/01/book-review-the-rails-3-way.html">The Rails 3 Way</a> &ndash; the common example seems to be in creating sessions.  Instead of adding <strong>login</strong> and <strong>logout</strong> methods to the Users controller, we can think of sessions being a resource.  So we might end up with a Session controller with new, create and destroy actions.  Which actually makes a lot more sense.</p>
<p>If you would like to have a look at the code you can find it <a href="https://github.com/Jaco-Pretorius/routes_app">on Github</a>.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/02/keeping-your-routes-restful.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Checking if variables are defined in Rails Partial Views</title>
		<link>http://www.jacopretorius.net/2012/01/checking-if-variables-are-defined-in-rails-partial-views.html</link>
		<comments>http://www.jacopretorius.net/2012/01/checking-if-variables-are-defined-in-rails-partial-views.html#comments</comments>
		<pubDate>Tue, 31 Jan 2012 15:00:23 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=450</guid>
		<description><![CDATA[During this week I was working on a Rails app when I ran into an issue where I needed to check if a variable has been defined in my view. The standard way to check if a variable is defined in Ruby is with the defined? operator. defined? name # nil name = "Bob" defined? [...]]]></description>
			<content:encoded><![CDATA[<p>During this week I was working on a Rails app when I ran into an issue where I needed to check if a variable has been defined in my view.  The standard way to check if a variable is defined in Ruby is with the <strong>defined?</strong> operator.</p>
<pre class="brush: ruby;">
defined? name
# nil
name = "Bob"
defined? name
# "local-variable"
</pre>
<p>However, I remember reading something in <a href="http://www.jacopretorius.net/2012/01/book-review-the-rails-3-way.html">The Rails 3 Way</a> about not being able to do this in partial views.  Apparently there is an implementation restriction in the rendering system, and we need to use the <strong>local_assigns</strong> hash.</p>
<pre class="brush: xml;">
&lt;% if local_assigns.has_key? :name %&gt;
  &lt;p&gt;&lt;%= name %>&lt;/p&gt;
&lt;% end %&gt;
</pre>
<p>I tried to find out what exactly the restriction is, but the only reference I could find was in the <a href="http://api.rubyonrails.org/classes/ActionView/Base.html">Rails API</a> (under <strong>Passing local variables to sub templates</strong>).</p>
<blockquote><p>Testing using defined? headline will not work. This is an implementation restriction.</p>
</blockquote>
<p>I guess it&rsquo;s just one of those things we need to remember.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/01/checking-if-variables-are-defined-in-rails-partial-views.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Good User Stories</title>
		<link>http://www.jacopretorius.net/2012/01/good-user-stories.html</link>
		<comments>http://www.jacopretorius.net/2012/01/good-user-stories.html#comments</comments>
		<pubDate>Mon, 30 Jan 2012 15:00:05 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[UserStories]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=441</guid>
		<description><![CDATA[Writing good user stories is a real art. I have no doubt that I still have a lot to learn in this regard, but from my limited experience I&#8217;ve definitely seen some user stories which are very good and some which are very bad. One of the discussions which often comes up is whether or [...]]]></description>
			<content:encoded><![CDATA[<p>Writing good user stories is a real art.  I have no doubt that I still have a lot to learn in this regard, but from my limited experience I&rsquo;ve definitely seen some user stories which are very good and some which are very bad.</p>
<p>One of the discussions which often comes up is whether or not something <em>qualifies</em> to be a user story.  More specifically, we might want to introduce a more technical story &ndash; which means we would have to choose between creating a new user story or lumping it with one of the existing stories.  While there is no right or wrong answer, I like the idea of viewing user stories as a planning tool &ndash; we shouldn&rsquo;t be afraid of creating a story to aid in our planning.</p>
<p>While reading the <a href="http://pragprog.com/book/achbd/the-rspec-book">RSpec book</a> I came across a very good test to determine if something qualifies as a user story.  According to Bob Koss a user story must have the following characteristics:</p>
<p><strong>Have business value.</strong>  To me, this is the key when introducing more technical stories.  A feature doesn&rsquo;t necessarily have to directly be used by a user in order to qualify as a story.  It only needs to add business value.</p>
<p><strong>Be testable.</strong>  We need a set outcome, and therefore we need to be able to test that outcome.  Otherwise we don&rsquo;t know when the story is complete.</p>
<p><strong>Be small enough to implement in one iteration.</strong>  This speaks to the need to balance implementation concerns with requirements.  We want to keep the stories small, while still keeping a single piece of functionality as coherent as possible.  As I said, it&rsquo;s a real art.</p>
<p>While creating good user stories is easier in theory than in practice, I really like the idea of evaluating stories against these characteristics.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/01/good-user-stories.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Book Review: Programming Ruby</title>
		<link>http://www.jacopretorius.net/2012/01/book-review-programming-ruby.html</link>
		<comments>http://www.jacopretorius.net/2012/01/book-review-programming-ruby.html#comments</comments>
		<pubDate>Fri, 27 Jan 2012 15:00:02 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=431</guid>
		<description><![CDATA[TLDR Version: This book is incredibly well researched and covers pretty much everything in the Ruby world. While it does have a very good introductory section I think the main benefit to this book is as a reference guide. Programming Ruby is probably the most well-known book in the Ruby world. I guess I&#8217;m a [...]]]></description>
			<content:encoded><![CDATA[<p><img src="https://lh4.googleusercontent.com/-ztc76JmKsGw/THjhLvtFcnI/AAAAAAAAAMI/PaQsCbynquI/s288/ruby_pickaxe%25255B1%25255D.jpg" alt="Programming Ruby" class="white-shadow" style="display: inline; margin: 0 0 15px 15px;" align="right" /><strong>TLDR Version</strong>:  This book is incredibly well researched and covers pretty much everything in the Ruby world.  While it does have a very good introductory section I think the main benefit to this book is as a reference guide.</p>
<p><a href="http://pragprog.com/book/ruby3/programming-ruby-1-9">Programming Ruby</a> is probably the most well-known book in the Ruby world.  I guess I&rsquo;m a little unsure as to the target audience for this book, but based on the amount of recognition it has received it seems to be aimed at pretty much anyone who codes in Ruby.</p>
<p>There are several points in the book where the author gives you the option of skipping past a particularly difficult section, which would be very helpful to newcomers to Ruby will still making it useful to more experienced developers.</p>
<h4>The Good</h4>
<p>I started reading this book to learn Ruby.  I already knew a bit of Ruby at that point, but I wanted to really understand the different concepts and functions of the language.  This book does work pretty well for that approach &ndash; new concepts are introduced in an order that makes it easy to understand and the explanations are straightforward and backed up by good examples.  The first section of the book serves pretty much as a tutorial to the Ruby language.</p>
<p>After reading the first 100 pages or so I abandoned the book and started coding a few simple examples.  I then moved on to <a href="http://projecteuler.net/">Project Euler</a> and solved a fair number of the problems with my new Ruby skills.  This is probably the approach I would recommend &ndash; you can try to read the whole book cover to cover, but you&rsquo;re probably better off writing more code as soon as you feel comfortable.</p>
<p>All the sections in this book are incredibly detailed and well-written.  The amount of research that must have gone into this is <em>very</em> impressive.  I only read the latest version (aimed at Ruby 1.9), but from what I read online almost 50% of the book was modified from the previous version.</p>
<h4>The Bad</h4>
<p>Similar to <a href="http://www.jacopretorius.net/2012/01/book-review-the-rails-3-way.html">The Rails 3 Way</a>, this book is <em>long</em> &ndash; more than 900 pages in all!  I don&rsquo;t think anyone will read this cover-to-cover, but even reading everything up to the reference section is more 400 pages.  While this makes the book great from a reference point of view, I did find everything past the first (tutorial) section to be a bit long-winded.  For example, I don&rsquo;t really see the need to know all 8 aliases for the exit command in IRB (the Interactive Ruby Shell).</p>
<p>I also found some of the examples to be a bit confusing &ndash; especially some of the examples around testing could probably be improved.  (I&rsquo;ve found this to be the case for quite a few books, so maybe I&rsquo;m just overly fussy)</p>
<h4>Conclusion</h4>
<p>This book is incredibly well researched and covers pretty much everything in the Ruby world.  While it does have a very good introductory section I think the main benefit to this book is as a reference guide.</p>
<p>I&rsquo;m a bit in two minds about using a book as a reference guide in today&rsquo;s world where most reference material is simply a Google search away, but from what I&rsquo;ve seen this book would work <em>very</em> well in complementing online reference material.  It&rsquo;s simply a matter of all the topics being very detailed and well researched.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/01/book-review-programming-ruby.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Method Resolution in Ruby</title>
		<link>http://www.jacopretorius.net/2012/01/method-resolution-in-ruby.html</link>
		<comments>http://www.jacopretorius.net/2012/01/method-resolution-in-ruby.html#comments</comments>
		<pubDate>Thu, 26 Jan 2012 15:00:30 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=426</guid>
		<description><![CDATA[While reading the Ruby Pickaxe book I realized that while JavaScript and Ruby are both dynamic languages, they handle method resolution in very different ways. I often use JavaScript as a reference since it&#8217;s the dynamic language I&#8217;m most familiar with. A Simple Example in JavaScript Let&#8217;s first look at a simple JavaScript example. var [...]]]></description>
			<content:encoded><![CDATA[<p>While reading the <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9">Ruby Pickaxe book</a> I realized that while JavaScript and Ruby are both dynamic languages, they handle method resolution in very different ways.  I often use JavaScript as a reference since it&rsquo;s the dynamic language I&rsquo;m most familiar with.</p>
<h4>A Simple Example in JavaScript</h4>
<p>Let&rsquo;s first look at a simple JavaScript example.</p>
<pre class="brush: js;">
var widget = {}

widget.name = "Wobble"
alert(widget.name)

widget.surname = "Bobble"
alert(widget.surname)
</pre>
<p>This will run without any problems.  If you try to get the value of a property that doesn&rsquo;t exist JavaScript will simply return <em>undefined</em>.  If you try to set a property that doesn&rsquo;t exist JavaScript will create that property and set the value.  JavaScript <em>will</em> complain when you try to invoke a method that doesn&rsquo;t exist.</p>
<p>If I recall correctly, dynamic objects in C# 4.0 will function the same way &ndash; you can add properties to a dynamic object without problems, but invoking a method will raise an error.  (It&rsquo;s been a while since I worked in C#, so don&rsquo;t quote me on that)</p>
<p>Ruby doesn&rsquo;t have the concept of properties, so in the following snippet of Ruby code,</p>
<pre class="brush: ruby;">
widget.name = "Wobble"
</pre>
<p>Ruby is actually looking for a method called <strong>name=</strong> and passing the string <strong>&ldquo;Wobble&rdquo;</strong> as a parameter.</p>
<h4>A Simple Example in Ruby</h4>
<p>Let&rsquo;s try the same example in Ruby.</p>
<pre class="brush: ruby;">
class Widget
end

widget = Widget.new
widget.name = "Wobble"
puts widget.name
</pre>
<p><img src="https://lh6.googleusercontent.com/-bN2725uQuos/TxhezYlgEpI/AAAAAAAAAkk/DqAxaWLJDYM/s800/Screen%252520Shot%2525202012-01-19%252520at%2525201.19.21%252520PM.png" alt="NoMethodError" class="shadow" /></p>
<p>As you might expect, Ruby raises an error saying there is no <strong>name=</strong> method on this object.</p>
<p>There are a couple of ways we can get around this limitation.  The simplest is probably to add a <strong>name</strong> accessor to the class.</p>
<pre class="brush: ruby;">
class Widget
end

widget = Widget.new
class Widget
  attr_accessor :name
end
widget.name = "Wobble"
puts widget.name
</pre>
<p>As you can see from the example, Ruby allows us to add accessors for a <strong>@name</strong> instance variable to the class.  The <strong>attr_accessor</strong> method (also called a <em>Macro</em>) will add the necessary methods to access this attribute &ndash; in other words, it&rsquo;s similar to adding the following two methods:</p>
<pre class="brush: ruby;">
def name
  @name
end
def name=(val)
  @name = val
end
</pre>
<p>It&rsquo;s important to know that the <strong>attr_accessor</strong> method doesn&rsquo;t actually create the <strong>@name</strong> instance variable &ndash; it will be created the first time we access it.</p>
<h4>Using method_missing</h4>
<p>Ruby also allows us to define a <strong>method_missing</strong> method (also called a <em>Hook</em>) which will be invoked when a method is not found (as you might deduce from the name).  It has a pretty simple signature:</p>
<pre class="brush: ruby;">
def method_missing(name, *args, &#038;block)
</pre>
<p>So we have the name of the method being called (passed as a <strong>symbol</strong>), the arguments passed as a <a href="http://www.jacopretorius.net/2012/01/splat-operator-in-ruby.html">splat array</a>, and a block.</p>
<p>We can now put this to use to allow us to dynamically access any instance variable.</p>
<pre class="brush: ruby;">
class Widget
  def method_missing(name, *args, &#038;block)
    if name =~ /.*=$/
      instance_variable_set("@" + name.to_s.chop, args[0])
      return args[0]
    end
    if name =~ /.*[^=]$/
      return instance_variable_get("@" + name.to_s)
    end
    raise "I can't figure out what you're trying to do"
  end
end

widget.surname = "Bobble"
puts widget.surname
</pre>
<h4>Conclusion</h4>
<p>I definitely wouldn&rsquo;t advocate using this type of code in a real project, but it&rsquo;s interesting to see what&rsquo;s possible.</p>
<p>If you want to play around with my example you can find it <a href="https://sites.google.com/site/jacopretoriusbloghost/Home/MethodResolution.rb?attredirects=0&amp;d=1">here</a>.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/01/method-resolution-in-ruby.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Test Behavior, Not Implementation</title>
		<link>http://www.jacopretorius.net/2012/01/test-behavior-not-implementation.html</link>
		<comments>http://www.jacopretorius.net/2012/01/test-behavior-not-implementation.html#comments</comments>
		<pubDate>Wed, 25 Jan 2012 15:00:29 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=421</guid>
		<description><![CDATA[While I was reading the Ruby Pickaxe book I came across an example of Unit Testing which &#8211; in my opinion &#8211; is testing implementation rather than behavior. This particular example was used to explain Duck Typing in Ruby, but I think it illustrates that it&#8217;s pretty easy to write tests which end up testing [...]]]></description>
			<content:encoded><![CDATA[<p>While I was reading the <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9">Ruby Pickaxe book</a> I came across an example of Unit Testing which &ndash; in my opinion &ndash; is testing implementation rather than behavior.  This particular example was used to explain Duck Typing in Ruby, but I think it illustrates that it&rsquo;s pretty easy to write tests which end up testing the wrong thing.</p>
<h4>A Simple Example</h4>
<p>In this example we have a simple Customer class.</p>
<pre class="brush: ruby;">
class Customer
  def initialize(first_name, last_name)
    @first_name, @last_name = first_name, last_name
  end

  def append_name_to_file(file)
    file &lt;&lt; @first_name &lt;&lt; " " &lt;&lt; @last_name
  end
end
</pre>
<p>Let&rsquo;s go ahead and write a test for the <strong>append_name_to_file</strong> method.  (I&rsquo;m not a fan of doing testing this way &ndash; we really should write the test <em>first</em>, but let&rsquo;s ignore that for a moment)</p>
<p>One way to test this would be to create an actual temporary file and pass that to the Customer object.</p>
<pre class="brush: ruby;">
class TestCustomer &lt; Test::Unit::TestCase
  def test_customer_writes_full_name_to_file
    customer = Customer.new("Mark","Twain")
    File.open("Output.txt","w") do |file|
      customer.append_name_to_file(file)
    end
    File.open("Output.txt") do |file|
      assert_equal(file.read, "Mark Twain")
    end
    File.delete("Output.txt")
  end
end
</pre>
<p>If I run the test I get the familiar success output.  Hurrah!</p>
<p><img src="https://lh6.googleusercontent.com/-LS10OR8WydY/Txc0a7vXC0I/AAAAAAAAAkM/k9F-YpxrLnc/s800/Screen%252520Shot%2525202012-01-18%252520at%2525204.06.05%252520PM.png" alt="Test Output" class="shadow" /></p>
<h4>That&rsquo;s an ugly test</h4>
<p>Ok, so this test isn&rsquo;t all that pretty.  For one thing, there&rsquo;s quite a lot of work going on just in order to get the test to run and to make sure the file we create is removed at the end.  Even worse, when the test fails the final line of the test will not get executed and the temporary file is never removed!  Using my knowledge of <a href="http://www.jacopretorius.net/2012/01/exceptions-in-ruby.html">Exceptions</a> I can fix that easily enough:</p>
<pre class="brush: ruby;">
class TestCustomer &lt; Test::Unit::TestCase
  def test_customer_writes_full_name_to_file
    begin
      customer = Customer.new("Mark","Twain")
      File.open("Output.txt","w") do |file|
        customer.append_name_to_file(file)
      end
      File.open("Output.txt") do |file|
        assert_equal(file.read, "Mark Twain")
      end
    ensure
      File.delete("Output.txt")
    end
  end
end
</pre>
<p>I&rsquo;ve taken care of the file being left behind when the test fails, but my test code is still pretty ugly.  The author of the Pickaxe book now argues that we don&rsquo;t really need to pass a file to the <strong>append_name_to_file</strong> method &ndash; we simply need to pass something which acts like a file.  How about using a simple array?</p>
<pre class="brush: ruby;">
class TestCustomer &lt; Test::Unit::TestCase
  def test_customer_writes_full_name_to_file
    customer = Customer.new("Charles", "Dickens")
    fake_file = []
    customer.append_name_to_file(fake_file)
    assert_equal(["Charles", " ", "Dickens"], fake_file)
  end
end
</pre>
<p>The test passes, and the code is much simpler.  Are we done?</p>
<h4>The Implementation changes</h4>
<p>Not quite.  Let&rsquo;s say I&rsquo;m working on the Customer class and I decide that I don&rsquo;t really this C++ syntax &ndash; I would prefer to do a simple formatted string.</p>
<pre class="brush: ruby;">
def append_name_to_file(file)
  file &lt;&lt; "#{@first_name} #{@last_name}"
end
</pre>
<p>Notice that I didn&rsquo;t change the <em>behavior</em>, but when I run the test…</p>
<p><img src="https://lh6.googleusercontent.com/-YZVi1lO8HRk/Txc40WGBD4I/AAAAAAAAAkY/L66Y0lH5KQE/s800/Screen%252520Shot%2525202012-01-18%252520at%2525204.24.52%252520PM.png" alt="Broken Test Output" class="shadow" /></p>
<p>Uh-oh.  The problem stems from the fact that we were testing the underlying implementation details, not the behavior.  I didn&rsquo;t check that the Customer object can write to a file, I tested that the Customer object uses the &lt;&lt; method to write 3 different strings to the file object I pass to it.</p>
<p>One way to fix this would be to stop using an array and pass in a string.  Let&rsquo;s try that.</p>
<pre class="brush: ruby;">
class TestCustomer &lt; Test::Unit::TestCase
  def test_customer_writes_full_name_to_file
    customer = Customer.new("Jane", "Austen")
    fake_file = ""
    customer.append_name_to_file(fake_file)
    assert_equal("Jane Austen", fake_file)
  end
end
</pre>
<p>Once again our test passes, and the code is even simpler.  Are we done?  Well, let&rsquo;s see &ndash; another developer is now working on the code and he/she is of the <strong>strong</strong> opinion that the only correct way to write to a file is to use the <strong>File#write</strong> method.</p>
<pre class="brush: ruby;">
def append_name_to_file(file)
  file.write "#{@first_name} #{@last_name}"
end
</pre>
<p>And we&rsquo;re back to square one.  Once again, I didn&rsquo;t change the behavior of the method, but changing the implementation has broken the test.  This is an example of <strong>fragile</strong> unit tests &ndash; tests which break when the code under test is still functionally correct.  This is often a symptom of poorly designed tests.</p>
<h4>What&rsquo;s the Answer?</h4>
<p>So what&rsquo;s the answer?  Should we go back to using a temporary file?  (Using a temporary file worked for all three implementations)  Not really.  I think in this case the problem is actually poor design and we&rsquo;re struggling to test the code as a result.  From an object-orientated perspective it doesn&rsquo;t really make sense for a Customer object to have an <strong>append_name_to_file</strong> method.  Any time you see a method taking an object and then doing something to it, it&rsquo;s usually a code smell.</p>
<p>Let&rsquo;s try and refactor this code.  Instead of the Customer writing something to a file, I think it makes more sense for a Customer to have a method that returns their full name.</p>
<pre class="brush: ruby;">
class Customer
  def initialize(first_name, last_name)
    @first_name, @last_name = first_name, last_name
  end

  def full_name
    "#{@first_name} #{@last_name}"
  end
end
</pre>
<p>Now it&rsquo;s straightforward to write a test.</p>
<pre class="brush: ruby;">
class TestCustomer < Test::Unit::TestCase
  def test_customer_has_full_name
    customer = Customer.new("John", "Milton")
    assert_equal("John Milton", customer.full_name)
  end
end
</pre>
<h4>That&rsquo;s only ONE solution</h4>
<p>Ok, what should we do when we really <em>do</em> need to test interaction with a file?</p>
<p>Unfortunately, there is no silver bullet or golden rule here.  If there was, this wouldn&rsquo;t be an issue.  We could possibly mock the behavior or maybe we really <em>do</em> need to use a temporary file.  The only golden rule (in my opinion) is that we need to make sure we&rsquo;re testing the right thing &ndash; behavior, not implementation.  This leads to better, more maintainable tests &ndash; which will pay massive dividends in the long run.</p>
<p>If you want to play around with my example you can find it <a href="https://sites.google.com/site/jacopretoriusbloghost/Home/DuckTyping.rb?attredirects=0&amp;d=1">here</a>.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/01/test-behavior-not-implementation.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Catch and Throw in Ruby</title>
		<link>http://www.jacopretorius.net/2012/01/catch-and-throw-in-ruby.html</link>
		<comments>http://www.jacopretorius.net/2012/01/catch-and-throw-in-ruby.html#comments</comments>
		<pubDate>Tue, 24 Jan 2012 15:00:17 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=412</guid>
		<description><![CDATA[In my last post I had a look at handling exceptions in Ruby and the functionality around that. In this post I&#8217;m going to look at how Ruby also allows us to unwind a single block of code without raising an exception. I&#8217;ve said before that exceptions should be exceptional &#8211; the functionality in Ruby [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.jacopretorius.net/2012/01/exceptions-in-ruby.html">last post</a> I had a look at handling exceptions in Ruby and the functionality around that.  In this post I&rsquo;m going to look at how Ruby also allows us to unwind a single block of code without raising an exception.  I&rsquo;ve said before that <a href="http://www.jacopretorius.net/2009/10/exceptions-should-be-exceptional.html">exceptions should be exceptional</a> &ndash; the functionality in Ruby offers a lightweight version of this within a single scope.</p>
<h4>Let&rsquo;s see some code</h4>
<p>This is much easier to explain with an example.</p>
<pre class="brush: ruby;">
def get_number
  rand(100)
end

random_numbers = catch (:random_numbers) do
  result = []
  10.times do
    num = get_number
    throw :random_numbers if num < 10
    result << num
  end
  result
end

p random_numbers
</pre>
<p>The <strong>catch</strong> keyword defines a block with a given name.  The block is processed normally until a <strong>throw</strong> statement is encountered.</p>
<p>When a <strong>throw</strong> statement is encountered Ruby will look up the call stack for a <strong>catch</strong> statement with the corresponding symbol.  It will then unwind the call stack up to that point and terminate the block.</p>
<p>In this example the block will have two possible return values.  If no number under 10 is generated the <strong>throw</strong> statement will never execute and the array of random numbers will be returned.  If the <strong>throw</strong> statement <em>does</em> execute the block will simply return <strong>nil</strong>.  Ruby also allows us to override this behavior &ndash; for example, instead of returning <strong>nil</strong> I might choose to return an empty array.  We can do this by specifying a second parameter to the <strong>throw</strong> statement.</p>
<pre class="brush: ruby; highlight: [5];">
random_numbers = catch (:random_numbers) do
  result = []
  10.times do
    num = get_number
    throw(:random_numbers, []) if num < 10
    result << num
  end
  result
end
</pre>
<h4>Performance</h4>
<p>One of the reasons why it&rsquo;s possibly not a good idea to overuse exceptions in your code is performance.  Every time you raise an exception Ruby has to build a stack trace.  If your exceptions are exceptional (as they should be) this won&rsquo;t be a problem.  However, if you&rsquo;re using a large number of exceptions in a tight loop it <em>could</em> have a negative impact on performance.  I&rsquo;m assuming that a <strong>catch-throw</strong> block doesn&rsquo;t need to create a stack trace &ndash; let&rsquo;s see if we can get a rough idea of the performance impact.</p>
<pre class="brush: ruby;">
start = Time.now
10_000_000.times do |i|
  begin
    raise StandardError, "Error #{i}"
  rescue StandardError => error
    error.inspect
  end
end
puts "Raise&#038;Rescue Operation took #{Time.now - start} seconds"

start = Time.now
10_000_000.times do |i|
  catch (:the_loop) do
    throw :the_loop
  end
end
puts "Catch&#038;Throw Operation took #{Time.now - start} seconds"
</pre>
<p><img src="https://lh4.googleusercontent.com/-Y0q4RW_h-xo/TxXvrMtCCtI/AAAAAAAAAkA/dNT8gKtYmE4/s800/Screen%252520Shot%2525202012-01-17%252520at%2525205.00.06%252520PM.png" alt="Performance" class="shadow" /></p>
<p>As I mentioned, these are very rough performance estimates, but there does seem to be a significant performance difference between using exceptions and using a <strong>catch-throw</strong> block.</p>
<h4>Conclusion</h4>
<p>The catch-throw block seems to be a lightweight error handling mechanism &ndash; useful when you want to jump out of a nested construct during normal processing.  The performance figures point to the same conclusion.</p>
<p>If you want to play around with my example you can find it <a href="https://sites.google.com/site/jacopretoriusbloghost/Home/Throw_And_Catch.rb?attredirects=0&amp;d=1">here</a>.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/01/catch-and-throw-in-ruby.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exceptions in Ruby</title>
		<link>http://www.jacopretorius.net/2012/01/exceptions-in-ruby.html</link>
		<comments>http://www.jacopretorius.net/2012/01/exceptions-in-ruby.html#comments</comments>
		<pubDate>Mon, 23 Jan 2012 15:00:58 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=405</guid>
		<description><![CDATA[I like Exceptions. They&#8217;re a very useful concept for raising and handling errors at the correct level without cluttering our code. Coming from C# the way Exceptions work in Ruby are intuitive to me, but there are actually a few extra features which aren&#8217;t available in the .NET world. Basics First To illustrate Exceptions, I&#8217;ve [...]]]></description>
			<content:encoded><![CDATA[<p>I like Exceptions.  They&rsquo;re a very useful concept for raising and handling errors at the correct level without cluttering our code.  Coming from C# the way Exceptions work in Ruby are intuitive to me, but there are actually a few extra features which aren&rsquo;t available in the .NET world.</p>
<h4>Basics First</h4>
<p>To illustrate Exceptions, I&rsquo;ve created a very simple class that simulates interaction with a remote resource.</p>
<pre class="brush: ruby;">
class RemoteResource

  def initialize
    @users = Hash.new
    @users["Malcolm"] = "password1"
    @users["Angus"] = "password1"
    @users["Phil"] = "password1"
    @users["Cliff"] = "password1"
    @users["Brian"] = "password1"
  end

  def create_connection(username,password,secure=false)
    unless @users[username] &#038;&#038; @users[username] == password
      raise ArgumentError.new("Invalid username or password")
    end
    raise SecurityError.new("Secure connections are unavailable") if secure
    @connection_initialized = true
  end

  def get_resource
    unless @connection_initialized
      raise SecurityError.new("A connection has not been established")
    end
    raise StandardError.new("An unknown error has occurred") if rand(3) == 0
    "Widget #{rand(11)}"
  end

end
</pre>
<p>Let&rsquo;s see what happens when we raise a simple exception.</p>
<pre class="brush: ruby;">
remote_resource = RemoteResource.new
remote_resource.create_connection("Kurt","password1")
</pre>
<p><img src="https://lh3.googleusercontent.com/-E6mAmB3ka6c/TxXHTMydi9I/AAAAAAAAAgU/4rGoDDKtfVs/s800/Screen%252520Shot%2525202012-01-17%252520at%2525202.08.01%252520PM.png" alt="Terminal Output" class="shadow" /></p>
<p>As you would probably expect, our little application exits immediately and reports the type and message of the exception that was raised.  So far so good.</p>
<h4>Handling Exceptions</h4>
<p>Let&rsquo;s see how we handle an exception.</p>
<pre class="brush: ruby;">
remote_resource = RemoteResource.new
begin
  remote_resource.create_connection("Kurt","password1")
rescue Exception => error
  print "Could not create connection: #{error}\n"
end
</pre>
<p>Pretty neat.  This is probably not very good code, since we&rsquo;re handling the global <strong>Exception</strong> class which is bad practice &ndash; we should try to handle only specific Exception classes.</p>
<pre class="brush: ruby;">
remote_resource = RemoteResource.new
begin
  remote_resource.create_connection("Malcolm","password1", true)
rescue ArgumentError => argument_error
  print "Could not create connection: #{argument_error}\n"
rescue SecurityError => security_error
  print "Could not create secure connection: #{security_error}\n"
end
</pre>
<p><img src="https://lh5.googleusercontent.com/-q66mlIpWi3k/TxXJEmsBcBI/AAAAAAAAAgg/YoGnJ2mkF8k/s800/Screen%252520Shot%2525202012-01-17%252520at%2525202.16.05%252520PM.png" alt="Terminal Output" class="shadow" /></p>
<p>We can also handle multiple Exception classes in one block.</p>
<pre class="brush: ruby;">
remote_resource = RemoteResource.new
begin
  remote_resource.create_connection("Malcolm","password1", true)
rescue ArgumentError, SecurityError => error
  print "Could not create connection: #{error}\n"
end
</pre>
<h4>Ensure code is executed</h4>
<p>We can also ensure that a block of code is executed &ndash; for example, we might want to add some logging code around the accessing of the remote resource.</p>
<pre class="brush: ruby;">
remote_resource = RemoteResource.new
remote_resource.create_connection("Malcolm","password1")
print "Connection created at #{Time.now}\n"
begin
  result = remote_resource.get_resource
rescue SecurityError => error
  print "Error using connection: #{error}\n"
ensure
  print "Resource released at #{Time.now}\n"
end
</pre>
<p><img src="https://lh5.googleusercontent.com/-3_EWfQ3e1Tk/TxXLC-t09uI/AAAAAAAAAgs/Xw5zbqQ1rfE/s800/Screen%252520Shot%2525202012-01-17%252520at%2525202.24.27%252520PM.png" alt="Terminal Output" class="shadow" /></p>
<p>As the name implies, <strong>ensure</strong> ensures that a certain block of code is executed &ndash; as you can see from the output.  C# users will immediately recognize a strong similarity to the <strong>finally</strong> keyword in .NET.</p>
<p>Ruby also introduces the <strong>else</strong> clause &ndash; this will only execute if no errors were encountered.  The <strong>else</strong> clause must go before the <strong>ensure</strong> clause and after any <strong>rescue</strong> clauses.</p>
<pre class="brush: ruby;">
remote_resource = RemoteResource.new
remote_resource.create_connection("Angus","password1")
print "Connection created at #{Time.now}\n"
begin
  result = remote_resource.get_resource
rescue SecurityError => error
  print "Error using connection: #{error}\n"
else
  print "The connection was accessed without any errors\n"
ensure
  print "Resource released at #{Time.now}\n"
end
</pre>
<p>This is probably quite useful in certain scenarios.</p>
<h4>Retry the block</h4>
<p>Ruby also allows us to correct the cause of the exception and retry the block.  For example, since my remote resource is a little unstable I might choose to retry the block until the resource is returned.</p>
<pre class="brush: ruby;">
remote_resource = RemoteResource.new
remote_resource.create_connection("Angus","password1")
begin
  result = remote_resource.get_resource
  print "#{result}\n"
rescue SecurityError => error
  print "Error using connection: #{error}\n"
rescue StandardError => error
  print "Error accessing remote resource - #{error}\n"
  retry
end
</pre>
<p><img src="https://lh5.googleusercontent.com/-h9PyhCr8DIc/TxXQKuqBt1I/AAAAAAAAAhA/bpPbLTxq5LY/s800/Screen%252520Shot%2525202012-01-17%252520at%2525202.45.01%252520PM.png" alt="Terminal Output" class="shadow" /></p>
<p>As you might imagine, it&rsquo;s one of the easiest ways of creating an infinite loop so use with care.  In fact, I actually managed to create an infinite loop while writing this post!</p>
<h4>Conclusion</h4>
<p>As someone coming from C# the Exception handling in Ruby seems very intuitive to me.  The additional functionality (<strong>else</strong> and <strong>retry</strong>) could also be very useful in certain scenarios.</p>
<p>If you want to play around with my example you can find it <a href="https://sites.google.com/site/jacopretoriusbloghost/Home/Exceptions.rb?attredirects=0&amp;d=1">here</a>.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/01/exceptions-in-ruby.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

