<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns: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/" version="2.0">

<channel>
	<title>P is for Programming</title>
	
	<link>http://www.jacopretorius.net</link>
	<description />
	<lastBuildDate>Wed, 15 Feb 2012 15:00:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/PForProgramming" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="pforprogramming" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Closures in Ruby</title>
		<link>http://www.jacopretorius.net/2012/02/closures-in-ruby.html</link>
		<comments>http://www.jacopretorius.net/2012/02/closures-in-ruby.html#comments</comments>
		<pubDate>Wed, 15 Feb 2012 15:00:30 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=526</guid>
		<description><![CDATA[The complete title for this post is: Closures in Ruby make my head hurt. I&#8217;ve had a rough idea of how closures work (from my JavaScript experience), but I just watched An Introduction Blocks, Lambdas and Closures in Ruby and I&#8217;ve realized that I my knowledge is a mere drop in the ocean. I would [...]]]></description>
			<content:encoded><![CDATA[<p>The complete title for this post is: Closures in Ruby make my head hurt.  I&rsquo;ve had a rough idea of how closures work (from my JavaScript experience), but I just watched <a href="http://www.youtube.com/watch?v=VBC-G6hahWA">An Introduction Blocks, Lambdas and Closures in Ruby</a> and I&rsquo;ve realized that I my knowledge is a mere drop in the ocean.</p>
<p>I would highly recommend this video to anyone who is looking for a better understanding of these three topics.</p>
<p>To get started, let&rsquo;s look at a very basic example of a closure.</p>
<pre class="brush: ruby;">
def run_proc(p)
  p.call
end

name = "Bob"
puts_name = proc { puts name }
run_proc puts_name
# Bob
</pre>
<p>This code obviously works, but keep in mind what is really going on here &ndash; we are creating a proc which references the <em>name</em> variable.  We then execute the block in the context of the run_proc method, where the <em>name</em> variable doesn&rsquo;t exist!  So this little snippet of code is actually doing something really complex.</p>
<p>Ruby actually attaches the <em>name</em> variable to the block which then makes it available when we want to use it!  This is called a <strong>closure</strong>.</p>
<p>Let&rsquo;s look at another example, using a lambda instead of a proc.</p>
<pre class="brush: ruby;">
def run_lambda(l, val)
  l[val]
end

a = 5
multiply_by_a = lambda do |x|
  x * a
end

puts run_lambda(multiply_by_a, 2)
# 10
</pre>
<p>Again, this works as we expected it to &ndash; the <em>a</em> variable is attached to the lambda and can be accessed when the lambda is executed.  Now we can try something really strange.</p>
<pre class="brush: ruby;">
def run_lambda(l, val)
  l[val]
end

a = 5
multiply_by_a = lambda do |x|
  x * a
end

a = 10
puts run_lambda(multiply_by_a, 3)
# 30
</pre>
<p>What this snippet is illustrating is that Ruby closures actually attach a reference to the variable being used.  That&rsquo;s why we can update the a variable and have the lambda use the updated value &ndash; this is actually different to how a number of other languages implement closures.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/02/closures-in-ruby.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Alias class methods in Ruby</title>
		<link>http://www.jacopretorius.net/2012/02/alias-class-methods-in-ruby.html</link>
		<comments>http://www.jacopretorius.net/2012/02/alias-class-methods-in-ruby.html#comments</comments>
		<pubDate>Tue, 14 Feb 2012 15:10:41 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=517</guid>
		<description><![CDATA[Yesterday I came across a problem where one possible solution was to alias a class method. I&#8217;ve blogged about aliasing methods before, but I didn&#8217;t know how to do this for class methods. Turns out, it&#8217;s pretty simple &#8211; the syntax is just a bit different. class Person def self.all %w{ Bob Steve } end [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I came across a problem where one possible solution was to alias a class method.  I&rsquo;ve blogged about <a href="http://www.jacopretorius.net/2012/01/alias-methods-in-ruby.html">aliasing methods</a> before, but I didn&rsquo;t know how to do this for class methods.</p>
<p>Turns out, it&rsquo;s pretty simple &ndash; the syntax is just a bit different.</p>
<pre class="brush: ruby;">
class Person
  def self.all
    %w{ Bob Steve }
  end

  class << self
    alias_method &#58;old_all, :all

    def all
      old = self.old_all
      old << "Peter"
      old << "Owen"
    end
  end
end

p Person.old_all
# ["Bob", "Steve"]
p Person.all
# ["Bob", "Steve", "Peter", "Owen"]
</pre>
<p>Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/02/alias-class-methods-in-ruby.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Zip in Ruby</title>
		<link>http://www.jacopretorius.net/2012/02/using-zip-in-ruby.html</link>
		<comments>http://www.jacopretorius.net/2012/02/using-zip-in-ruby.html#comments</comments>
		<pubDate>Mon, 13 Feb 2012 15:00:26 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=513</guid>
		<description><![CDATA[Last week I blogged about the Enumerable module in Ruby and specifically mentioned the Enumerable#zip method. I didn&#8217;t think the zip method was particularly useful, but I have actually found a few extra features which are very nice. To refresh your memory, the zip method will combine the elements of two different arrays. names = [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I blogged about the <a href="http://www.jacopretorius.net/2012/02/exploring-enumerable-in-ruby.html">Enumerable module in Ruby</a> and specifically mentioned the <strong>Enumerable#zip</strong> method.  I didn&rsquo;t think the <strong>zip</strong> method was particularly useful, but I have actually found a few extra features which are very nice.</p>
<p>To refresh your memory, the <strong>zip</strong> method will combine the elements of two different arrays.</p>
<pre class="brush: ruby;">
names = %w{ Michael Tobias Ann Barry }
surnames = %w{ Bluth Funke Veal Zuckerkorn }

p names.zip(surnames)
# [["Michael", "Bluth"], ["Tobias", "Funke"], ["Ann", "Veal"], ["Barry","Zuckerkorn"]]
</pre>
<p>I also mentioned that you can actually combine multiple arrays in this way.</p>
<pre class="brush: ruby;">
names = %w{ Michael Tobias Ann Barry }
surnames = %w{ Bluth Funke Veal Zuckerkorn }
ages = [ 42, 44, 17, 49 ]

p names.zip(surnames, ages)
# [["Michael", "Bluth", 42], ["Tobias", "Funke", 44], ["Ann", "Veal", 17], ["Barry","Zuckerkorn", 49]]
</pre>
<p>What I didn&rsquo;t realize was that you can very easily create a hash mapping between two arrays when you use this method in combination with the [] method on the Hash class.</p>
<pre class="brush: ruby;">
names = %w{ Michael Tobias Ann Barry }
surnames = %w{ Bluth Funke Veal Zuckerkorn }

p Hash[names.zip(surnames)]
# {"Tobias"=>"Funke", "Michael"=>"Bluth", "Ann"=>"Veal", "Barry"=>"Zuckerkorn"}
</pre>
<p>This is a pretty cool trick.  Lastly, we can actually pass a <strong>block</strong> to the <strong>zip</strong> method &ndash; the block will execute exactly the same as an <strong>each</strong> block executed on the result.</p>
<pre class="brush: ruby;">
names = %w{ Michael Tobias Ann Barry }
surnames = %w{ Bluth Funke Veal Zuckerkorn }
ages = [ 42, 44, 17, 49 ]

names.zip(surnames, ages) do |elem|
  p elem
end
# ["Michael", "Bluth", 42]
# ["Tobias", "Funke", 44]
# ["Ann", "Veal", 17]
# ["Barry", "Zuckerkorn", 49]
</pre>
<p>I still don&rsquo;t really get the name of the method, but it&rsquo;s pretty useful.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/02/using-zip-in-ruby.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Presence of a substring in Ruby</title>
		<link>http://www.jacopretorius.net/2012/02/presence-of-a-substring-in-ruby.html</link>
		<comments>http://www.jacopretorius.net/2012/02/presence-of-a-substring-in-ruby.html#comments</comments>
		<pubDate>Fri, 10 Feb 2012 15:00:22 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=504</guid>
		<description><![CDATA[I just watched the &#8216;Ruby Trick Shots&#8217; video. This video basically shows a bunch of very useful methods, libraries and techniques you might be unaware of. If you&#8217;re a Ruby developer I would highly recommend it. One of the &#8216;tricks&#8217; I found particularly interesting was checking for a substring. Let&#8217;s say we have the following [...]]]></description>
			<content:encoded><![CDATA[<p>I just watched the <a href="http://rubyreloaded.com/trickshots/">&lsquo;Ruby Trick Shots&rsquo; video</a>.  This video basically shows a bunch of very useful methods, libraries and techniques you might be unaware of.  If you&rsquo;re a Ruby developer I would highly recommend it.</p>
<p>One of the &lsquo;tricks&rsquo; I found particularly interesting was checking for a substring.  Let&rsquo;s say we have the following string, and we want to check if it contains the word &lsquo;test&rsquo;.</p>
<pre class="brush: ruby;">
s = "this is a test"
</pre>
<p>The normal way of doing this would be to use a Regular expression.</p>
<pre class="brush: ruby;">
if s =~ /test/
  puts "Found the substring"
end
</pre>
<p>I know many developers absolutely <em>love</em> Regular expressions, but I&rsquo;m not a fan.  I find them difficult to maintain and not intuitive at all.  (This is perhaps a discussion for another day)  In any case, a nice and easy way of testing to see if a substring exists is with the following snippet.</p>
<pre class="brush: ruby;">
if s["test"]
  puts "Found the substring"
end
</pre>
<p>Here we are actually calling the [] method on the string class &ndash; which will simply return <strong>nil</strong> if the specified string doesn&rsquo;t exist.  As far as I can tell the only downside here is that we can&rsquo;t ignore the case of the substring.  If we want to do that we&rsquo;ll have to revert back to the Regular expression.</p>
<pre class="brush: ruby;">
if s =~ /Test/i
  puts "Found the substring"
end
</pre>
<p>The [] method will happily accept a Regular expression, but I think it&rsquo;s probably better to stick with this syntax.  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/02/presence-of-a-substring-in-ruby.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>For vs Each in Ruby</title>
		<link>http://www.jacopretorius.net/2012/02/for-vs-each-in-ruby.html</link>
		<comments>http://www.jacopretorius.net/2012/02/for-vs-each-in-ruby.html#comments</comments>
		<pubDate>Thu, 09 Feb 2012 15:00:42 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=500</guid>
		<description><![CDATA[One of the discussions I was involved in at RubyFuza revolved around the difference between for and each in Ruby. There is only a subtle difference around scoping, but I think it&#8217;s an important distinction because it reveals some important aspects of Ruby. The for loop is a syntax construct, similar to the if statement. [...]]]></description>
			<content:encoded><![CDATA[<p>One of the discussions I was involved in at <a href="http://www.jacopretorius.net/2012/02/rubyfuza-2012.html">RubyFuza</a> revolved around the difference between <strong>for</strong> and <strong>each</strong> in Ruby.  There is only a subtle difference around scoping, but I think it&rsquo;s an important distinction because it reveals some important aspects of Ruby.</p>
<p>The <strong>for</strong> loop is a syntax construct, similar to the <strong>if</strong> statement.  Whatever variable you define in the <strong>for</strong> loop will remain after the loop as well.</p>
<pre class="brush: ruby;">
list = %w{ google yahoo bing duckduckgo }

for engine in list
  # do something with engine
end
puts engine
# duckduckgo
</pre>
<p>On the other hand, <strong>Enumerable#each</strong> is a <strong>method</strong> which receives a <strong>block</strong>.  A block introduces a new lexical scope, so any variables we declare in the block will not be around after the block executes.</p>
<pre class="brush: ruby;">
list = %w{ google yahoo bing duckduckgo }

list.each do |engine|
  # do something with engine
end
puts engine
# NameError: undefined local variable or method ‘engine’
</pre>
<p>The <strong>for</strong> loop is very rarely used in Ruby.  I don&rsquo;t think it&rsquo;s <em>that</em> bad to be using it, but the <strong>each</strong> method does decrease the possibility of side effects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/02/for-vs-each-in-ruby.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exploring Enumerable in Ruby</title>
		<link>http://www.jacopretorius.net/2012/02/exploring-enumerable-in-ruby.html</link>
		<comments>http://www.jacopretorius.net/2012/02/exploring-enumerable-in-ruby.html#comments</comments>
		<pubDate>Wed, 08 Feb 2012 15:00:06 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=496</guid>
		<description><![CDATA[One of talks I was able to attend at last week&#8217;s RubyFuza conference was by Andrew Timberlake titled &#8216;Ruby&#8217;s Hidden Gems&#8217;. It basically revolved around examples of how we often implement something in Ruby that is already supported in the API. I&#8217;ve blogged about this before &#8211; how I found myself writing C# code, but [...]]]></description>
			<content:encoded><![CDATA[<p>One of talks I was able to attend at last week&rsquo;s <a href="http://www.jacopretorius.net/2012/02/rubyfuza-2012.html">RubyFuza conference</a> was by <a href="http://andrewtimberlake.com/">Andrew Timberlake</a> titled &lsquo;Ruby&rsquo;s Hidden Gems&rsquo;.  It basically revolved around examples of how we often implement something in Ruby that is already supported in the API.  I&rsquo;ve <a href="http://www.jacopretorius.net/2011/11/first-steps-with-ruby-from-a-c-guy.html">blogged about this before</a> &ndash; how I found myself writing C# code, but doing it in Ruby.</p>
<p>A few of the example revolved around the Enumerable module, so I&rsquo;m going to take a look at some of the built-in methods within this module.  We also discussed how it&rsquo;s good practice to try and implement these methods yourself, so I&rsquo;m going to try that.</p>
<h4>Enumerable#any?</h4>
<p>Let&rsquo;s say you have an array of numbers and you want to test if any of them are higher than 10.  You might write the following:</p>
<pre class="brush: ruby;">
arr = *1..15

higher_than_10 = false
arr.each do |elem|
  higher_than_10 = elem &gt; 10
  break if higher_than_10
end
</pre>
<p>Which is rather ugly and unnecessary.  You could also try several of the other Enumerable methods to get to the same result:</p>
<pre class="brush: ruby;">
higher_than_10 = arr.select { |elem| elem &gt; 10 }.length &gt; 0
higher_than_10 = arr.count { |elem| elem &gt; 10 } &gt; 0
</pre>
<p>Which seems better, until you realize that you should be using the <strong>Enumerable#any?</strong> method:</p>
<pre class="brush: ruby;">
higher_than_10 = arr.any? { |elem| elem &gt; 10 }
</pre>
<p>Implementing the <strong>any?</strong> method is pretty straightforward.</p>
<pre class="brush: ruby;">
def any?(list)
  list.each do |elem|
    return true if yield(elem)
  end
  false
end
</pre>
<h4>Enumerable#all?</h4>
<p>As the name implies, this method applies a block to the collection and returns true if the block evaluates to true for all values.</p>
<pre class="brush: ruby;">
all_higher_than_10 = arr.all? { |elem| elem &gt; 10 }
</pre>
<p>What might the <strong>Enumerable#all?</strong> method look like if we tried to implement it?</p>
<pre class="brush: ruby;">
def all?(list)
  list.each do |elem|
    return false unless yield(elem)
  end
  true
end
</pre>
<p>Pretty neat.</p>
<h4>Enumerable#take_while</h4>
<p>I can&rsquo;t really imagine a scenario where this method would be useful, but I guess it&rsquo;s good to know that it exists.</p>
<pre class="brush: ruby;">
first_few = arr.take_while { |elem| elem &lt; 25 }
</pre>
<p>What might the <strong>Enumerable#take_while</strong> method look like if we had to implement it ourselves?</p>
<pre class="brush: ruby;">
def take_while(list)
  res = []
  list.each do |elem|
    return res unless yield(elem)
    res &lt;&lt; elem
  end
end
</pre>
<p>I feel there should be a nicer way of implementing this, but I can&rsquo;t really see it.</p>
<h4>Enumerable#zip</h4>
<p>Once in a while you might find yourself in a situation where you&rsquo;re working with multiple arrays of the same length containing corresponding values.  For example, you might have two arrays &ndash; one with a list of names and one with a list of surnames.  This usually leads to some pretty messy code when we try to iterate over this.</p>
<pre class="brush: ruby;">
names = %w{ Bob Steve Dave Peter }
surnames = %w{ Miller Scott Parker Smith }
for i in 0...names.length do
  puts "#{names[i]} #{surnames[i]}"
end
# Bob Miller
# Steve Scott
# Dave Parker
# Peter Smith
</pre>
<p>It&rsquo;s not all that often that we need to use a for loop in Ruby &ndash; we can get rid of it by using the <strong>Enumerable#each_with_index</strong> method.</p>
<pre class="brush: ruby;">
names.each_with_index do |name, i|
  puts "#{name} #{surnames[i]}"
end
# Bob Miller
# Steve Scott
# Dave Parker
# Peter Smith
</pre>
<p>This is still pretty messy &ndash; luckily Ruby has the <strong>Enumerable#zip</strong> method.  This converts each element to an array and then merges each array with corresponding elements from the arguments.  (You can actually pass in multiple argument arrays, which makes it a bit trickier)</p>
<pre class="brush: ruby;">
names = %w{ Bob Steve Dave Peter }
surnames = %w{ Miller Scott Parker Smith }

p names.zip(surnames)
# [["Bob", "Miller"], ["Steve", "Scott"], ["Dave", "Parker"], ["Peter", "Smith"]]
</pre>
<p>Ruby will substitute <em>nil</em> if there are no corresponding elements in the arguments.  Can we try and implement <strong>Enumerable#zip</strong> ourselves?</p>
<pre class="brush: ruby;">
def zip(list, *args)
  res = []
  list.each_with_index do |elem, i|
    elem_arr = elem.to_a
    args.each do |arg_arr|
      elem_arr &lt;&lt; arg_arr[i]
    end
    res &lt;&lt; elem_arr
  end
  res
end
</pre>
<p>I&rsquo;m not too crazy about the double loop &ndash; if you have a better implementation, I would love to see it!  Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/02/exploring-enumerable-in-ruby.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RubyFuza 2012</title>
		<link>http://www.jacopretorius.net/2012/02/rubyfuza-2012.html</link>
		<comments>http://www.jacopretorius.net/2012/02/rubyfuza-2012.html#comments</comments>
		<pubDate>Tue, 07 Feb 2012 15:00:09 +0000</pubDate>
		<dc:creator>Jaco Pretorius</dc:creator>
				<category><![CDATA[Conferences]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jacopretorius.net/?p=489</guid>
		<description><![CDATA[Last week I was lucky enough to be able to attend the RubyFuza conference in Cape Town, South Africa. As far as I know this is the biggest Ruby conference in South Africa and when ThoughtWorks offered me the chance to attend I grabbed it with both hands (even though it&#8217;s a long flight from [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I was lucky enough to be able to attend the <a href="http://rubyfuza.org/">RubyFuza</a> conference in Cape Town, South Africa.  As far as I know this is the biggest Ruby conference in South Africa and when ThoughtWorks offered me the chance to attend I grabbed it with both hands (even though it&rsquo;s a <em>long</em> flight from New York).</p>
<p>The conference took place over two days and had close to 100 delegates attending.  Obviously this is nowhere near the size of some of the conferences we have in the US, but considering that this is only the second iteration of the conference I consider it a smashing success.  If you&rsquo;re a Ruby developer in South Africa make sure you attend it next year.  (The conference has a <a href="http://twitter.com/#!/rubyfuza">twitter account</a> for updates)</p>
<p>I was quite surprised by the number of international speakers &ndash; out of the 20 speakers only 12 were based in South Africa.  They key note was done by <a href="http://svenfuchs.com/">Sven Fuchs</a> who is very well-known in the open source community.  There was a good mixture of technologies being discussed (including two relating to CoffeeScript) as well as general talks on structuring and abstracting code.  I predict in a few years the popularity of the conference will require multiple tracks to be introduced which usually improves the overall quality of presentations even further.</p>
<p>I would definitely recommend the conference to any Ruby developer (no matter what you level of experience) and if you feel up to it &ndash; try and present.  The conference also has lightning talks (which are usually less than 5 minutes) if you only want to wet your feet with a very brief presentation.</p>
<p>As part of the conference there was also a <a href="http://coderetreat.com/">Code Retreat</a> &ndash; basically a day of talking about the right way of writing code and pairing with different developers.  I really enjoyed this part of the conference as it really opens your eyes to different ways of thinking about practices like TDD.</p>
<p>As I said, I would highly recommend the conference.  It&rsquo;s a great way to learn about different technologies in the Ruby world and meet other developers.  Cape Town in February &ndash; what could be better?</p>
<p><img src="https://lh5.googleusercontent.com/-07k67GkRiX0/TzBJiYrLNKI/AAAAAAAAAl0/T3Yy5PMob3k/s400/Photo%2520Feb%252003%252C%252010%252056%252059%2520AM.jpg" alt="Cape Town" class="shadow" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jacopretorius.net/2012/02/rubyfuza-2012.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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 model.  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>
	</channel>
</rss>

