<?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>Justin Spradlin</title>
	<atom:link href="http://www.justinspradlin.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.justinspradlin.com</link>
	<description>Coding and such...</description>
	<lastBuildDate>Sun, 06 Mar 2011 06:19:59 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Book Review: Eloquent Ruby</title>
		<link>http://www.justinspradlin.com/reviews/book-review-eloquent-ruby/</link>
		<comments>http://www.justinspradlin.com/reviews/book-review-eloquent-ruby/#comments</comments>
		<pubDate>Sun, 06 Mar 2011 06:16:23 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[Reviews]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=96</guid>
		<description><![CDATA[I can&#8217;t even begin to imagine how difficult it would be to write a book covering such an in-depth topic as the Ruby Programming language. Add to that a target audience with a widely diverse range of skills and the tasks seems to be out right impossible. Fortunately for us mere mortals Russ Olsen has [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.justinspradlin.com/uncategorized/book-review-eloquent-ruby"><img class="rev_left" src="http://www.justinspradlin.com/images/er.jpg" alt="Eloquent Ruby" /></a>I can&#8217;t even begin to imagine how difficult it would be to write a book covering such an in-depth topic as the Ruby Programming language. Add to that a target audience with a widely diverse range of skills and the tasks seems to be out right impossible. Fortunately for us mere mortals Russ Olsen has taken on this challenge and surpassed my high expectations in his second book, Eloquent Ruby.</p>
<p>The first part of the book is for the Ruby newbies, but takes an interesting deviation from most programming books. Instead of focusing simply on the syntax and language libraries, Eloquent Ruby focuses on the community aspect of the Ruby programming language. Each programming community has its own style and norms and without a lot of direction and practice, these style and norms can be difficult to learn. The Ruby community is heavily opinionated and Russ&#8217;s book does a great job of explaining these opinions and their manifestation in many Ruby codebases.</p>
<p><span id="more-96"></span></p>
<p>In Part Two of Eloquent Ruby, Olsen dives into the core concepts and building blocks of the Ruby programming language. This section of the book covers the everyday usage patterns and common best practices when working with Ruby&#8217;s classes, iterators, blocks, and modules.</p>
<p>The power and flexibility of Ruby is put on full display in Part Three of Russ&#8217;s book. Newcomers to Ruby are often mystified by Ruby code that appears to be doing magical things like dynamically adding methods to a class. In this section, Russ pulls back the curtain and explains the magic that is metaprogramming. Those unfamiliar with the concept may find the topic confusing at first, but Olsen breaks it down in a way that is easy to understand. This section thoroughly covers Ruby&#8217;s <code>method_missing</code> hook and how to open classes to add your own customizations.</p>
<p>In the last section Russ ties a lot of the concepts of the book together through a discussion on how Ruby can be used to create Domain Specific Languages (DSLs). As a bonus Russ finishes the book with a chapter on how to package your code into a gem (Ruby library) and a chapter on the different Ruby Implementations.</p>
<p>At almost 400 pages I feared Eloquent Ruby would take a while to read, but I was pleasantly surprised at the pace at which I made it through the book. Even though the book was a quick read it still felt as if I had gained a lot of new knowledge after its completion. I credit the speed reading and depth of understanding to Olsen&#8217;s writing style. The book is broken up into 30 concise chapters that each focus on a specific topic. This makes the book&#8217;s information very easy to digest.</p>
<p>Following a similar pattern from his first book, Design Patterns in Ruby, each chapter of Eloquent Ruby describes code examples &#8220;In the Wild&#8221; where Olsen discusses code snippets from open source projects using the topics covered within that chapter. In my opinion giving &#8220;real world&#8221; code examples was a great way to prove the relevance of the information covered in the book. Overall, Eloquent Ruby was a great read and I&#8217;d highly recommend it to Rubyist at all skill levels.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/reviews/book-review-eloquent-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Introducing GMoney – A RubyGem for Interacting with the Google Finance API</title>
		<link>http://www.justinspradlin.com/programming/introducing-gmoney-a-rubygem-for-interacting-with-the-google-finance-api/</link>
		<comments>http://www.justinspradlin.com/programming/introducing-gmoney-a-rubygem-for-interacting-with-the-google-finance-api/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 06:00:30 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=87</guid>
		<description><![CDATA[That's why I wrote GMoney, a <a href="http://docs.rubygems.org/">RubyGem</a> for interacting with the <a href="http://code.google.com/apis/finance/">Google Finance API]]></description>
			<content:encoded><![CDATA[<div class="blockquote"> 
<p><strong>Update March 03, 2010:</strong></p><p>Due to changes in the Google Finance API only GMoney gem versions >= 0.4.3 are working.  If you run <code>gem update gmoney</code> to get the latest version or install the gem from scratch you will be fine.</p>
</div>
<p>Let&#8217;s pretend the year is 2007 and I have a close &#8220;friend&#8221; who is really excited about the upcoming <a href="http://www.fifa.com/worldcup/">2010 World Cup</a>.  My friend is not too naive and realizes that airfare to Africa, lodging, tickets to the games, and Safaris are all very expensive.  My friend has a little extra cash to save each month and with a three year time horizon he figures he can stow away a little money in a moderately aggressive mutual fund in order to take advantage of some growth opportunities.</p>
<p>Unfortunately for my friend the next two years would be some of the <a href="http://en.wikipedia.org/wiki/Financial_crisis_of_2007%E2%80%932010">worst the world economy has ever seen</a>.  Like many people, my friend <a href="http://idioms.thefreedictionary.com/took+a+bath#MainTxt">took a bath</a> on his investments and his hopes and dreams of going to the World Cup went down the drain along with his money.</p>
<p>It&#8217;s too bad my friend didn&#8217;t keep better track of his investments.  Perhaps if he had he could have pulled his money out of the stock market and salvaged his vacation.  Since my friend is an avid Ruby lover I figured I&#8217;d help make sure he doesn&#8217;t end up in this situation ever again.  That&#8217;s why I wrote GMoney, a <a href="http://docs.rubygems.org/">RubyGem</a> for interacting with the <a href="http://code.google.com/apis/finance/">Google Finance API</a>.</p>
<span id="more-87"></span>
<h3>Background</h3>
<p>The Google Finance API allows users to interact with <a href="http://www.google.com/finance">Google Finance</a> and can help developers programmatically &#8220;request a list of a user&#8217;s portfolios, retrieve performance and return statistics on an existing portfolio, query the positions and transactions in a portfolio, and create new portfolios and transactions.&#8221;</p>
<p>GMoney is a wrapper for this API and allows developers to take advantage of the API&#8217;s functionality using the <a href="http://www.ruby-lang.org/en/">Ruby programming language</a>.  To minimize the learning curve I tried to give GMoney an interface similar to that of <a href="http://ar.rubyonrails.org/">ActiveRecord</a> so that developers would have a familiar starting point.</p>
<h3>Google Finance Model</h3>
<p>The Google Finance model is pretty simple.  It is made up of the following three entities:</p>
<p><strong>Portfolios</strong></p>
<div class="blockquote"> 
<p>A portfolio is a collection of positions that the user holds in various securities, plus metadata.  Each portfolio entry contains the portfolio&#8217;s title along with data such as currency and total market value. Each portfolio entry also contains a link to the portfolio&#8217;s position feed (i.e. a Portfolio &#8220;has_many&#8221; Positions).</p>
</div>
<p><strong>Positions</strong></p>
<div class="blockquote"> 
<p>A position is a collection of information about a security that the user holds.  Each position entry contains the ticker exchange and symbol for a stock, mutual fund, or other security, along with the number of units of that security that the user holds. Each position entry also contains a link to the position&#8217;s transaction feed (i.e. a Position &#8220;has_many&#8221; Transactions).</p>
<p>You can&#8217;t directly create or update position entries; positions are derived from transactions.</p>
</div>
<p><strong>Transactions</strong></p>
<div class="blockquote"> 
<p>A transaction is a collection of information about an instance of buying or selling a particular security.  Each transaction entry contains a transaction type (such as buy or sell), a number of units, the price, and so on.</p>
</div>
<h3>Installation</h3>
<p>To install GMoney simply run the following command:</p>
<div class="codeBlock"> 
	<pre><code>gem install gmoney</code></pre> 
</div> 
<h3>Login</h3>
<p>You will need a <a href="http://www.google.com/accounts">Google account</a> in order to use the Google Finance API.  Once you have obtained an account you can login via GMoney using the following code:</p>
<div class="codeBlock"> 
	<pre><code>require 'rubygems'
require 'gmoney'

GMoney::GFSession.login('&lt;YOUR GOOGLE USER ID&gt;','&lt;YOUR GOOGLE PASSWORD&gt;')</code></pre> 
</div>
<h3>Create a portfolio</h3>
<p>If you were to login to Google Finance for the first time using a browser you would see the following screen showing the default Google Finance Portfolio called &#8220;My Portfolio&#8221;:</p>
<p><a href="http://www.justinspradlin.com/images/default_portfolio.jpg"><img src="http://www.justinspradlin.com/images/default_portfolio_s.jpg" class="center" alt="Create Portfolio" /></a></p>
<p>To create your own Portfolio using GMoney use the following code:</p>
<div class="codeBlock"> 
	<pre><code>portfolio = GMoney::Portfolio.new
portfolio.title = "My New Ruby Portfolio"
portfolio.save</code></pre> 
</div>
<p>After executing the code and refreshing the browser you should see that the &#8220;My New Ruby Portfolio&#8221; has been created.</p>
<p><a href="http://www.justinspradlin.com/images/create_portfolio.jpg"><img src="http://www.justinspradlin.com/images/create_portfolio_s.jpg" class="center" alt="Create Portfolio" /></a></p>
<h3>Create a transaction(s)</h3>
<p>As mentioned above transactions are used to buy and sell stocks within a given portfolio.  The positions within your portfolio will be based on the transaction information.  Running the following code will buy shares of Apple, Red Hat, Google, and Microsoft and place them into your portfolio:</p>
<div class="codeBlock"> 
	<pre><code>stocks = {"NASDAQ:GOOG" => 529.00, 
          "NASDAQ:AAPL" => 192.00, 
          "NYSE:RHT" => 27.00, 
          "NASDAQ:MSFT" => 28.00}
 
stocks.each do |symbol, price| 
  transaction = GMoney::Transaction.new
  #pid is the human readable id of the portfolio created above
  transaction.portfolio = portfolio.pid
  transaction.type = GMoney::BUY
  transaction.shares = 50
  transaction.ticker = symbol
  transaction.price = price  
  transaction.save
end</code></pre> 
</div>
<p>The result of running the code is as follows:</p>
<p><a href="http://www.justinspradlin.com/images/buy_stocks.jpg"><img src="http://www.justinspradlin.com/images/buy_stocks_s.jpg" class="center" alt="Create Portfolio" /></a></p>
<h3>Update Transaction</h3>
<p>If you actually meant to buy 100 shares of Goolge instead of 50 you can update the transaction using the following code:</p>
<div class="codeBlock"> 
	<pre><code>#I know the transaction id is '4'
transaction = GMoney::Transaction.find "#{portfolio.pid}/NASDAQ:GOOG/4"
transaction.shares = 100
transaction.save</code></pre> 
</div>
<p>The result:</p>
<p><a href="http://www.justinspradlin.com/images/update_goog.jpg"><img src="http://www.justinspradlin.com/images/update_goog_s.jpg" class="center" alt="Create Portfolio" /></a></p>
<h3>Delete Transaction</h3>
<p>We can delete a transaction like so:</p>
<div class="codeBlock"> 
	<pre><code>GMoney::Position.find("#{portfolio.pid}/NASDAQ:MSFT").delete</code></pre> 
</div>
<p>Now we have no more MSFT stock:</p>
<p><a href="http://www.justinspradlin.com/images/delete_trans.jpg"><img src="http://www.justinspradlin.com/images/delete_trans_s.jpg" class="center" alt="Create Portfolio" /></a></p>
<h3>Reading all the Positions in a Porfolio</h3>
<p>If we&#8217;d like to see all of the positions within our portfolio we can execute this code:</p>
<div class="codeBlock"> 
	<pre><code>portfolio.positions.each do |position| 
  puts position.title
end</code></pre> 
</div>
<p><strong>Output:</strong></p>
<div class="outputBlock"> 
<pre>Red Hat, Inc.
Apple Inc.
Google Inc.</pre> 
</div> 
<h3>Gotcha</h3>
<p>There is a bit of a &#8220;gotcha&#8221; right now with the Google Finance API.  For whatever reason, stock returns information is not being sent by Google.  I figured it was something I was doing wrong in my code, but then I used <a href="http://code.google.com/apis/gdata/docs/client-libraries.html">Google&#8217;s official API client</a> and was still unable to retrieve the returns data.  I&#8217;ll be sure to file a <a href="http://code.google.com/p/gdata-issues/issues/list">bug report</a> with Google over the next few days.</p>
<h3>Conclusion</h3>
<p>GMoney offers a lot more features than what has been written about here.  Be sure to check out the documentation and the source code on <a href="http://github.com/jspradlin/gmoney">Github</a>.  The full script of the code used for this blog entry can also be found on <a href="http://github.com/jspradlin/justinspradlin.com-blog-examples/tree/master/2010-02-01_Introducing-GMoney-A-RubyGem-for-Interacting-with-the-Google-Finance_API/">Github</a>.</p>
<p>Overall building GMoney was an incredible learning experience.  It was my first significant Ruby project and also my first Open Source project.  As of today GMoney has been downloaded almost <a href="http://gemcutter.org/gems/gmoney">200 times</a>.  I&#8217;ve tested GMoney on Windows and Linux using Ruby versions 1.8.6, 1.8.7, and 1.9.1 (via <a href="http://rvm.beginrescueend.com/">RVM</a>).  Feedback and bug reports are more than welcome.</p>
<p>With GMoney in place my friend will be sure to keep much better track of his investments and is looking forward to the <a href="http://en.wikipedia.org/wiki/2014_FIFA_World_Cup">2014 World Cup in Brazil</a>.</p>
<p><i>Disclaimer:</i> I am in no way endorsing any of the companies mentioned in this blog entry and all company references are for example purposes only.</p>]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/programming/introducing-gmoney-a-rubygem-for-interacting-with-the-google-finance-api/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Create a Photostream Using jQuery and the Flickr API</title>
		<link>http://www.justinspradlin.com/programming/create-a-photostream-using-jquery-and-the-flickr-api/</link>
		<comments>http://www.justinspradlin.com/programming/create-a-photostream-using-jquery-and-the-flickr-api/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 02:18:04 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=77</guid>
		<description><![CDATA[Recently I added a Flickr photostream to the footer of the home page of this blog and I thought it would be cool to post an entry on how you can use jQuery and the Flickr API to do the same.  Even if you&#8217;re not familiar with jQuery or the Flickr API it&#8217;s actually [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I added a <a href="http://www.flickr.com/sprad">Flickr</a> photostream to the footer of the <a href="http://www.justinspradlin.com/#footer">home page</a> of this blog and I thought it would be cool to post an entry on how you can use jQuery and the Flickr API to do the same.  Even if you&#8217;re not familiar with jQuery or the Flickr API it&#8217;s actually quite simple to accomplish this task.</p>
<span id="more-77"></span>
<h3>Prerequisites</h3>
<p>Download <a href="http://docs.jquery.com/Downloading_jQuery">jQuery</a></p>
<div class="blockquote"> 
<p>jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animation, and Ajax interactions for rapid web development.</p>
</div>
<p>Download <a href="http://leandrovieira.com/projects/jquery/lightbox/">jQuery lightBox</a></p>
<div class="blockquote"> 
<p>jQuery lightBox is a jQuery plugin that can be used to display a gallery of images on the current page using the power and flexibility of jQuery&#8217;s selectors.</p>
</div>
<p>Create a Flickr Account and <a href="http://www.flickr.com/services/api/misc.api_keys.html">API Key</a> if you don&#8217;t already have them</p>
<div class="blockquote"> 
<p>A Flickr API key is necessary for accessing additional service features offered by Flickr.</p>
</div>
<h3>Code Time</h3>
<p>Let&#8217;s assume that our HTML page is as follows:</p>
<div class="codeBlock"> 
	<pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; 
&lt;html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" 
	lang="en-US" xml:lang="en-US"&gt;
&lt;head&gt; 
  &lt;title&gt;JQuery/Flickr API Code&lt;/title&gt; 
  &lt;link rel="stylesheet" href="<strong>styles/style.css</strong>" 
  	type="text/css" media="screen" /&gt;
  &lt;link rel="stylesheet" href="<strong>styles/jquery.lightbox-0.5.css</strong>" 
  	type="text/css" media="screen" /&gt;
  &lt;script type="text/javascript" src="<strong>js/jquery-1.3.2.min.js</strong>"&gt;&lt;/script&gt; 
  &lt;script type="text/javascript" src="<strong>js/jquery.lightbox-0.5.min.js</strong>"&gt;&lt;/script&gt;
  &lt;script type="text/javascript" src="<strong>js/custom.js</strong>"&gt;&lt;/script&gt;
&lt;/head&gt; 
&lt;body&gt; 
    &lt;!-- Some Content --&gt;
    <strong>&lt;div id="footer"&gt; 
        &lt;div id="flickr"&gt;&lt;/div&gt; 
    &lt;/div&gt;</strong>	
&lt;/body&gt; 
&lt;/html&gt;</code></pre> 
</div> 
<p>There are only a few important things to be aware of with this code.  First we need to make sure that we include all of our style sheets and JavaScript files in the <code>head</code> section of our HTML page.  In addition to including the jQuery and jQuery lightBox files notice that I have also created a style sheet called &#8220;<code>style.css</code>&#8221; and a JavaScript file called &#8220;<code>custom.js</code>&#8220;.  We will use these files to store our custom code.</p>
<p>Flickr has a very extensive <a href="http://www.flickr.com/services/api/">API</a> that allows developers to grab images using many different techniques.  For this example I have chosen to pull back images using the <code><strong><a href="http://www.flickr.com/services/api/flickr.photos.search.html">flickr.photos.search</a></strong></code> method.  This method &#8211; among other things &#8211; allows users to grab images that have been labeled with a specific tag.</p>
<p>In the <code>custom.js</code> file we will include the following code:</p>
<div class="codeBlock"> 
	<pre><code>$(function() {
    var apiKey = '<strong>&lt;YOUR API KEY&gt;</strong>';
    var userId = '<strong>&lt;FLICKR USER ID&gt;</strong>';
    var tag = '<strong>&lt;COMMA SEPERATED LIST OF TAGS&gt;</strong>';
    var perPage = '25';
    var showOnPage = '6';
    
    <strong>$.getJSON</strong>('http://api.flickr.com/services/rest/?format=<strong>json</strong>&amp;method='+
        '<strong>flickr.photos.search</strong>&amp;api_key=' + apiKey + '&amp;user_id=' + userId + 
        '&amp;tags=' + tag + '&amp;per_page=' + perPage + '&amp;jsoncallback=?', 
    function(data){
        var classShown = 'class="lightbox"';
        var classHidden = 'class="lightbox hidden"';
        
        $.each(data.photos.photo, function(i, rPhoto){
          var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/'
            + rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret;            
            
            var thumbPhotoURL = basePhotoURL + '_s.jpg';
            var mediumPhotoURL = basePhotoURL + '.jpg';
            
            var photoStringStart = '&lt;a ';
            var photoStringEnd = 'title="' + rPhoto.title + '" href="'+ 
                mediumPhotoURL +'"&gt;&lt;img src="' + thumbPhotoURL + '" alt="' + 
                rPhoto.title + '"/&gt;&lt;/a&gt;;'                
            var photoString = (i &lt; showOnPage) ? 
                photoStringStart + classShown + photoStringEnd : 
                photoStringStart + classHidden + photoStringEnd;
                                        
            <strong>$(photoString).appendTo("#flickr");</strong>
        });
        <strong>$("a.lightbox").lightBox();</strong>
    });
});</code></pre> 
</div> 
<p>Let&#8217;s examine the variables that are declared at the top of this JavaScript file:</p>
<div class="blockquote"> 
<p><strong>apiKey</strong> – Your Flickr API key<br/>
<strong>userId</strong> – User ID of the user whose pictures you wish to grab<br/>
<strong>tag</strong> – A comma separated list of tag values<br/>
<strong>perPage</strong> – The number of images you wish to pull back (maximum: 500)<br/>
<strong>showOnPage</strong> – The number of images you wish to display on the page<br/>
</p>
</div>
<p>Next we call jQuery&#8217;s <code><strong>$.getJson</strong></code> method passing it a custom URL and a callback method.  The URL is dynamically created based on the values set in the variables mentioned above.  The callback method takes the JSON object returned by Flickr and parses it to grab the relevant photo data.  The JSON returned by Flickr might look something like this:</p>
<div class="codeBlock"> 
	<pre><code>jsonFlickrApi({"photos":{"page":1, "pages":1, "perpage":25, "total":"17",
"photo":[{"id":"42626017633f", "owner":"705311402@N00", 
"secret":"2casd5d2079e", "server":"4010", "farm":5, "title":"Some Photo Title",
"ispublic":1, "isfriend":0,"isfamily":0}, {"id":"42626017633f", 
"owner":"705311402@N00", "secret":"2casd5d2079e", "server":"4008", 
"farm":5, "title":"Some Other Photo", "ispublic":1, "isfriend":0, 
"isfamily":0}, ...]}, "stat":"ok"})	</code></pre> 
</div> 
<p>Using the jQuery <code><strong>$.each</strong></code> method we can easily iterate through all of the photo elements and create the dynamic HTML needed to add the photostream to our HTML page.  For each photo, we grab its relevant information (id, server location, title, etc.) and build image links with the following structure:</p>
<div class="codeBlock"> 
	<pre><code>&lt;a class="lightbox" 
  href="http://farm5.static.flickr.com/4010/42626017633f _2casd5d2079e.jpg" 
  title="Some Photo Title"&gt;
    &lt;img alt="Some Photo Title" 
    src="http://farm5.static.flickr.com/4010/42626017633f _2casd5d2079e<strong>_s</strong>.jpg"/&gt;
&lt;/a&gt;    
</code></pre> 
</div> 
<p>These images will be appended to the <code>div</code> with the ID of &#8220;<code><strong>flickr</strong></code>&#8221; on our HTML page.  The jQuery <code><strong>$.append</strong></code> method is used to accomplish this task.  Notice that we end the &#8220;thumbnail&#8221; photo URLs with &#8220;<strong>_s</strong>&#8220;.  This will request a small square shaped version of our image from Flickr which is perfect for display in a photostream.</p>
<p>Each image will have a CSS class of &#8220;<code><strong>lightbox</strong></code>&#8221; so that we can properly select all of the images to be used by the jQuery lightBox library.  Notice that the callback function passed into the $.each method stores a loop counter variable called &#8220;<code><strong>i</strong></code>&#8220;.  Since we only want 6 images displayed on our page at once we can use this counter variable to check the current loop position and add an additional CSS class called &#8220;<code><strong>hidden</strong></code>&#8220;&#8221; to the images not within the first 6 photos returned.  These photos will be added to the page, but will not be visible to the user.</p>
<p>After we add all of the images to the page we call <code><strong>$("a.lightbox").lightBox();</strong></code> to create a Lightbox for all of the images (including the hidden ones) in our photostream.</p>
<p>When we view the page we will see the first 6 images in our photostream.</p>
<p><img src="http://www.justinspradlin.com/images/flickr_stream.jpg" alt="Flickr Stream" /></p>
<p>Clicking on any of the images will launch a Lightbox and allow us to scroll through the remaining photos.</p>
<p><img src="http://www.justinspradlin.com/images/ss_jump.jpg" alt="Sand Soccer Jump" /></p>
<h3>Source Code</h3>
<p>The complete source code example for this blog entry can be downloaded by <a href="http://github.com/jspradlin/justinspradlin.com-blog-examples/tree/master/2010-01-12_Creating-a-Photostream-Using-jQuery-and-the-Flickr-API/">clicking here</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/programming/create-a-photostream-using-jquery-and-the-flickr-api/feed/</wfw:commentRss>
		<slash:comments>45</slash:comments>
		</item>
		<item>
		<title>Hello World: 2.0</title>
		<link>http://www.justinspradlin.com/general/hello-world-2-0/</link>
		<comments>http://www.justinspradlin.com/general/hello-world-2-0/#comments</comments>
		<pubDate>Sat, 02 Jan 2010 01:30:30 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=73</guid>
		<description><![CDATA[Hello and welcome to JustinSpradlin.com (formerly Fiascode.com).  This is the personal technology blog and resume site for Justin Spradlin.
The last few weeks of 2009 were spent rewriting this site from the ground up.  I hope you like the new design.  Come back often for updates or subscribe to the feed to have [...]]]></description>
			<content:encoded><![CDATA[<p>Hello and welcome to JustinSpradlin.com (formerly Fiascode.com).  This is the personal technology blog and resume site for <a href="http://www.justinspradlin.com/about">Justin Spradlin</a>.</p>
<p>The last few weeks of 2009 were spent rewriting this site from the ground up.  I hope you like the new design.  Come back often for updates or subscribe to the <a href="http://feeds.feedburner.com/JustinSpradlin">feed</a> to have the latest posts appear directly in your favorite RSS reader.</p>
<p>Happy New Year!</p>]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/general/hello-world-2-0/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Giving Design Patterns a Second Chance: Ruby Edition</title>
		<link>http://www.justinspradlin.com/reviews/giving-design-patterns-a-second-chance-ruby-edition/</link>
		<comments>http://www.justinspradlin.com/reviews/giving-design-patterns-a-second-chance-ruby-edition/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 00:00:28 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[Reviews]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=27</guid>
		<description><![CDATA[I have a confession to make.
You know that really popular design patterns book that most software developers (especially in the Java world) claim to have read?  You know the one I&#8217;m talking about. The one written by the &#8220;Gang of Four&#8221;.  The one you were supposed to have read during your junior or [...]]]></description>
			<content:encoded><![CDATA[<a href="http://www.justinspradlin.com/reviews/giving-design-patterns-a-second-chance-ruby-edition/"><img class="rev_right" src="http://www.justinspradlin.com/images/dpir2.jpg" alt="Design Patterns in Ruby" /></a><p>I have a confession to make.</p>
<p>You know that really popular design patterns book that most software developers (especially in the Java world) claim to have read?  You know the one I&#8217;m talking about. The one written by the &#8220;Gang of Four&#8221;.  The one you were supposed to have read during your junior or senior year of college.  Yeah, <a href="http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612">this one</a>.</p>
<p>I&#8217;ve never read it.</p>
<p>Sure, I&#8217;ve owned it.  I have even thumbed through it a few times.  But I&#8217;ve never sat down with any real intention of absorbing the information within its covers.  The problem for me personally was that when I first opened <em>Design Patterns</em> I was just starting my software development career.  I was too young and hadn&#8217;t seen enough code to really comprehend the authors&#8217; message or understand the need for such a book.</p>
<p><span id="more-27"></span></p>
<p>A few years have passed since then and while it&#8217;s still early in my career I now have a much better idea of how to develop software and have a much better understanding of Object Oriented Design.  Even though I spend a significant amount of my free time developing my skills and reading about software development I have yet to read the seminal <em>Design Patterns</em> book.</p>
<p>Design patterns have left a bad taste in my mouth.  Over the years they have been abused and misunderstood.  They seem to have become caught up in the all too familiar silver bullet buzzword vernacular of the IT industry (<a href="http://en.wikipedia.org/wiki/Service_Oriented_Architecture">SOA</a> anyone?).  So I simply avoided them.  Unless I was about to interview for a new job, design patterns never so much as crossed my mind.  Repeat after me: Singleton, Factory, MVC.  <em>You&#8217;re hired!</em></p>
<p>But things have changed.  Over the past year and a half or so I&#8217;ve really started to focus on my career as a software developer.  I&#8217;ve learned new operating systems and languages, created this blog, and started attending local developer meetings on a regular basis.  While I still have my favorite technologies and interests, I&#8217;ve been doing a much better job of keeping an open mind about trying out new development tools and methodologies.</p>
<p>Enter <a href="http://jroller.com/rolsen/">Russ Olsen</a>.  In addition to being a great developer and all around good guy, Russ is someone who I had the honor of working with at the beginning of my career.  He was very much a mentor and I credit him with teaching me many of the applied fundamentals of software development.  So what does Russ have to do with design patterns?  Well it just so happens that a few years after I left the company where Russ and I worked together he wrote a book called <em><a href="http://www.amazon.com/Design-Patterns-Ruby-Russ-Olsen/dp/0321490452">Design Patterns in Ruby</a></em>.  Because of my respect for Russ and my fondness of Ruby I decided I&#8217;d give the book a shot.  While I was certainly expecting to learn some new things, I was surprised (although I shouldn&#8217;t have been) by how much great information I was able to extract from this book.</p>
<p>In their most minimal form, design patterns are simply reusable solutions that have been created to solve common coding problems.  While this may seem intuitive, it was actually somewhat of a revelation to me – a person who has ignored the direct usage of design patterns for all these years.  I see now that given an appropriate situation design patterns can be used to create consistent, maintainable code.  The important thing to remember is that each pattern has a specific use and should only be used when applicable.</p>
<p>Although the title of the book is <em>Design Patterns in Ruby</em>, a majority of the principles and patterns apply to many other object oriented languages as well.  In fact, while I was reading Russ&#8217;s book I was in the middle of working on a small Java project.  This project had to keep track of rapid state changes on a particular website.  I needed to keep track of a countdown timer, a list of participants, and an aggregate score.  Each of these pieces of information was updated independently, but I needed to make decisions in my code based on the combination of this information at any given time.  After reading the chapter on the <a href="http://en.wikipedia.org/wiki/Observer_pattern">Observer pattern</a>, I realized it would be the perfect fit.  Prior to using the pattern my code was a huge pile of tangled spaghetti. Afterwards, it was clean and easy to read.</p>
<p>I really liked the way the chapters were organized in <em>Design Patterns in Ruby</em>.  Russ started each chapter by posing a common programming problem.  Then he would explain how a specific design pattern could be used to solve that problem.  As the chapter progressed Russ would work through the problem using examples that were very easy to understand.  Each chapter ended with real world examples of the patterns as they have been implemented in the Ruby core libraries or various open source projects.  I found the real world code samples to be especially useful as compliments to the examples given in the book.</p>
<p>Not only did I enjoy reading this book because it was written by Russ, but I genuinely feel like it has helped to make me a better programmer.  In addition, it has helped increase my Ruby specific programming skills.  Learning to program in Ruby is easy, but learning to program the &#8220;Ruby Way&#8221; is a much greater challenge.  Ruby is full of powerful idioms that are not necessarily obvious without a deep examination of the language.  Russ&#8217;s book helps enlighten would be Ruby programmers to many of Ruby&#8217;s powerful language features.</p>
<p>For example, compare an implementation of the <a href="http://en.wikipedia.org/wiki/Proxy_pattern">Proxy pattern</a> written in Java and Ruby:</p>
<h3>Java Version</h3>
<p><code>MathService.java</code></p>
<div class="codeBlock">
<pre><code>public interface MathService {
    public void add(int x, int y);
    public void subtract(int x, int y);
}</code></pre>
</div>
<p><code>MathServiceImpl.java</code></p>
<div class="codeBlock">
<pre><code>public class MathServiceImpl implements MathService {
    public void add(int x, int y) {
        System.out.println("Result ("+x+ " + "+y+"): " + (x + y));
    }

    public void subtract(int x, int y) {
        System.out.println("Result ("+x+ " - "+y+"): " + (x - y));
    }
}</code></pre>
</div>
<p><code>MathServiceProxy.java</code></p>
<div class="codeBlock">
<pre><code>public class MathServiceProxy implements MathService {
    private MathService delegate;

    public MathServiceProxy(MathService ms){
        this.delegate = ms;
    }

    public void add(int x, int y) {
        System.out.println("Call made to the add method");
        delegate.add(x, y);
    }

    public void subtract(int x, int y) {
        System.out.println("Call made to the subtract method");
        delegate.subtract(x, y);
    }
}</code></pre>
</div>
<p><code>MathServiceDriver.java</code></p>
<div class="codeBlock">
<pre><code>public class MathServiceDriver {
    public static void main(String[] args) {
        MathService ms = new MathServiceProxy(new MathServiceImpl());
        ms.add(1, 2);
        ms.subtract(4, 3);
    }
}</code></pre>
</div>
<h3>Ruby Version</h3>
<p><code>math_service.rb</code></p>
<div class="codeBlock">
<pre><code>class MathService
  def add(x, y)
    puts "Result (#{x} + #{y}): #{x + y}"
  end

  def subtract(x, y)
    puts "Result (#{x} - #{y}): #{x - y}"
  end
end

class MathServiceProxy
  def initialize(math_service)
    @delegate = math_service
  end

  def method_missing(name, *args)
    puts "Call made to the #{name} method"
    @delegate.send(name, *args)
  end
end

ms = MathServiceProxy.new(MathService.new)
ms.add(1,2)
ms.subtract(4,3)</code></pre>
</div>
<h3>Result of Running Either Program</h3>
<div class="outputBlock">
<pre>Call made to the add method
Result (1 + 2): 3
Call made to the subtract method
Result (4 - 3): 1</pre>
</div>
<p>In this example we use the Proxy pattern to print out a message before each method call.  If we decided to add any methods to our <code>MathService</code> interface we would need to update our <code>MathServiceImpl</code> and <code>MathServiceProxy</code> Java classes as well.  However, by using Ruby&#8217;s built in <code>method_missing</code> method we have the ability to wrap each <code>MathService</code> method call dynamically without having to write a new method in our <code>MathServiceProxy</code> class.  Ruby removes the tedium of implementing the Proxy pattern.</p>
<p>This is just one small example of the flexibility and power provided by the Ruby language.  Before reading Russ&#8217;s book I didn&#8217;t necessarily &#8220;get&#8221; many of Ruby&#8217;s idioms.  Reading <em>Design Patterns in Ruby</em> has certainly helped solidify my understanding and is great for programmers who would like to take their Ruby skills to the next level.<!--end_raw--></p>
<h3>Code Samples</h3>
<p>All code samples from this blog entry can be downloaded from GitHub by <a href="http://github.com/jspradlin/fiascode-blog-examples/tree/8b744699647d587329f0b7e2f558360c67426173/2009-07-01_Giving-Design-Patterns-a-Second-Chance-Ruby-Edition">clicking here</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/reviews/giving-design-patterns-a-second-chance-ruby-edition/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Ruby Screen Scraping with scRUBYt!</title>
		<link>http://www.justinspradlin.com/programming/ruby-screen-scraping-with-scrubyt/</link>
		<comments>http://www.justinspradlin.com/programming/ruby-screen-scraping-with-scrubyt/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 10:00:21 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=26</guid>
		<description><![CDATA[I am currently in the market to buy my first home so I've been spending a lot of time on various real estate websites searching through listings trying to find the perfect property.  I live in a competitive housing market so it is important that I am informed whenever a new property becomes available. [...]]]></description>
			<content:encoded><![CDATA[<p>I am currently in the market to buy my first home so I've been spending a lot of time on various real estate websites searching through listings trying to find the perfect property.  I live in a competitive housing market so it is important that I am informed whenever a new property becomes available.  Logging onto any number of real estate websites to check for new listings each day is very repetitive and time consuming.  Fortunately, it is possible to easily gather this information automatically using a technique called <a href="http://en.wikipedia.org/wiki/Screen_scraping">screen scraping</a>.</p>
<p>Since most web pages are simply made of HTML it is easy for a computer to parse and store the information contained within these documents.  Each programming language commonly has a host of libraries to assist in the screen scraping/parsing process and Ruby is no exception.  To create simple screen scrapers in Ruby I have been using a library called <a href="http://scrubyt.org/">scRUBYt!</a>.  scRUBYt! provides methods to access a given website and scrape its content.  All the programmer needs to do is provide the <a href="http://www.w3.org/TR/xpath">XPath</a> string to the desired information.</p>
<p>Using the scRUBYt! library has allowed me to write a small screen scraper script to access the <a href="http://franklymls.com/">FranklyMLS.com</a> website, check for new listings, and then report back with the results. This has saved me a lot of time and effort.  Let's dive into some code to see how this is done.</p>
<span id="more-26"></span>
<p>First, we'll need to create a simple class to store the information that we scrape from the FranklyMLS.com website.  The <code>Property</code> class will hold various property related information (price, MLS number, square footage, etc.):</p>
<div class="codeBlock">
	<pre><code>class Property
  attr_accessor :mls, :list_price, :dom, :address,
                :city, :zip, :bed, :bath, :sqft, :built

  def initialize(property)
    @mls = (property/:mls).inner_html
    @list_price = (property/:list_price).inner_html
    @dom = (property/:dom).inner_html
    @address = (property/:address).inner_html
    @city = (property/:city).inner_html
    @zip = (property/:zip).inner_html
    @bed = (property/:bed).inner_html
    @bath = (property/:bath).inner_html
    @sqft = (property/:sqft).inner_html
    @built = (property/:built).inner_html
  end
end</code></pre>
</div>
<p>Next we'll need to make sure that scRUBYt! is installed.  If you don't already have <a href="http://github.com/">Github</a> set up as one of your gem repositories do so now by executing the following command:</p>
<div class="codeBlock">
	<pre><code>gem sources -a http://gems.github.com</code></pre>
</div>
<p>Then install the scRUBYt! gem:</p>
<div class="codeBlock">
	<pre><code>gem install jspradlin-scrubyt</code></pre>
</div>
<p><i><strong>Side note:</strong>  I've built some functionality into the scRUBYt! library so you will need to grab the gem from <a href="http://github.com/jspradlin">my Github repository</a> (i.e. jspradlin-scrubyt).  I've spoken with the lead developer on the scRUBYt! project and it looks like my changes might make it into a future version of the official gem.</i></p>
<p>At this point we need to give scRUBYt! the URL of a website that we wish to scrape.  The FranklyMLS.com website has its own special URL query syntax which displays only properties that meet our specific criteria.  For example, if we only wanted to find active listings in the following zip codes - 22201, 22202, 22203 - the FranklyMLS.com URL would be:</p>
<div class="codeBlock">
	<pre><code>http://franklymls.com/default.aspx?m=R&amp;s=(22201,22202,22203)+active</code></pre>
</div>
<p>We can dynamically generate a URL with our specific housing criteria by including the following code in our script:</p>
<div class="codeBlock">
	<pre><code># Generate the URL for FranklyMLS.com given
# the following criteria:
zips = [22201,22202,22203,22209]
beds = [2, 3].collect{ |bed| bed.to_s+'bdr'}
min_price = 150 #in thousands
max_price = 350 #in thousands
exclusions = ['JEFFERSON'].collect{ |exclude| "+-#{exclude}"}

fmls_url = "http://franklymls.com/default.aspx?"
fmls_url += "m=R&amp;l=#{min_price}K&amp;h=#{max_price}K"
fmls_url += "&amp;s=(#{zips.join(',')})+active"
fmls_url += "+(#{beds.join(',')})"
fmls_url += exclusions.to_s</code></pre>
</div>
<p>Now we're ready to scrape some housing data.  Once the FranklyMLS.com property page loads we are presented with a table that contains information about the listings that meet our criteria (image modified to save space):</p>
<img class="centered" src="http://www.justinspradlin.com/images/table.jpg" alt="FranklyMLS.com Property Table"/>
<p>The HTML that generates this table would appear like this (modified to save space):</p>
<div class="codeBlock">
	<pre><code><span class="colorBlue">&lt;table id="dgRealtorStyle"&gt;</span>
  ...
  <span class="colorGreen">&lt;tr style="display:visible"&gt;</span>
    <span class="colorRed">&lt;td&gt;&lt;a&gt;...&lt;/a&gt;&lt;a&gt;AR6552162&lt;/a&gt;&lt;/td&gt;&lt;!-- td[1]--&gt;</span>
    <span class="colorPurple">&lt;td&gt;$256,000&lt;/td&gt;&lt;!-- td[2]--&gt;</span>
    &lt;td&gt;$339,000&lt;/td&gt;
    &lt;td&gt;$&lt;/td&gt;
    &lt;td&gt;&nbsp;&lt;/td&gt;
    &lt;td&gt;&nbsp;&lt;/td&gt;
    &lt;td&gt;562&lt;/td&gt;
    <span class="colorOrange">&lt;td&gt;1931 CLEVELAND #313&lt;/td&gt;&lt;!-- td[8]--&gt;</span>
    ...
    &lt;td&gt;ARLINGTON&lt;/td&gt;
    &lt;td&gt;22201&lt;/td&gt;
    &lt;td&gt;&nbsp;&lt;/td&gt;
    &lt;td&gt;CLEVLAND HO&lt;/td&gt;
    &lt;td&gt;3/1&lt;/td&gt;
    &lt;td&gt;860&lt;/td&gt;
    &lt;td&gt;1960&lt;/td&gt;
    &lt;td&gt;...&lt;/td&gt;
    &lt;td&gt;1&lt;/td&gt;
    &lt;td&gt;160&lt;/td&gt;
    &lt;td&gt;&lt;a&gt;x&lt;/a&gt;&lt;/td&gt;
  <span class="colorGreen">&lt;/tr&gt;</span>
  ...
<span class="colorBlue">&lt;/table&gt;</span></code></pre>
</div>
<p>Finally, the Ruby code to scrape this data using scRUBYt!:</p>
<div class="codeBlock">
	<pre><code>#Scrape the FranklyMLS.com website using scRUBYt!
property_data = Scrubyt::Extractor.define do
  fetch fmls_url

  <span class="colorBlue">properties '//table[@id="dgRealtorStyle"]'</span> do
    <span class="colorGreen">property "//tr"</span> do
      <span class="colorRed">mls "/td[1]//a[2]"</span>
      <span class="colorPurple">list_price "/td[2]"</span>
      dom "/td[7]"
      <span class="colorOrange">address "/td[8]"</span>
      city "/td[9]"
      zip "/td[10]"
      bed "/td[13]",
        :format_output => lambda {|bed_bath| bed_bath.split('/')[0]}
      bath "/td[13]",
        :format_output => lambda {|bed_bath| bed_bath.split('/')[1]}
      sqft "/td[14]"
      built "/td[15]"
    end
  end
end</code></pre>
</div>
<p>If you look at the table, the HTML code, and the Ruby code you'll see that I've color coordinated each separate piece of information to illustrate how it is parsed and then stored.  The scRUBYt! library will "fetch" the given URL, locate the HTML elements by the given XPath, and then store the data.</p>
<p>Once we have all of the data collected we may want to do something useful with the information such as convert it into an <a href="http://en.wikipedia.org/wiki/RSS_(file_format)">RSS</a> feed.  We can accomplish this by using the <a href="http://wiki.github.com/why/hpricot">Hpricot</a> and <a href="http://builder.rubyforge.org/">Builder</a> libraries (which should be installed as dependencies of scRUBYt!).  The code for the RSS conversion would look like this:</p>
<div class="codeBlock">
	<pre><code># Read in the XML generated by scRUBYt! then
# convert the data into Property objects
# and store them in the property_hash.
property_hash = {}

hp = Hpricot.XML(property_data.to_xml)
(hp/:property).each do |property|
  property_hash[(property/:mls).inner_html] = Property.new(property)
end

# Using the Builder library, iterate through
# the property_hash to generate an RSS feed.
xml = Builder::XmlMarkup.new(:target => $stdout, :indent => 2 )
xml.instruct! :xml, :version => "1.0"
xml.rss :version => "2.0" do
  xml.channel do
    xml.title "Property Feed"
    xml.link "&lt;--YOUR URL--&gt;"
    xml.description "This is my property feed"

    property_hash.each do | key, property |
      pub_date = (Time.now - property.dom.to_i*60*60*24)
      pub_date = pub_date.strftime("%a, %d %b %Y %I:%M:%S")

      xml.item do
        xml.title property.address
        xml.link "http://franklymls.com/#{property.mls}"
        xml.pubDate "#{pub_date} EST"
        xml.description "City: #{property.city}
          Address: #{property.address}
          Price: #{property.list_price}
          Bed: #{property.bed}
          Bath: #{property.bath}
          Sqft: #{property.sqft}
          Built: #{property.built}"
      end
    end
  end
end</code></pre>
</div>
<p>To make sure I get routine updates, I run this Ruby code on my server every hour using a <a href="http://en.wikipedia.org/wiki/Cron">cron job</a> and pipe its output to an RSS feed.  I am subscribed to the generated RSS feed so now I know exactly when a new property becomes available in my area!</p>
<p>Overall scRUBYt! is very easy to use and for simple screen scraping tasks it should work fine.  However, I have found that it can run into some problems when the HTML gets complex.  In these cases I would recommend using Hpricot for fine-level scraping.</p>
<p>To view the source code for this entry and to view other screen scraping code that I have written check out <a href="http://github.com/jspradlin">my Github page</a>.</p>
<p>If you'd like to look at another example of scRUBYt! in action, feel free to read the post I wrote for my company's blog by <a href="http://blog.platinumsolutions.com/Ruby-Screen-Scraping-and-a-Little-Friendly-Competition">clicking here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/programming/ruby-screen-scraping-with-scrubyt/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Helpful Tips from Pragmatic Thinking and Learning</title>
		<link>http://www.justinspradlin.com/reviews/helpful-tips-from-pragmatic-thinking-and-learning/</link>
		<comments>http://www.justinspradlin.com/reviews/helpful-tips-from-pragmatic-thinking-and-learning/#comments</comments>
		<pubDate>Mon, 02 Feb 2009 02:00:29 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[Reviews]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=25</guid>
		<description><![CDATA[In order to stay up to speed in an industry that changes by the day developers must constantly be learning and acquiring new skills.  As technology fads come and go it is important for developers to isolate and keep pace with the technologies that are in high demand.  Because technologies change so rapidly [...]]]></description>
			<content:encoded><![CDATA[<a href="http://www.justinspradlin.com/reviews/helpful-tips-from-pragmatic-thinking-and-learning/"><img src="http://www.justinspradlin.com/images/ptl.jpg" alt="Pragmatic Thinking and Learning" class="rev_left" /></a><p>In order to stay up to speed in an industry that changes by the day developers must constantly be learning and acquiring new skills.  As technology fads come and go it is important for developers to isolate and keep pace with the technologies that are in high demand.  Because technologies change so rapidly it is important that we are able to learn as quickly and efficiently as possible.  While there is certainly no shortage of information available on the latest technologies, making sense of this information, figuring out what is important, and putting this information to use can be a very challenging task.  Therefore it is important that developers learn how to learn.</p>
<p>I recently finished the book <i>Pragmatic Thinking and Learning: Refactor Your Wetware</i> by Andy Hunt, co-author of the seminal book <i><a href="http://www.pragprog.com/titles/tpp/the-pragmatic-programmer">The Pragmatic Programmer</a></i>.  In this book Hunt discusses how people (specifically software developers) learn and offers tips on how we can set out to learn more effectively.  Here are some useful tips I stumbled upon while reading <i>Pragmatic Thinking and Learning</i>:</p>
<span id="more-25"></span>
<h3>SQ3R</h3>
<p>It is unfortunate that the most common way that many people attempt to teach themselves new skills is by reading.  A lot of people tend to learn better through experimentation and observation, but in many cases these are not practical first steps to take when starting out with a given subject.  On the other hand, reading is an important skill and reading material is abundant so it&#8217;s important that we are able to get the most out of the things we read.</p>
<p>The main reason reading is not a great way to learn is because it is often viewed as a passive activity.  As Hunt describes in his book however humans don&#8217;t do a great job of simply ingesting material.  Instead, Hunt suggests that we turn reading into a more active endeavor and describes using a technique called <a href="http://en.wikipedia.org/wiki/SQ3R">SQ3R</a>.  SQ3R is a simple strategy that can be used to actively engage yourself in whatever it is you are reading.  The SQ3R process is as follows:</p>
<div class="blockquote">
<p>
<strong>S</strong>urvey &#8211; Scan the chapter headings and summaries for an overview.<br/>
<strong>Q</strong>uestion &#8211; Note any questions you have.<br/>
<strong>R</strong>ead &#8211; Read in its entirety.<br/>
<strong>R</strong>ecite &#8211; Summarize, take notes, and put in your own words.<br/>
<strong>R</strong>eview &#8211; Reread, expand notes, and discuss with colleagues.<br/>
</p>
</div>
<p>There is plenty of information available on <a href="http://www.google.com/search?q=sq3r">SQ3R</a> on the web and of course there are <a href="http://en.wikipedia.org/wiki/KWL_table">many</a> <a href="http://en.wikipedia.org/wiki/PQRST#The_PQRST_method">other</a> techniques that can be used as well.  What is important however is that instead of passively trying to absorb what we read we are deliberate in the way we go about consuming information.</p>
<h3>Mind Maps</h3>
<p>Generating ideas, especially on structured topics can oftentimes be a challenge.  Traditional brainstorming techniques such as creating outlines are a great start, but are often limited by their structure and by the restriction of simply using words to express ideas.  An alternative approach which Hunt presents in this book is to create a <a href="http://en.wikipedia.org/wiki/Mind_map">Mind Map</a>.</p>
<p>A Mind Map is a free form diagram that focuses on a central idea and illustrates the relationships among topics associated with that idea.  The advantage of using a Mind Map is that you are not limited to simply using words.  You can sketch pictures, draw lines between ideas, and use color to group similar thoughts.</p>
<p>As an example, I decided to create a Mind Map for a presentation I will be giving in a few weeks on <a href="http://www.virtualbox.org/">VirtualBox</a>.  To be fair this might not have been the greatest example of the power of using a Mind Map because I have already done quite a bit of <a href="http://www.justinspradlin.com/general-technology/5-reasons-virtualbox-rocks-my-socks/">research on the topic</a>, but it was a good place for me to get started with Mind Maps and definitely helped me solidify some ideas for my presentation.  Here&#8217;s what I came up with (click to enlarge):</p>
<a href="http://www.justinspradlin.com/images/mindmap_large.jpg"><img class="centered" src="http://www.justinspradlin.com/images/mindmap_small.jpg" alt="VirtualBox Mind Map"/></a>
<p>One thing I found interesting while creating this Mind Map was that I actually needed to create multiple drafts.  My first draft of this very same image was pretty scatter-brained.  But that is the point of creating a Mind Map.  It helps you take the ideas from your head and organize them into a tangible format that can then be translated into actual work (i.e. a presentation, an essay, code, etc.).</p>
<h3>Harvesting Techniques</h3>
<p>Have you ever struggled with a tough coding problem?  Do you think as hard as you can about the problem, but are still unable come up with the answer?  Then has the solution ever popped in your head upon waking the next day?  Did the answer you were looking for suddenly appear during your daily commute when you were least expecting it?  This happens all the time and the reason it occurs is because in many case we already know the answers to our problems.</p>
<p>Our brains have an amazing capacity for storing and retrieving all sorts of relevant (and irrelevant) information.  As an oversimplification we can think of our brains as being split into two distinct hemispheres.  The left hemisphere (L-mode) is analytic, logical, temporal, linear, and rational.  It is responsible for processing words and symbols.  The right hemisphere (R-mode) is more spatial and is good at processing patterns and relationships.  The right side of our brain is intuitive and makes decisions based on hunches, feelings, and images.</p>
<p>As developers we tend to heavily favor using the left side of our brain to solve problems in our daily work, but in order to learn and work as efficiently as possible we must use both sides of our brain.  It is very difficult to force R-mode thinking, but you can help coax R-mode ideas out of your brain by using what Hunt calls harvesting techniques.  Harvesting techniques are ways to relax your brain&#8217;s L-mode processing in order to allow your R-mode thoughts to surface.  Here are a few examples of harvesting techniques:</p>
<p><strong>Free Form Journaling</strong> &#8211; Writing is a great way to relax your mind and allow your R-mode thoughts and ideas to escape your brain and present themselves onto paper.  When ideas pop into your head, write them down, and then elaborate on those ideas.  Simple brainstorming on paper can give you the opportunity to clarify your thoughts.</p>
<p><strong>Walking</strong> &#8211; Sometimes the best way to come up with ideas is to simply step away from your desk, relax your mind, and go for a walk.  While you&#8217;re walking though, try not to think about anything, especially the problem you are trying to solve.  The goal is to silence your L-mode and give your R-mode the chance to do some work.</p>
<p><strong>Image Streaming</strong> &#8211; This is the process of deliberately observing images in your mind and paying close attention to them.  First, pose a problem to yourself or ask yourself a question.  Then shut your eyes and relax.  As images start to cross your mind describe them out loud.  Try to describe as many details as you can using all five senses.  This type of thinking can help you discover fresh insights to the problem or question you presented yourself.</p>
<p>At first some of these ideas may seem a bit silly, but keep and open mind and give them a chance.  You may be pleasantly surprised with the results.</p>
<h3>Conclusion</h3>
<p><i>Pragmatic Thinking and Learning</i> is very accessible and easy to read.  Hunt writes the book using simple terms and concepts and illustrates his points with many examples.  I&#8217;ve really only begun to scratch the surface of the material covered with this blog entry.  Hunt goes into much further detail in his book and offers many additional techniques to help developers discover how they can best approach learning a new subject.</p>
<p>The book describes many different aspects of human physiology and psychology to explain why certain techniques work and others do not.  While Hunt does not claim to be an expert in either of these fields he cites a multitude of references and clearly shows that he has put in the thorough research required to write such a book.  Overall this book was a pleasure to read and I would certainly recommend it to anyone interested in improving their ability to learn.</p>]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/reviews/helpful-tips-from-pragmatic-thinking-and-learning/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>5 Reasons VirtualBox Rocks My Socks</title>
		<link>http://www.justinspradlin.com/general-technology/5-reasons-virtualbox-rocks-my-socks/</link>
		<comments>http://www.justinspradlin.com/general-technology/5-reasons-virtualbox-rocks-my-socks/#comments</comments>
		<pubDate>Mon, 12 Jan 2009 01:30:37 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[General Technology]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[VirtualBox]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=24</guid>
		<description><![CDATA[Lately I&#8217;ve been interested in learning about a variety of the Operating Systems that are available today.  I&#8217;m a big advocate of using the right tool for the job so experimenting with the latest OSes is a must in order to figure out the strengths and weaknesses of each.  While experimentation is a [...]]]></description>
			<content:encoded><![CDATA[<a href="http://www.justinspradlin.com/general-technology/5-reasons-virtualbox-rocks-my-socks/"><img src="http://www.justinspradlin.com/images/vboxlogo.jpg" alt="Virtualbox Logo" class="rev_right"/></a><p>Lately I&#8217;ve been interested in learning about a variety of the Operating Systems that are available today.  I&#8217;m a big advocate of using the right tool for the job so experimenting with the latest OSes is a must in order to figure out the strengths and weaknesses of each.  While experimentation is a great way to learn it can be a bit of a pain to find an old machine, format the hard drive, and install an OS.  <a href="http://en.wikipedia.org/wiki/Dual_boot">Dual booting</a> is an alternative option, but there is the inherent risk of messing up the current state of your machine.</p>
<p>Overcoming these issues was always a bit of a challenge for me until about six months ago when I stumbled upon <a href="http://www.virtualbox.org/">VirtualBox</a>.  VirtualBox is Sun&#8217;s &#8220;family of powerful x86 virtualization products.&#8221;  VirtualBox allows you to install and run &#8220;guest&#8221; operating systems in their own virtual environment on top of a &#8220;host&#8221; operating system.  I know that virtualization has been around for a while, but until finding VirtualBox, I&#8217;ve never had much success running virtualization software.  VirtualBox is different.  It&#8217;s intuitive and easy to use.  Here are the top 5 reasons why I love VirtualBox:</p>
<span id="more-24"></span>
<ol>
	<li><a href="#cheap_machines">Cheap Machines for Easy Experimentation</a></li>
	<li><a href="#dual_booting">No More Dual Booting</a></li>
	<li><a href="#networking_works">Networking Works</a></li>
	<li><a href="#vm_cloning">Virtual Machine Cloning</a></li>
	<li><a href="#guest_additions">Guest Additions Make for Seamless Work</a></li>
</ol>
<h3 id="cheap_machines">1. Cheap Machines for Easy Experimentation</h3>
<p>If you&#8217;ve ever wanted to try out a particular OS, but didn&#8217;t feel like dealing with the hassles mentioned above then VirtualBox may be exactly what you are looking for.  VirtualBox allows you to install guest operating systems in their own virtual environment which means there are no side effects on the current state of your machine (other than taking up some hard drive space of course).  If you mess something up simply discard your virtual machine (VM) and start over.</p>
<p>The net effect is that you save a lot of time.  No need for additional machines, formatting, or partitioning.  Simply create a new VM, mount the CD drive (or an .iso image of the OS you want to install), and fire up the virtual machine.</p>
<p><a href="http://www.justinspradlin.com/images/vbox_config.jpg"><img class="centered" src="http://www.justinspradlin.com/images/vbox_config_small.jpg" alt="VirtualBox settings window"/></a><br/><i>VirtualBox allows you to install a wide range of OSes including, but not limited to Linux (Ubuntu, etc.), BSD, Solaris, Windows (including 3.1).  For a full list of guest operating systems <a href="http://www.virtualbox.org/wiki/Guest_OSes">click here.</a></i></p>
<h3 id="dual_booting">2. No More Dual Booting</h3>
<p>When I first started dual booting years ago I appreciated the fact that it was possible to run two (or more) operating systems on the same machine.  This proved to be very useful when I wanted to play video games, write, or work with multimedia and graphics tools using Windows, but wanted to develop software using the tools available under various flavors of Linux.  There was a problem however.  Sometimes I would want to do work that required tools available in one of the OSes but not the other.  Other times I would simply prefer to work in a way that favored a particular operating system.  In either case I would often have to reboot my machine, select a particular OS, do my work in that OS, and then reboot back to my main operating system.  As you can imagine this was quite painful.</p>
<p>With VirtualBox you can have the best of all worlds.  You can work with as many OSes as you want at the same time.  I do this a lot particularly when developing websites.  I can run a full <a href="http://en.wikipedia.org/wiki/LAMP_(software_bundle)">LAMP</a> stack on an Ubuntu Linux guest operating system while I use photo editing software on my Windows host machine.  As a bonus you can place the guest OS into &#8220;Full Screen&#8221; mode and be totally ignorant of the fact that you are running a virtualized operating system.  Best of all:  No reboots required.</p>
<p><a href="http://www.justinspradlin.com/images/ubuntu_guest.jpg"><img class="centered" src="http://www.justinspradlin.com/images/ubuntu_guest_small.jpg" alt="VirtualBox running inside of Windows"/></a><br/><i>VirtualBox running inside of Windows.</i></p>
<p><a href="http://www.justinspradlin.com/images/ubuntu_full.jpg"><img class="centered" src="http://www.justinspradlin.com/images/ubuntu_full_small.jpg" alt="VirtualBox running in full screen mode"/></a><br/><i>VirtualBox running in full screen mode.</i></p>
<h3 id="networking_works">3. Networking Works</h3>
<p>One of the most exciting aspects about VirtualBox for me is that networking works between guest and host operating systems, guest and other guest operating systems, and guest operating systems and external networks (i.e. the Internet).  This has a lot of interesting implications.  One thing that I&#8217;ve been able to do is set up an old Dell computer in my closet running two VirtualBox VMs.  I have Ubuntu Linux installed on both VM instances.  I use one VM to serve as a centralized <a href="http://git-scm.com/">Git</a> source code repository (you are using <a href="http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-1/">Git</a>, <a href="http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-2/">right?</a>).  The other VM hosts a LAMP stack for serving a simple Wiki.  On my network these two VMs act as individual machines.  I can restart, shutdown, or in any other way modify one VM without disrupting the other.</p>
<p>With previous versions of VirtualBox networking could be slightly cumbersome to set up, but version 2.1 makes setup a breeze.  If you do try VirtualBox and get caught up along the way there is plenty of <a href="http://www.virtualbox.org/wiki/Documentation">documentation</a> and a strong <a href="http://www.virtualbox.org/wiki/Community">development community</a> to help you out along the way.</p>
<p><a href="http://www.justinspradlin.com/images/networking.jpg"><img class="centered" src="http://www.justinspradlin.com/images/networking_small.jpg" alt="VirtualBox networking"/></a><br/><i>VirtualBox networking allows for communication between guests, hosts, and outside networks.</i></p>
<h3 id="vm_cloning">4. Virtual Machine Cloning</h3>
<p>I once spent a lot of time setting up one of my virtual machine guest environments to the exact specifications that I needed.  I downloaded tons of software, added bash aliases, and tweaked various configurations to suit my needs.  Then an interesting thing happened.  I ended up needing another VM with the exact same specifications.  Taking the time to manually configure another VM wasn&#8217;t really an option.  Fortunately VirtualBox has built in VM cloning* support.  All I had to do was run the following command:<sup>**</sup></p>
<div class="codeBlock">
	<pre><code>VBoxManage clonehd &lt;/path/source.vdi&gt; &lt;/path/target.vdi&gt; -format VDI</code></pre>
</div>
<p>This saves a lot of time by reducing the effort needed to reproduce the guest virtual machines that you have previously set up using VirtualBox.  This also allows you to share your environment with other people by simply giving them access to your .vdi file (VirtualBox VM instance) and configuration settings.  In addition, once you set up a pristine environment you can clone it and always have it stored as a backup incase you mess something up with the VM you are currently working with.</p>
<p><sup>*</sup><i>There is a bit of a bug in VirtualBox 2.1.  The <code>clonehd</code> command seems to be generating corrupt .vdi files.  In the meantime as a work around you can simply copy the .vdi file, paste it into a target directory, and then run <code>VBoxManage internalcommands sethduuid &lt;target.vdi&gt;</code> command (thanks to <a href="http://paulsiu.wordpress.com/category/virtualization/virtualbox/">The Bonobo Journal</a> for the tip).</i></p>
<p><sup>**</sup><i>Note:  On Windows don&#8217;t forget to make sure you add the VBoxManage application to your path so that you can run it from the command line.</i></p>
<h3 id="guest_additions">5. Guest Additions Make for Seamless Work</h3>
<p>If you decide to install VirtualBox you will definitely want to install the &#8220;Guest Additions&#8221; package that is available for most guest operating systems.  Guest Additions allow for better interoperability between your installed guest VMs and your host system.  A few of the best features included with Guest Additions are:</p>
<blockquote>
<p><strong>Shared Clipboard</strong> &#8211; gives you the ability to bi-directionally copy and paste text between guest and host operating systems.</p>
<p><strong>Independent Mouse Control</strong> &#8211; permits you to move your mouse between guest and host systems.  Without Guest Additions installed your mouse is &#8220;captured&#8221; by the guest virtual machine until the &#8220;Host Key&#8221; is pressed (usually the right <code>ctrl</code> key).</p>
<p><strong>Better Video Support</strong> &#8211; allows you to resize your VM window while also dynamically resizing the screen resolution of your guest operating system.</p>
</blockquote>
<p><a href="http://www.justinspradlin.com/images/resized_guest.jpg"><img class="centered" src="http://www.justinspradlin.com/images/resized_guest_small.jpg" alt="Resized VirtualBox Window"/></a><br/><i>With Guest Additions installed VirtualBox screens can dynamically be resized to any screen resolution.</i></p>
<h3>Conclusion</h3>
<p>Besides simply saving time, space, and energy there are a lot of real world applications for VirtualBox.  I really like to setup multiple VMs on my host machine to serve as development and staging environments for the various web applications that I work on.  Also I like to test my web applications using a combination of different operating systems and browsers (especially various Windows/Internet Explorer combinations).  With VirtualBox this is all very straight forward.  In the future I would like to use VirtualBox to experiment with running multiple VMs over a network to learn more about setting up clustered, load balanced environments.</p>
<p>There are other virtualization and emulation tools on the market (<a href="http://www.vmware.com/">VMWare</a>, <a href="http://www.xen.org/">Xen</a>, <a href="http://www.winehq.org/">Wine</a>), but I find that VirtualBox has the right mix of performance and ease of use to suit all of my development needs.</p>]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/general-technology/5-reasons-virtualbox-rocks-my-socks/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Book Review: The Productive Programmer</title>
		<link>http://www.justinspradlin.com/reviews/book-review-the-productive-programmer/</link>
		<comments>http://www.justinspradlin.com/reviews/book-review-the-productive-programmer/#comments</comments>
		<pubDate>Fri, 28 Nov 2008 17:13:10 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[Reviews]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=22</guid>
		<description><![CDATA[Author: Neal Ford Rating: 3.5/5
As a developer I am constantly seeking ways in which I can improve my ability to quickly generate high quality code so I was excited to pick up Neal Ford&#8217;s latest book, The Productive Programmer.  This book offers advice on how to accelerate the production and quality of code by [...]]]></description>
			<content:encoded><![CDATA[<a href="http://www.justinspradlin.com/reviews/book-review-the-productive-programmer/"><img src="http://www.justinspradlin.com/images/productive-programmer.jpg" alt="The Productive Programmer" class="rev_left" /></a><p><strong>Author:</strong> <a href="http://memeagora.blogspot.com/">Neal Ford</a><br/> <strong>Rating:</strong> 3.5/5</p>
<p>As a developer I am constantly seeking ways in which I can improve my ability to quickly generate high quality code so I was excited to pick up Neal Ford&#8217;s latest book, <i>The Productive Programmer</i>.  This book offers advice on how to accelerate the production and quality of code by exploring many tools and practices that developers can use on a daily basis.  In the book, Ford introduces several productivity patterns that can be used immediately, but more importantly he defines a nomenclature that allows developers to construct additional productivity patterns on their own.</p>
<p><i>The Productive Programmer</i> is broken up into two parts:</p>
<span id="more-22"></span>
<h3>Part I.  Mechanics</h3>
<p>This section discusses tips, tricks, and tools that developers can use while physically engaged in the act of writing code.  This section is laid out in a recipe style format and is the part of the book which I found to be the most useful.</p>
<p>Ford breaks Part 1 down into four chapters which he calls the &#8220;Principles of Programmer Productivity&#8221;.  These principles are:</p>
<p><i>Acceleration</i></p>
<p>This chapter discusses tips developers can use to speed up their development efforts.  Ford lists many tips on using launchers, clipboards, and keyboard shortcuts for a variety of popular development tools and operating systems.</p>
<p><i>Focus</i></p>
<p>Ford uses this chapter to introduce guidelines on how to limit distractions, context switching, and pesky officemates so that developers can stay in the zone and focus on what&#8217;s really important &#8211; their work!</p>
<p><i>Automation</i></p>
<p>Common tasks that are repeated over and over again can kill a developer&#8217;s productivity.  This chapter lists strategies for automating such tasks to help save precious time throughout the workday.</p>
<p><i>Canocality (i.e. <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">D.R.Y</a>)</i></p>
<p>In this chapter Ford discusses the importance of version control, continuous build machines, and syncing development tools.  This helps to ensure the entire development team is on the same playing field so that precious time is not lost in dealing with inconsistencies between individual developer environments.</p>
<h3>Part II.  Practice</h3>
<p>In Part 2, Ford takes aim at practices that developers can use to improve the quality of their code.  By using the techniques and philosophies discussed in this section, Ford illustrates how code can be broken down into small, readable pieces that are easy to maintain.  Practices covered include Test Driven Development, Static Analysis, and Meta-Programming.  Also discussed are a few development philosophies that can guide developers when making decisions about how they should go about writing their code.  These philosophies include: <a href="http://en.wikipedia.org/wiki/You_Ain't_Gonna_Need_It">YAGNI (You Ain&#8217;t Gonna Need It)</a>, SLAP (Single Level of Abstraction Principle), and my favorite &#8211; Questioning Authority, an excerpt:</p>
<div class="blockquote">
<p>This is a story I first heard from Dave Thomas during a keynote address he delivered called Angry Monkeys and Cargo Cults. I don&#8217;t know if it&#8217;s true (despite researching it quite a bit), but it doesn&#8217;t matter-it illustrates a point beautifully.</p>
<p>Back in the 1960s (when scientists were allowed to do all kinds of crazy things), behavioral scientists conducted an experiment where they placed five monkeys in a room with a stepladder and a bunch of bananas hanging from the ceiling. The monkeys quickly figured out that they could climb the ladder and eat the bananas, but every time the monkeys got near the stepladder, the scientists would douse the entire room in ice cold water. You can guess what that generated: angry monkeys. Soon, none of the monkeys would go near the ladder.</p>
<p>Then, the scientists replaced one of the monkeys with a new monkey, who had not been subject to the blasts of water. The first thing he did was make a beeline for the ladder, and all the other monkeys beat him up. He didn&#8217;t know why they were beating him up, but he quickly learned: don&#8217;t go near the ladder. Gradually, the scientists replaced the original monkeys with new monkeys until they had a group of monkeys who had never been doused with cold water, yet they would still attack any monkey that approached the ladder.</p>
</div>
<p>The point is that just because things have always been done a certain way does not mean that we should blindly accept the status quo in favor of doing things that might actually make more sense or improve our code.</p>
<h3>Thoughts</h3>
<p><i>The Productive Programmer</i> was an enjoyable read.  At 200 pages the book reads very quickly &#8211; perhaps a bit too quickly in fact.  My one criticism of the book is that it would have helped to have some additional examples to solidify some of the concepts in the second part of the book (I would guess that is probably my one criticism of most books).  I did pick up a lot of small tips however and have been using them in my day to day work.  I&#8217;ve noticed some small speed and productivity improvements so in my opinion this book was totally worth the Amazon sticker price.</p>]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/reviews/book-review-the-productive-programmer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting it on with Git &#8211; Part 2</title>
		<link>http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-2/</link>
		<comments>http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-2/#comments</comments>
		<pubDate>Sun, 05 Oct 2008 21:20:09 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[General Technology]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Project Management]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=21</guid>
		<description><![CDATA[In my previous post I introduced Git and discussed its distributed nature, speed, and powerful branching/merging capabilities.  Today I'm going to continue the discussion on Git by writing about GitHub, Git in practice, and why Git may not be for everyone.

GitHub is Sexy
GitHub is an online Git repository hosting service that is freely available [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-1/">previous post</a> I introduced <a href="http://git.or.cz/">Git</a> and discussed its distributed nature, speed, and powerful branching/merging capabilities.  Today I'm going to continue the discussion on Git by writing about GitHub, Git in practice, and why Git may not be for everyone.</p>
<span id="more-21"></span>
<h3 id="github_sexy">GitHub is Sexy</h3>
<p><a href="http://github.com/">GitHub</a> is an online Git repository hosting service that is freely available to anyone who wishes to share their Git managed projects.  The service is very similar to <a href="http://sourceforge.net/">SourceForge</a> and <a href="http://code.google.com/hosting/">Google Code Hosting</a>, but because GitHub uses Git as its source control management system it offers a variety of advantages over other code hosting services.</p>
<p>To begin with, by using GitHub the barrier for working on and contributing to open source projects is significantly reduced.  In traditional centralized models only certain developers are given commit rights to any given project repository.  This creates a problem however for those developers who checkout the project and make changes.  Those developers have no way of keeping track of their local changes and history unless they import the project into their own centralized repository.  Doing this however means that the developer will lose the ability to easily synchronize their local project with the original project.</p>
<p>This problem goes away when using Git because all commits are local.  You can checkout a project from GitHub, makes changes as you wish, and commit them to your local repository.  This allows you to keep track of all of your changes and their history.  If you want to synchronize with the original project's repository you simply need to issue a "pull" command to get the latest updates.  As a bonus, if you come up with some feature that you think is particularly useful to the original project, you can ask the owner of that project to issue a "pull" request from your repository so your changes can be merged back into the master project.</p>
<p>Setting up your own remote Git repository is not that difficult, but GitHub adds a great web interface on top of Git that feels very much like a social networking site and serves as a platform for developers to share and contribute to each other's projects.  A lot of big name open source projects (especially in the Ruby community) are hosted on GitHub including <a href="http://www.rubyonrails.org/">Rails</a>, <a href="http://merbivore.com/">Merb</a>, and <a href="http://script.aculo.us/">Script.aculo.us</a> so developers can feel confident that the guys at GitHub have their act together.  GitHub also offers a variety of other features including private repositories (for a fee), a developer API, and integration with other services including <a href="http://www.basecamphq.com/">Basecamp</a>, <a href="http://lighthouseapp.com/">Lighthouse</a>, and <a href="http://twitter.com/">Twitter</a>.</p>
<h3 id="git_in_practice">Git in Practice</h3>
<p>It's highly unlikely that a developer will be able to get their current project team to switch version control systems overnight, but with Git you don't have to.  Git has powerful migration tools that can be used in conjunction with other version control systems, especially <a href="http://subversion.tigris.org/">Subversion</a>.  Current Subversion users can use Git to manage the source code on their local machine while still staying in sync with their team's Subversion repository using a built in Git command called "<a href="http://www.kernel.org/pub/software/scm/git/docs/git-svn.html">git-svn</a>".  The git-svn command allows developers to "push" and "pull" commits to and from a centralized Subversion repository.  This gives developers the power of local branching/merging capabilities using Git without forcing the technology on their team members.  In fact, no one even needs to know that Git is being used.</p>
<h3 id="git_not_for_everyone">Git, it's not for everyone</h3>
<p>Git is a pretty incredible tool, but it is likely not going to be championed by all developers.  To begin with, Git's learning curve can be a bit steep especially when compared with other version control tools.  Developers who desire to give Git a shot should be very comfortable working with the command line because Git's visualization support leaves something to be desired.</p>
<p>Git was created by Linux kernel developer Linus Torvalds so it may not come as a huge surprise that Git support on Windows is a bit lackluster.  I would guess that a majority of developers use Windows in some capacity so having a tool with weak Windows support is likely to hinder the adoption of that tool.  Fortunately, there is a project called <a href="http://code.google.com/p/msysgit/">MSysgit</a> which allows developers to use Git on their Windows machines.  I've personally used this tool on my Windows XP laptop and find that it works pretty well.</p>
<h3>Conclusion</h3>
<p>Minor drawbacks aside, Git is a pretty amazing tool for source control management and will be the one that I use for my future projects.  Its distributed nature, speed, and branching/merging capabilities make it a great tool for managing source code changes and revision history.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting it on with Git &#8211; Part 1</title>
		<link>http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-1/</link>
		<comments>http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-1/#comments</comments>
		<pubDate>Wed, 01 Oct 2008 02:40:56 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[General Technology]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Project Management]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=20</guid>
		<description><![CDATA[When I first heard about Git a few months ago the first thing that popped in my mind was: "Why the hell would I ever want to learn a new version control system?"  Subversion works perfectly fine, doesn't it?  I resisted at first, but after a few weeks I came around and decided [...]]]></description>
			<content:encoded><![CDATA[<p>When I first heard about <a href="http://git.or.cz/">Git</a> a few months ago the first thing that popped in my mind was: "Why the hell would I ever want to learn a new version control system?"  Subversion works perfectly fine, doesn't it?  I resisted at first, but after a few weeks I came around and decided to take Git for a test drive.  This is what I discovered:</p>
<span id="more-20"></span>
<h3>Distributed Source Code Management</h3>
<p>Git is a <strong><em>distributed</em></strong> source code management tool which means that there is no centralized source code repository.  This is a fundamental shift in the way source control is handled by systems like <a href="http://subversion.tigris.org/">Subversion</a>, <a href="http://www.nongnu.org/cvs/">CVS</a>, and <a href="http://www.perforce.com/">Perforce</a> and is probably the most challenging concept to grasp (it certainly was for me) when first learning about Git.  Version control using a centralized model is useful for things such as sharing code among developers, providing a history of changes to the code, and backing up data in a single location.  However, since Git does not use a centralized repository, a few obvious questions are raised about the Git's workflow model.  Questions like:</p>
<p><strong><em>Where are code commits stored?</em></strong></p>
<p>All code commits are stored on each developer's local machine.  Everyone has a copy of the entire repository and all of its history.</p>
<p><strong><em>How do developers share code?</em></strong></p>
<p>Developers share code with Git by executing commands called "push" and "pull".  Issuing a push command will push changes made in your repository to another developer's repository.  Conversely, issuing a pull command will pull changes from another developer's repository into your repository.  This may seem strange at first, but it actually ends up providing developers with a lot of collaborative power.  For example, instead of checking code changes into a central repository for everyone to see, two or more developers can share code with one another directly in a controlled fashion by pushing and pulling changes to and from each of their repositories respectively.</p>
<p><strong><em>How are backups handled in Git?</em></strong></p>
<p>If all of my code commits are stored on my local machine and my hard drive fails, wouldn't I be in a lot of trouble?  Not with Git.  If you are working by yourself, regularly backing up your repository using <a href="http://samba.anu.edu.au/rsync/">rsync</a>, <a href="http://mozy.com/">Mozy</a>, <a href="http://www.apple.com/timecapsule/backup.html">Time Capsule</a> or some other backup system will allow you to completely restore all of your work.  This is because Git stores all code revisions and history within each repository.</p>
<p>If you are working with other developers you simply need to <a href="http://www.kernel.org/pub/software/scm/git/docs/git-clone.html">clone</a> their copy of the repository.  In this sense, Git is actually incredibly fault-tolerant in that it provides geographically redundant archives of a repository because each repository is essentially a mirror of the entire project.</p>
<p>Finally, you could use one of the many publicly available Git repositories including <a href="http://github.com/">GitHub</a> and <a href="http://repo.or.cz/">repo.or.cz</a>.</p>
<h3>Git is Blazing Fast</h3>
<p>Since all commits, branching, and merging operations are local, Git is fast.  Real fast.  Unless you are pushing or pulling code there is no network to worry about.  Increased speed means developers can be more productive because they don't have to spend time waiting for costly repository operations to take place across a network.</p>
<h3>Git Makes Branching and Merging Easy</h3>
<p>In a centralized version control system branching and merging can often times be a source of frustration for developers.  All branches must live in the centralized repository and are likely viewable by other developers on the team.  If enough developers decide to create branches on the centralized server the repository can quickly become bloated.</p>
<p>Git takes a different approach.  Branching and merging in Git occur locally.  This dramatically increases the speed in which branching and merging can take place.  In addition, a single developer can create and destroy as many branches as they desire without having to worry about polluting a centralized repository.  Experimental features can quickly and easily be tested by creating a branch from the current working copy's "master" branch.  If the code produced in the branch proves worthy, it can be merged back into the "master" branch.  If the code from the branch ends up being useless, the branch can simply be deleted and no one ever needs to know that it existed.</p>
<h3>Part 1 Wrap Up</h3>
<p>Sunday I'll post <a href="http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-2/">Part 2</a> of my "Getting it on with Git" series where I'll discuss <a href="http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-2#github_sexy">GitHub</a>, <a href="http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-2#git_in_practice">Git in practice</a>, and why <a href="http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-2#git_not_for_everyone">Git may not be for everyone</a>.  Be sure to check back then!</p>
<h3>Useful Links</h3>
<p><a href="http://git.or.cz/">Official Git Site</a></p>
<p><a href="http://git.or.cz/gitwiki/GitCheatSheet">Git Cheat sheet</a></p>
<p><a href="http://www.youtube.com/watch?v=8dhZ9BXQgc4">Google Tech Talk on Git</a></p>
<p><a href="http://www.youtube.com/watch?v=4XpnKHJAok8">Linus Torvalds on Git</a></p>
<p><a href="http://www-cs-students.stanford.edu/~blynn/gitmagic/book.html">GitMagic Book</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/general-technology/getting-it-on-with-git-part-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Groovy Domain Specific Language Tutorial</title>
		<link>http://www.justinspradlin.com/programming/groovy-domain-specific-language-tutorial/</link>
		<comments>http://www.justinspradlin.com/programming/groovy-domain-specific-language-tutorial/#comments</comments>
		<pubDate>Mon, 18 Aug 2008 00:42:05 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=19</guid>
		<description><![CDATA[Although it may seem like an advanced topic, writing a simple Domain Specific Language (DSL) in Groovy is actually pretty easy.  Groovy's dynamic nature and metaprogramming capabilities give developers all the tools they need to quickly and easily write their own DSL.

Domain Specific Languages are typically small, simple languages with a highly expressive syntax [...]]]></description>
			<content:encoded><![CDATA[<p>Although it may seem like an advanced topic, writing a simple <a href="http://en.wikipedia.org/wiki/Domain-specific_programming_language">Domain Specific Language (DSL)</a> in <a href="http://groovy.codehaus.org/">Groovy</a> is actually pretty easy.  Groovy's dynamic nature and metaprogramming capabilities give developers all the tools they need to quickly and easily write their own DSL.</p>
<span id="more-19"></span>
<p>Domain Specific Languages are typically small, simple languages with a highly expressive syntax and grammar.  In computing, DSLs are used to provide domain experts (who may or may not have prior programming experience) with programming capabilities limited to their specific area of expertise.</p>
<p>There are two types of DSLs: external and internal.  External DSLs allow you to define a new language using any grammar or syntax you wish.  External DSLs must then be parsed and executed by the programming language of your choice.  Internal DSLs also define a new language, but are limited to the constructs made available by the implementing language.  Because of their dynamic features, languages like Groovy and Ruby make writing internal DSLs relatively easy.</p>
<h3>A Stock Trading DSL</h3>
<p>A few weeks ago <a href="http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-groovy/">I wrote about trading stocks</a> using Google's Finance API.  Sticking with that theme, I thought it would be cool to write a Domain Specific Language that could also be used to mimic stock trading activities.</p>
<p>I'm guessing that most Wall Street traders don't know much about programming, but I'm sure most traders could decipher the actions that would take place after executing the following code:</p>
<div class="codeBlock">
	<pre><code>buy 500, "AAPL", 179.30
buy(250, "AAPL", 179.30) <strong>//parenthesis are optional</strong>
buy 500, "SUNW", 10.14
sell 350, "AAPL", 179.30

show_transactions "AAPL"

print_portfolio_value</code></pre>
</div>
<p>The code above is actual Groovy code.  It tells the application to buy 750 shares of Apple stock at $179.30 in two separate transactions, buy 500 shares of Sun Microsystems stock at $10.14, and then sell 350 shares of Apple stock at $179.30.  After all the transactions take place the code shows the transaction history for the Apple trades and then prints the total value of the portfolio.</p>
<p>The Groovy code to drive the functionality behind this simple DSL looks like this:</p>
<div class="codeBlock">
	<pre><code><strong>portfolio = [:] //Holds all of the stock transactions</strong>

/**
 *A simple object to hold the data for each individual transaction
 */
class StockTransaction {
    def tickerSymbol
    def numberOfShares
    def sharePrice
    def type
    def transactionDate
}

def buy(numberOfShares, symbol, sharePrice){
    transaction('Buy', numberOfShares, symbol, sharePrice)
}

def sell(numberOfShares, symbol, sharePrice){
    transaction('Sell', numberOfShares, symbol, sharePrice)
}

def transaction(transactionType, numberOfShares, symbol, sharePrice){
    def transaction = new StockTransaction(tickerSymbol:symbol,
        numberOfShares:numberOfShares, sharePrice:sharePrice,
        type:transactionType, transactionDate:new Date())

    println "${transaction.type}ing ${transaction.numberOfShares} shares" +
        " of ${transaction.tickerSymbol} at ${transaction.sharePrice}"

    <strong>//If no transactions exist for a particular stock, check to see that the
    //transaction type is a 'Buy' and if so create a new list to hold
    //transactions for a particular stock.</strong>
    if(portfolio[transaction.tickerSymbol] == null){
        if(transactionType == 'Buy')
            portfolio[transaction.tickerSymbol] = [transaction]
        else
            println "You can't sell a stock you don't own."
    } else{
        portfolio[transaction.tickerSymbol] &lt;&lt; transaction
    }
}

def show_transactions(tickerSymbol){
    portfolio[tickerSymbol].each { transaction -&gt;
        println "${transaction.transactionDate}: ${transaction.type} " +
          "${transaction.numberOfShares} shares of ${tickerSymbol} at " +
          "${transaction.sharePrice}"
    }
}

def <strong>getPrint_portfolio_value()</strong>{
    def totalValue = 0

    <strong>//Add all of the 'Buy' transactions and subtract all of the 'Sell'
    //transactions from the total portfolio value.</strong>
    portfolio.each { tickerSymbol, transactionList -&gt;
        transactionList.each { transaction -&gt;
            if(transaction.type == 'Buy')
                totalValue +=
                    (transaction.numberOfShares * transaction.sharePrice)
            else
                totalValue -=
                    (transaction.numberOfShares * transaction.sharePrice)
        }
    }

    println "Your Total Portfolio Value is: ${totalValue}"
}</code></pre>
</div>
<p>The only thing the code really does is define methods for the different types of stock trading activities.  I use a <code>HashMap</code> called <code><strong>portfolio</strong></code> to hold each of the individual stock transaction's attributes stored in a simple <code>StockTransaction</code> object.  Each time a buy or sell action takes place the <code>portfolio HashMap</code> is updated with the corresponding <code>StockTransaction</code> object.</p>
<p>The readability of the DSL code is greatly improved because Groovy allows for optional parenthesis on methods that take one or more parameters.  Notice that the second call to purchase Apple stock uses the parenthesis to illustrate this point.  It is important to keep things as simple as possible when creating a DSL.  Programmers should try to avoid bogging the domain expert down by forcing him or her to use unnecessary constructs of a language such as parenthesis.</p>
<p>If you look closely at the code that defines the DSL you will notice that in order to make the parenthesis optional for calls to the <code><strong>print_portfolio_value</strong></code> method I had to get a little hacky and define the method as: <code><strong>getPrint_portfolio_value()</strong></code>.  This is because Groovy thinks that <code>print_portfolio_value</code> is a call to a property.  By adding the "get" in front of the method call, we can "trick" Groovy into calling the method as desired.</p>
<p>After executing the DSL code the output is as follows:</p>
<div class="outputBlock">
<pre>Buying 500 shares of AAPL at 179.30
Buying 250 shares of AAPL at 179.30
Buying 500 shares of SUNW at 10.14
Selling 350 shares of AAPL at 179.30
Sun Aug 17 19:15:05 EDT 2008: Buy 500 shares of AAPL at 179.30
Sun Aug 17 19:15:05 EDT 2008: Buy 250 shares of AAPL at 179.30
Sun Aug 17 19:15:05 EDT 2008: Sell 350 shares of AAPL at 179.30
Your Total Portfolio Value is: 76790.00</pre>
</div>
<h3>Fluency</h3>
<p>In the context of trading stocks, the DSL we created above is pretty straightforward, but it does suffer a bit from a problem with fluency.  It might be nice if we could make the DSL a bit more readable.  For example, what if the DSL was changed to read like this:</p>
<div class="codeBlock">
	<pre><code>buy 500.shares.of("AAPL").at(179.30)
buy 250.shares.of("AAPL").at(179.30)
buy 500.shares.of("SUNW").at(10.14)
sell 350.shares.of("AAPL").at(179.30)

show_transactions "AAPL"

print_portfolio_value</code></pre>
</div>
<p>Using <a href="http://www.justinspradlin.com/programming/groovy-metaprogramming-adding-behavior-dynamically/#categories">categories</a> it is possible to allow for a fluent DSL like the one above.  Take a look at the code behind this DSL:</p>
<div class="codeBlock">
	<pre><code>/**
 * The class used for the category
 */
class <strong>StockHelper</strong> {
    static portfolio = [:]

    static buy(<strong>self</strong>, stockTransaction) {
        stockTransaction.type = 'Buy'
        transaction(stockTransaction)
    }

    static sell(<strong>self</strong>, stockTransaction) {
        stockTransaction.type = 'Sell'
        transaction(stockTransaction)
    }

    static transaction(stockTransaction){
        println "${stockTransaction.type}ing " +
        "${stockTransaction.numberOfShares}" +
        " shares of ${stockTransaction.tickerSymbol} at " +
        "${stockTransaction.sharePrice}"

        if(portfolio[stockTransaction.tickerSymbol] == null){
            if(stockTransaction.type == 'Buy')
                portfolio[stockTransaction.tickerSymbol] = [stockTransaction]
            else
                println "You can't sell a stock you don't own."
        } else{
            portfolio[stockTransaction.tickerSymbol] &lt;&lt; stockTransaction
        }
    }

    static getShares(<strong>self</strong>) {
        def startTransaction = new StockTransaction(numberOfShares:<strong>self</strong>,
            transactionDate:new Date())
        return startTransaction
    }

    static of(<strong>self</strong>, tickerSymbol) {
        <strong>self</strong>.tickerSymbol = tickerSymbol
        return <strong>self</strong>
    }
    static at(<strong>self</strong>, sharePrice) {
        <strong>self</strong>.sharePrice = sharePrice
        return <strong>self</strong>
    }

    static show_transactions(<strong>self</strong>, tickerSymbol){
        portfolio[tickerSymbol].each { transaction ->
            println "${transaction.transactionDate}: ${transaction.type} " +
              "${transaction.numberOfShares} shares of ${tickerSymbol} at " +
              "${transaction.sharePrice}"
        }
    }

    static getPrint_portfolio_value(<strong>self</strong>){
        def totalValue = 0

        portfolio.each { tickerSymbol, transactionList ->

            transactionList.each { transaction -&gt;
                if(transaction.type == 'Buy')
                    totalValue +=
                        (transaction.numberOfShares * transaction.sharePrice)
                else
                    totalValue -=
                        (transaction.numberOfShares * transaction.sharePrice)
            }
        }

        println "Your Total Portfolio Value is: ${totalValue}"
    }
}</code></pre>
</div>
<p>By chaining methods calls together we can make our code very fluent.  We build a <code>StockTransaction</code> object by calling 3 methods: <code><strong>getShares()</strong></code>, <code><strong>of()</strong></code>, and <code><strong>at()</strong></code>.  Each of these calls is responsible for building a specific piece of the <code>StockTransaction</code> object and passing it along to the next call.  The <code><strong>self</strong></code> keyword is used to reference the target instance (i.e. the <code>StockTransaction</code> object being created).  After the <code>StockTransaction</code> is created, the <code>buy</code> or <code>sell</code> methods can be called to update the <code>portfolio HashMap</code> just as in the first example.</p>
<p>Even though parenthesis and the dot notation (for method access) must be used in order to execute this DSL code, I personally think this code is easier to read and understand as compared with the previous example.</p>
<h3>Conclusion</h3>
<p>The code in this blog entry is pretty brittle, but it illustrates how easily a DSL can be created using the Groovy programming language.  In a real life scenario programmers must be diligent about the design and usage of the DSLs they create.</p>
<p>By creating an internal DSL domain experts with some programming knowledge will also be able to exploit other constructs found in the implementing language such as loops and conditional statements.  For example, code could be written to do things such as:</p>
<div class="codeBlock">
	<pre><code>if(currentStockPriceVariable &lt; SOME_SHARE_PRICE_CONSTANT){
    buy 500.shares.of("AAPL").at(currentStockPriceVariable)
}</code></pre>
</div>
<p>or perhaps something like this:</p>
<div class="codeBlock">
	<pre><code>3.times {
    sell 500.shares.of("AAPL").at(179.30)
}</code></pre>
</div>
<p>Over the past few years DSLs have gained popularity along with the rise of dynamic languages.  For example, <code><a href="http://gant.codehaus.org/">GANT</a></code> is a popular DSL for the Groovy programming language that can be used to script <code><a href="http://ant.apache.org/">Ant</a></code> style builds.  It will be interesting to see what other types of DSLs become available in the future.  Be sure to look out for Martin Fowler's upcoming <a href="http://martinfowler.com/dslwip/">book</a> on the subject.</p>
<h3>Code</h3>
<p><a href="http://www.justinspradlin.com/downloads/groovydsl.zip">Click here</a> to download the code examples from this post.</p>
<h3>Disclaimer</h3>
<p>I am in no way endorsing any of the companies mentioned in this blog entry and all company references are for example purposes only.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/programming/groovy-domain-specific-language-tutorial/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Ruby Nation: Day 2 Wrap Up</title>
		<link>http://www.justinspradlin.com/general/ruby-nation-day-2-wrap-up/</link>
		<comments>http://www.justinspradlin.com/general/ruby-nation-day-2-wrap-up/#comments</comments>
		<pubDate>Sun, 03 Aug 2008 22:49:25 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=18</guid>
		<description><![CDATA[
Opening Keynote - Rich Kilmer
Rich Kilmer's opening keynote was by far the best presentation of the day.  Rich is an incredibly experienced and skilled Ruby developer who was one of the earlier adopters of the language.  During his keynote, Rich walked through his experiences with Ruby dating all the way back to 2001. [...]]]></description>
			<content:encoded><![CDATA[<p></p>
<h3>Opening Keynote - Rich Kilmer</h3>
<p>Rich Kilmer's opening keynote was by far the best presentation of the day.  Rich is an incredibly experienced and skilled Ruby developer who was one of the earlier adopters of the language.  During his keynote, Rich walked through his experiences with Ruby dating all the way back to 2001.  He has certainly worked on some interesting projects for impressive government agencies including DARPA and the United State Air Force.  Rich also talked about projects he has created for the Ruby community including <a href="http://freeride.rubyforge.org/wiki/wiki.pl">FreeRIDE</a> - a Ruby IDE and <a href="http://rubyforge.org/">RubyForge</a> - a code repository for Ruby projects.</p>
<p>One particularly interesting thing Rich mentioned was that Ruby is becoming a mainstream language.  I personally find this both exciting and scary.  It is exciting that the community is growing at that there will likely be more opportunities to work on Ruby projects professionally, but it is a bit worrisome that the community could start to be overpopulated with run-of-the-mill developers transitioning from other dying mainstream languages.</p>
<span id="more-18"></span>
<h3>Ruby Puzzlers - Mike Furr</h3>
<p>Mike Furr, a doctoral student at <a href="http://www.umd.edu/">UMCP</a>, gave a presentation on edge case scenarios that occur in the Ruby language.  Since I'm pretty new to Ruby I struggled to follow along, but Mike did do a good job of explaining how Ruby code reacted under various situations.  Even though it can be rare to deal with edge cases in a language, it is nice to know how to avoid them or work your way out of them if they do arise.</p>
<h3>Practical JRuby - David Keener</h3>
<p>A Java(ish) presentation at a Ruby conference?  It may seem a bit strange at first, but it actually makes a lot of sense.  Java as a platform has some pretty rock solid features including performance, garbage collection, and concurrency.  A lot time and thought has also been invested into Java libraries and corporate infrastructure so in many ways it makes sense to take advantage of what is already available.  David Keener hit on all of these points in his presentation and gave an example of how to integrate <a href="http://jruby.codehaus.org/">JRuby</a> with the <a href="http://www.jfree.org/jfreechart/">JFreeChart</a> Java library.</p>
<h3>Tools for Your Ruby Toolbox - Dave Bock</h3>
<p>Dave Bock is another <a href="http://www.fgm.com">FGM</a> employee that I had the pleasure of working with a few years back.  Dave has since moved on and started his own shop called <a href="http://www.codesherpas.com/">Codesherpas</a>.  In his presentation, Dave talked about 3 lightweight tools that can be used to quickly accomplish tasks in Ruby.  Dave first talked about <a href="http://www.rubyinside.com/staticmatic-ruby-powered-static-web-site-system-603.html">StaticMatic</a>, a framework for developing simple static websites using templates, but without using all of the built in functionality of Rails.  Another web framework Dave talked about was <a href="http://sinatrarb.com/Home">Sinatra</a>.  Again, this framework allows developers to create simple web applications without the full Rails stack, but it also includes some RESTful functionality.  Finally, Dave talked about <a href="http://www.ruby-doc.org/stdlib/libdoc/gserver/rdoc/classes/GServer.html">GServer</a>, a generic server library that allows developers to easily create server applications of their own.  During his presentation Dave demoed a quick "Knock Knock" client he created using the GServer library.</p>
<h3>Lightning Talks</h3>
<p>There were five lightening talks given yesterday, but again <a href="http://smartic.us/">Bryan Liles</a> stole the show with his presentation on Project Management.  The basic takeaway: meet with your reports regularly, project confidence, and set up processes that are easy to follow.  Sounds so simple doesn't it?</p>
<h3>Closing Keynote: Bad Ruby - Stuart Halloway</h3>
<p>Stuart Holloway closed RubyNation with a talk on Bad Ruby.  Playing off of a point made earlier in Rich Kilmer's talk about Ruby becoming mainstream, Stuart noted that now was the time for Ruby developers to begin to establish best practices for the language so that common pitfalls can be avoided when mainstream developers start to migrate to Ruby.  (Assuming of course "mainstream" developers actually migrate to Ruby).</p>
<h3>Conference Wrap Up</h3>
<p>Overall the conference was pretty great.  Day two was a little less energetic than day one, but that may not be too surprising seeing as how it was on a Saturday.  I was a little disappointed that Bruce Tate wasn't able to make the conference because I was really looking forward to hearing him speak, but I was pleasantly surprised at the quality of the other speakers.  I know that a lot of people put a lot of hard work into the conference so I'd personally like to thank everyone responsible for putting on this years conference and I can't wait to attend again next year.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/general/ruby-nation-day-2-wrap-up/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby Nation: Day 1 Wrap Up</title>
		<link>http://www.justinspradlin.com/general/ruby-nation-day-1-wrap-up/</link>
		<comments>http://www.justinspradlin.com/general/ruby-nation-day-1-wrap-up/#comments</comments>
		<pubDate>Fri, 01 Aug 2008 15:59:26 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=17</guid>
		<description><![CDATA[Ruby experts and enthusiasts from around the country met in Washington, D.C. today for the first annual RubyNation conference.  I always think it's awesome to get together with industry leaders to absorb and share new information and insights.  I've been to quite a few tech conferences in the past, but I've never been [...]]]></description>
			<content:encoded><![CDATA[<p>Ruby experts and enthusiasts from around the country met in Washington, D.C. today for the first annual <a href="http://www.rubynation.org">RubyNation</a> conference.  I always think it's awesome to get together with industry leaders to absorb and share new information and insights.  I've been to quite a few tech conferences in the past, but I've never been as engaged and attentive as I was today.  There is an energy around Ruby and Rails that I have yet to witness with other technologies.  I continue to be amazed by how passionate and open the community is as well.  I met and talked with more people today than all of the other conferences I've attended combined.</p>
<p>In case you weren't able to make it, here's a quick rundown of today's events:</p>
<span id="more-17"></span>
<h3>Opening Keynote: Ceremony vs. Essence - Neal Ford</h3>
<p><a href="http://memeagora.blogspot.com/">Neal Ford</a> is a seasoned consultant and speaker that I've seen present on more than one occasion.  I've always enjoyed his presentations, but his talk today really hit home with me.  Neal's talk basically boiled down to the fact that we developers need to <a href="http://en.wikipedia.org/wiki/KISS_principle">Keep It Simple (KISS)</a> and avoid the "accidental complexity" that is often unnecessarily added to the problems we are trying to solve.  I've listen rhetoric like this a 1,000 times, but I've never heard it articulated so elegantly.  It was literally like he was looking inside of my head and expressing the way I (and likely a lot of developers) feel about the current state of the industry (especially if you are a Java programmer like me).</p>
<h3>DSLs and Ruby: Blurring the Lines Between Programs And Data - Russ Olsen</h3>
<p>I used to work with Russ at a <a href="http://www.fgm.com">FGM</a> so I was really looking forward to hearing him speak.  Russ has become quite a leader in the Ruby community especially after publishing his first book: <a href="http://www.amazon.com/Design-Patterns-Ruby-Russ-Olsen/dp/0321490452">Design Patterns in Ruby</a>.  Russ's talk centered around Domain Specific Languages (DSLs) and how relatively easy it is to implement one using the Ruby language.  During his presentation Russ put together a simple Internal DSL for example purposes and also discussed use cases for when it is appropriate to create a DSL to solve a problem.</p>
<h3>The Culture of Innovation in Ruby - Glenn Vanderburg</h3>
<p>Innovation in testing frameworks in Ruby was the topic of Glenn Vanderburg's talk.  Glenn discussed some of the interesting testings frameworks available in the Ruby community (<a href="http://rspec.info/">Rspec</a>, <a href="http://mocha.rubyforge.org/">Mocha</a>, <a href="http://onestepback.org/software/flexmock/">Flex Mock</a>, <a href="http://thoughtbot.com/projects/shoulda">Shoulda</a>) and compared them to some of the stagnant frameworks in the Java community (<a href="http://www.junit.org/">JUnit</a>, <a href="http://testng.org/doc/">TestNG</a>).  Glenn also pointed out how Ruby's testing frameworks tend to make it much easier to mock objects and create more thorough tests with much less effort than the equivalent tests in the Java world.</p>
<h3>Living on the Edge - Yehuda Katz</h3>
<p>Yehuda Katz of <a href="http://engineyard.com/">EngineYard</a> talked about some of the new(er) technologies that are emerging in the Ruby community including <a href="http://merbivore.com/">Merb</a>, <a href="http://datamapper.org/">DataMapper</a>, Sake, Thor, YARDoc, and <a href="http://github.com/">GitHub</a>.  DataMapper looks like an especially interesting alternative to the incumbent ORM ActiveRecord.  It promises thread safety and increased performance which are obviously two great things.  GitHub looks pretty cool too.  I'm not quite ready to abandon <a href="http://subversion.tigris.org/">Subversion</a> just yet, but I will definitely be checking out <a href="http://git.or.cz/">Git</a> in the near future.</p>
<h3>Lightning Talks</h3>
<p>Chris Bucchere, David Jones, Simon Kaczor, and Bryan Liles all gave lightening talks today on a variety of topics including social networking, state machines, command line libraries, and testing respectively.  All of the talks presented useful information, but Bryan Liles was without a doubt the most entertaining speaker of the day.  He made it through about 65 slides in 15 minutes and was still able to convey a very important message about how often developers should be testing their code.  Check out his blog at: <a href="http://smartic.us/">http://smartic.us/</a></p>
<h3>Archaeopteryx: A Ruby MIDI Generator - Giles Bowkett</h3>
<p>I actually wasn't able to attend Giles Bowkett's session because I had a previous engagement to attend, but I did get a chance to view some <a href="http://gilesbowkett.blogspot.com/2008/02/archaeopteryx-ruby-midi-generator.html">screencasts</a> that show off his Ruby MIDI Generator.  Pretty cool stuff.</p>
<h3>Tomorrow</h3>
<p>Tomorrow looks to be a pretty exciting day as well.  I'm especially looking forward to talks from my former co-worker Dave Bock and author Stuart Holloway.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/general/ruby-nation-day-1-wrap-up/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Putting Google Finance to REST with Ruby</title>
		<link>http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-ruby/</link>
		<comments>http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-ruby/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 06:43:10 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=16</guid>
		<description><![CDATA[RubyNation is just a week and a half away and in order to prepare myself I thought I'd brush up on some Ruby and Rails in the days preceding the conference.  I don't use Ruby on a regular basis, but I'm a huge fan of dynamic languages so I'm really looking forward to attending [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.rubynation.org/">RubyNation</a> is just a week and a half away and in order to prepare myself I thought I'd brush up on some <a href="http://www.ruby-lang.org/">Ruby</a> and <a href="http://www.rubyonrails.org/">Rails</a> in the days preceding the conference.  I don't use Ruby on a regular basis, but I'm a huge fan of dynamic languages so I'm really looking forward to attending the conference and finding out what's new in the Ruby community.</p>
<p>By day I'm a Java developer, but I've also spent a fair amount of time studying Groovy.  Learning Groovy has been my "training wheels" approach to understanding dynamic languages.  Studying Groovy has helped me grasp new (new to me at least) concepts like <a href="http://www.justinspradlin.com/?s=metaprogramming">Metaprogramming</a> and Domain Specific Languages all from the comfort of my Java environment.</p>
<span id="more-16"></span>
<p>As a simple exercise I thought it would be interesting to rewrite the code from my <a href="http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-groovy/">last blog entry</a> in Ruby to see how it compares to the Groovy code I originally wrote.  So without further ado let's check out the code:</p>
<h3>Authenticating with Google</h3>
<p>In order to use the Google Finance API we need to first authenticate with Google by sending our <a href="https://www.google.com/accounts/NewAccount">Google Account</a> username and password to Google's client login URL: <strong>https://www.google.com/accounts/ClientLogin</strong>.</p>
<div class="codeBlock">
	<pre><code>def create_auth_token(username, password)
  https = Net::HTTP.new('www.google.com', <strong>443</strong>)
  <strong>https.use_ssl = true</strong>
  path = '/accounts/ClientLogin'

  query_string = "Email=#{username}&amp;Passwd=#{password}
                 &amp;service=finance&amp;source=company-groovyfinance-1.0"

  https.verify_mode = OpenSSL::SSL::VERIFY_NONE # don't display warnings

  response = https.<strong>post(</strong>path, query_string<strong>)</strong>

  if response.code == '200'
    return response.body[/Auth=(.*)/, 1] # The authorization token
  end

  return "Error"
end</code></pre>
</div>
<p>In the code above we create an <code>http</code> object and give it the correct URI and path to Google's login service.  We then send in a query string with our username, password, service, and source (application name).  If everything succeeds Google returns an Authentication token which we will set in the headers in subsequent calls to Google's service.</p>
<p>This code isn't much different from the Groovy code in my previous entry, but I do like the way Ruby allows <code>POST</code> calls directly on the <code><strong>http</strong></code> object.  This obsoletes the <code>processRequest()</code> method found in my Groovy code.</p>
<h3>Creating a Portfolio</h3>
<p>We can create a new portfolio in our Google Finance account by executing calls to the following method:</p>
<div class="codeBlock">
	<pre><code>def create_portfolio(authorization_token, portfolio_name)
  headers={}
  headers["Authorization"] = "GoogleLogin auth=#{authorization_token}"
  headers["Content-Type"] = "application/atom+xml"

  http = Net::HTTP.new('finance.google.com')
  path = "/finance/feeds/default/portfolios"

  atom_string = "&lt;?xml version='1.0'?&gt;
  &lt;entry xmlns='http://www.w3.org/2005/Atom'
         xmlns:gf='http://schemas.google.com/finance/2007'
         xmlns:gd='http://schemas.google.com/g/2005'&gt;
         &lt;title type='text'&gt;<strong>#{portfolio_name}</strong>&lt;/title&gt;
         &lt;gf:portfolioData currencyCode='USD'/&gt;
  &lt;/entry&gt;"

  response = <strong>http.post(</strong>path, atom_string, headers<strong>)</strong>

  if response.code == '201'
    doc = REXML::Document.new(response.body)
    return doc.root.elements["id"].text[/portfolios\/(.*)/, 1] #portfolio id
  end

  return "Error"
end</code></pre>
</div>
<p>This code is almost identical to the Groovy code I wrote <a href="http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-groovy/">last time</a> but I do really like the way Ruby allows you to place header attributes into a <code>Hash</code> and send them directly with a call to <code><strong>http.post()</strong></code>.</p>
<h3>Placing an Order</h3>
<p>Just like the example above, placing an order (stock trade) means that we need to create an <code><a href="http://en.wikipedia.org/wiki/Atom_(standard)">Atom</a></code> feed with our transaction attributes (transaction type, number of shares, etc.) and send them to a Google resource end point.  This end point in our case is the URL of the specific portfolio in which we wish to place our new asset.</p>
<div class="codeBlock">
	<pre><code>def create_stock_transaction(authorization_token, ticker_symbol,
                             number_of_shares, transaction_type, portfolio_id)

  headers={}
  headers["Authorization"] = "GoogleLogin auth=#{authorization_token}"
  headers["Content-Type"] = "application/atom+xml"

  http = Net::HTTP.new('finance.google.com')
  path = "/finance/feeds/default/portfolios/<strong>#{portfolio_id}</strong>/positions/" +
         "<strong>#{CGI::escape(ticker_symbol)}</strong>/transactions"

  transaction_time = Time.now.strftime("%Y-%m-%dT%H:%M:%S.000")

  atom_string = "&lt;?xml version='1.0'?&gt;
  &lt;entry xmlns='http://www.w3.org/2005/Atom'
         xmlns:gf='http://schemas.google.com/finance/2007'
         xmlns:gd='http://schemas.google.com/g/2005'&gt;
         &lt;gf:transactionData date='<strong>#{transaction_time}</strong>'
             shares='<strong>#{number_of_shares}</strong>' type='<strong>#{transaction_type}</strong>' /&gt;
  &lt;/entry&gt;"

  response = <strong>http.post(</strong>path, atom_string, headers<strong>)</strong>

  if response.code == '201'
    return response.body
  end

  return "Error"
end</code></pre>
</div>
<p>Once again the Ruby code looks nearly identical to the Groovy code.  We set the correct headers, generate a well formed Atom feed, and the post our data to Google.  If all goes well, the transaction will be made and an <code>Atom</code> representation of the transaction will be returned to the client.</p>
<h3>Groovy vs. Ruby Thoughts</h3>
<p>There are probably "Rubyer" ways to write the code samples listed above, but I did find it interesting that the code I wrote in Ruby was so similar to the code that I wrote in Groovy.  I'm not sure whether or not the similarities are due to the subjective nature of having the same programmer write both samples or if it's due to the fact that the languages are so similar to begin with.</p>
<p>Either way, exploring a new language (albeit a similar language) did give me some additional perspective.  I found myself bouncing back and forth between the Groovy and Ruby code comparing how similar tasks were performed in each language.  This type of information is always useful when trying to determine which technology is the right tool to use for a specific job.</p>
<p>In addition, studying Ruby <a href="http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-groovy/#comments">helped me write better Groovy code</a>.  In the create_auth_token() method in the Ruby sample a <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> is used to parse the authentication token from the returned string.  I was able to take this regular expression code and apply it to the same method (createAuthToken()) in my Groovy code to improve its readability.</p>
<h3>References</h3>
<br/><a href="http://www.justinspradlin.com/downloads/rubyfinance.zip">Download the Code</a><br/><br/>
<a href="http://code.google.com/apis/gdata/index.html">Google Data API Developers Guide</a><br/>
<a href="http://code.google.com/apis/finance/developers_guide_protocol.html">Google Finance Developers Guide</a><br/>
<a href="http://code.google.com/apis/finance/reference.html">Google Finance Reference</a><br/><br/>
<a href="http://code.google.com/support/bin/answer.py?answer=93164&amp;topic=12027">Using Ruby with the Google Data APIs</a><br/>
<a href="http://www.germane-software.com/software/rexml/docs/tutorial.html">REXML Guide</a><br/>
<h3>Disclaimer</h3>
<p>Again... I am in no way endorsing any of the companies mentioned in this blog entry and all company references are for example purposes only.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-ruby/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Putting Google Finance to REST with Groovy</title>
		<link>http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-groovy/</link>
		<comments>http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-groovy/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 03:07:13 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=15</guid>
		<description><![CDATA[For a while now I've been interested in learning more about building and consuming REST based web services.  Fortunately, many tech giants including Google and Yahoo expose much of their data and functionality through REST based APIs.  These powerful APIs, combined with Groovy's concise, readable syntax make it very easy to learn about [...]]]></description>
			<content:encoded><![CDATA[<p>For a while now I've been interested in learning more about building and consuming <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST</a> based web services.  Fortunately, many tech giants including <a href="http://code.google.com/">Google</a> and <a href="http://developer.yahoo.com/">Yahoo</a> expose much of their data and functionality through REST based APIs.  These powerful APIs, combined with Groovy's concise, readable syntax make it very easy to learn about the REST software architecture approach.</p>
<p>This particular blog entry makes use of <a href="http://code.google.com/apis/finance/">Google's Finance Data API</a>.  I'll explain how it is possible to programmatically authenticate with Google, create a new stock portfolio, and create positions (buy and sell stocks) within this portfolio by making REST based service calls.  I won't dive too deep into the details of the REST architecture, but if you have a general understanding of XML and the HTTP protocol it won't be too difficult to follow along.  For more information on REST, please see the links in the <a href="#reference">Reference</a> section below.</p>
<span id="more-15"></span>
<div class="codeBlock">
<i><strong>Note:</strong> If you want to try the code samples on your own you will need to have a Google Account.  To sign up for a free account <a href="https://www.google.com/accounts/NewAccount">click here</a>.</i>
</div>
<h3 id="googauth">Authenticating with Google</h3>
<p>In order to use Google's service we must first authenticate by <code><strong>POST</strong></code>ing a query string containing our username, password, service identifier, and source (application name) to the following URL: <code><strong>https://www.google.com/accounts/ClientLogin</strong></code>.  This code snippet illustrates how a <code><strong>POST</strong></code> request can be made in Groovy:</p>
<div class="codeBlock">
	<pre><code>static <strong>createAuthToken(</strong>String username, String password<strong>)</strong>{
    def url = new URL(<strong>"https://www.google.com/accounts/ClientLogin"</strong>)
    def connection = url.openConnection()

    def queryString = "<strong>Email</strong>=${username}&amp;<strong>Passwd</strong>=${password}" +
                      "&amp;<strong>service</strong>=finance&amp;<strong>source</strong>=company-groovyfinance-1.0"

    def returnMessage = <strong>processRequest(</strong>connection, queryString<strong>)</strong>

    if(returnMessage != "Error"){
        //the authentication token
        return returnMessage.split(/Auth=/)[1].trim()
    }
}

static String <strong>processRequest(</strong>connection, dataString<strong>)</strong>{
    connection.<strong>setRequestMethod("POST")</strong>
    connection.doOutput = true
    Writer writer = new OutputStreamWriter(connection.outputStream)
    writer.write(dataString)
    writer.flush()
    writer.close()
    connection.connect()

    if (connection.responseCode == 200 || connection.responseCode == 201)
        return connection.content.text

    return "Error"
}</code></pre>
</div>
<p>In the code above we create a <code>connection</code> to Google's authentication URL and <code>POST</code> the <code>queryString</code> by calling the reusable <code><strong>processRequest()</strong></code> method.  Within <code>processRequest()</code> we set the <code>connection's</code> request method type to "<code>POST</code>", create a <code>Writer</code>, and write the data to the supplied <code>connection</code>.</p>
<div class="codeBlock"><i><strong>Note:</strong> The code example for this blog post can be downloaded in its entirety by clicking the "Download the Code" link in the <a href="#reference">Reference</a> section below.</i></div>
<p>If our credentials are valid, Google will respond to our request with a string of name value pairs similar to this:</p>
<div class="codeBlock">
	<pre><code>SID=DQAAAIEAAAIgccs7qKgmwXGagt...lu6fg
LSID=DQAAAIIAAACsegj9oEm0Ob8pz...abyi5
Auth=<strong>DQAAAIMAAACgadj9oEm0Ob8pz...AGasG</strong></code></pre>
</div>
<p>The only piece of information we are interested in is the authorization token value that follows the "<code><strong>Auth</strong></code>" label.  We will need to use this token in the rest of our requests in order to authenticate with Google.</p>
<h3 id="portfoliocreation">Creating a Portfolio</h3>
<p>When users log into <a href="http://www.google.com/finance">Google Finance</a> for the first time they will be presented by default with an empty portfolio called "My Portfolio".  <i><strong>Note</strong>: a portfolio is simply a collection of assets (stocks, bonds, mutual funds, cash, etc.).</i></p>
<a href="http://www.justinspradlin.com/images/empty_portfolio_large.jpg"><img alt="Empty Portfolio" class="centered" src="http://www.justinspradlin.com/images/empty_portfolio_small.jpg" /></a>
<p>Let's pretend however that we do not wish to use the default portfolio, but instead want to create our own. To create a new portfolio we simply need to send a well formed <a href="http://en.wikipedia.org/wiki/Atom_(standard)"><code>Atom</code></a> XML feed that contains the name of the new portfolio (and optionally a currency code) to this URL: <code><strong>http://finance.google.com/finance/feeds/default/portfolios</strong></code></p>
<div class="codeBlock">
<pre><code>static <strong>createPortfolio(</strong>String authorizationToken, String portfolioName<strong>)</strong>{
    def url =
    	 new URL("<strong>http://finance.google.com/finance/feeds/default/portfolios</strong>")

    def connection = url.openConnection()
    connection.setRequestProperty("<strong>Content-Type</strong>", <strong>"application/atom+xml"</strong>)
    connection.setRequestProperty("<strong>Authorization</strong>",
                                  <strong>"GoogleLogin auth=${authorizationToken}"</strong>)

    def atomString = <strong>"""</strong>&lt;?xml version='1.0'?&gt;
    &lt;entry xmlns='http://www.w3.org/2005/Atom'
    	   xmlns:gf='http://schemas.google.com/finance/2007'
           xmlns:gd='http://schemas.google.com/g/2005'&gt;
        &lt;title type='text'&gt;<strong>${portfolioName}</strong>&lt;/title&gt;
        &lt;gf:portfolioData currencyCode='USD'/&gt;
    &lt;/entry&gt;<strong>"""</strong>

    def returnMessage = <strong>processRequest(</strong>connection, atomString<strong>)</strong>

    //Get the id of the newly created portfolio
    if(returnMessage != "Error"){
    	def entry = new <strong>XmlSlurper()</strong>.parseText(returnMessage)
    	def entryId = "${entry.id}"

    	return entryId[entryId.lastIndexOf('/')+1..-1]
    }
}</code></pre>
</div>
<p>Once again we create a <code>connection</code>, but this time we also need to set two request header parameters: <code><strong>Content-Type</strong></code> and <code><strong>Authorization</strong ></code>.  We set these parameters to "<code><strong>application/atom+xml</strong></code>" and "<code><strong>GoogleLogin auth=${authorizationToken}</strong></code>" respectively.  Note that the <code>authorizationToken</code> variable stores the authentication token that was returned by the <code>createAuthToken()</code> method.</p>
<p>After the connection is created we again call the <code>processRequest()</code> method that was discussed in the <a href="#googauth">Authenticating with Google</a> section above.  If all goes well, Google will create the new portfolio and return an <code>Atom</code> representation of that new portfolio to the client.  If we are logged into our web based Google Finance account we can refresh the screen and will notice our newly created portfolio.</p>
<a href="http://www.justinspradlin.com/images/groovy_portfolio_large.jpg"><img  alt="Groovy Portfolio Added" class="centered" src="http://www.justinspradlin.com/images/groovy_portfolio_small.jpg" /></a>
<p>Two code features really shine through in the example above:  Groovy's Triple Quotes and Groovy's <code><strong><a href="http://groovy.codehaus.org/Reading+XML+using+Groovy's+XmlSlurper">XmlSlurper</a></strong></code>.  The triple quotes surrounding the <code>Atom</code> XML allow us to easily write multi-line XML strings without having to worry about escaping special characters.  The <code>XmlSluper</code> meanwhile allows us to easily parse and locate a specific attribute (the portfolio id in this case) within the returned XML string.  Imagine how many lines of Java code it would take to recreate this functionality.</p>
<h3>Placing an Order</h3>
<p>So far our portfolio is pretty boring.  Let's create some stock transactions to add some assets into our portfolio.</p>
<div class="codeBlock">
<pre><code>static <strong>createStockTransaction(</strong>authorizationToken, tickerSymbol, numberOfShares,
                              transactionType, portfolioId<strong>)</strong>{

    StringBuffer transactionURL = new StringBuffer()
    transactionURL.append("<strong>http://finance.google.com/finance/feeds/</strong>")
        .append("<strong>default/portfolios/${portfolioId}/positions/</strong>")
        .append("<strong>${URLEncoder.encode(tickerSymbol)}/transactions</strong>")

    def url = new URL(transactionURL.toString())
    def connection = url.openConnection()

    connection.setRequestProperty("Content-Type", "application/atom+xml")
    connection.setRequestProperty("Authorization",
                                  "GoogleLogin auth=${authorizationToken}")

    String timeFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
    SimpleDateFormat dateFormatter = new SimpleDateFormat(timeFormat)
    String transactionDate = dateFormatter.format(new Date())

    def atomString = """&lt;?xml version='1.0'?&gt;
    &lt;entry xmlns='http://www.w3.org/2005/Atom'
    	xmlns:gf='http://schemas.google.com/finance/2007'
    	xmlns:gd='http://schemas.google.com/g/2005'&gt;
    	  &lt;gf:transactionData date='<strong>${transactionDate}</strong>'
    	      shares=<strong>'${numberOfShares}</strong>' type='<strong>${transactionType}</strong>' /&gt;
    &lt;/entry&gt;"""

    processRequest(connection, atomString)
}</code></pre>
</div>
<p>The concept with this code is basically the same as the <a href="#portfoliocreation">portfolio creation</a> example above.  We create a connection with the correct <code>Content-Type</code> and <code>Authorization</code> headers, define some <code>Atom</code> XML with attributes about the transaction we would like to make, and then <code>POST</code> the XML to a specific URL.  The interesting thing to note about this code is that unlike the other two examples, the URL for creating transactions is not static.  Instead, this URL needs to be parameterized with the portfolio id and ticker symbol of the stock you wish to trade: <code><strong> http://finance.google.com/finance/feeds/default/portfolios/&lt;portfolio id&gt;/
positions/&lt;ticker symbol&gt;/transactions</strong></code>.</p>
<p>Method calls to <code>createStockTransaction()</code> might look something like this:</p>
<div class="codeBlock">
<pre><code>createStockTransaction(authorizationToken, "NASDAQ:JAVA", 10000.00, "Buy", pId)
<strong>sleep(</strong>2000<strong>)</strong>
createStockTransaction(authorizationToken, "NYSE:F", 10000.00, "Buy", pId)
</code></pre>
</div>
<p>This would place an order for 10,000 shares of Sun Microsystems and Ford Motor Company stock.  Notice that the ticker symbol must be preceded by the name of the market on which it trades.  Therefore the ticker symbol we sent to Google to purchase Sun stock is: <strong>NASDAQ:JAVA</strong> because Sun trades on the NASDAQ stock exchange.  Stocks that trade on the New York Stock Exchange would be preceded by the acronym: NYSE (i.e. Ford = NYSE:F). Also notice that it is a good idea to "<code><strong>sleep</strong></code>" between service calls because sending too many requests to Google at once will result in errors.</p>
<p>When we refresh our Google Finance page we will notice these shares placed into our portfolio.</p>
<a href="http://www.justinspradlin.com/images/groovy_portfolio_sun_large.jpg"><img alt="Stocks Purchased" class="centered" src="http://www.justinspradlin.com/images/groovy_portfolio_sun_small.jpg" /></a>
<h3>Conclusion</h3>
<p>This blog post only skims the surface of what is possible using Google's Finance Data API.  The API also allows for RESTful calls to GET, UPDATE and DELETE specific portfolio and transaction feeds.  Overall, I've been incredibly impressed by all of the data and functionality made available through Google's Data APIs.</p>
<p>The code provided in this example should give you a solid foundation to start playing around with Google's Finance API, but it is far from bulletproof.  For example, I don't really do much in the way of error handling or input validation.  So you shouldn't be surprised if things bomb out if you try to sell shares of a stock that you don't own or create a portfolio with the same name as one of your existing portfolios.</p>
<p>The examples I've shown here are very low level because I wanted to learn the basics of REST.  A much easier way to implement the same functionality would be to use <a href="http://code.google.com/apis/gdata/clientlibs.html">Google's Data APIs Client Libraries</a> (which by the way work perfectly well with Groovy).</p>
<h3 id="reference">References</h3>
<br/><a href="http://www.justinspradlin.com/downloads/groovyfinance.zip">Download the Code</a><br/><br/>
<a href="http://code.google.com/apis/gdata/index.html">Google Data API Developers Guide</a><br/>
<a href="http://code.google.com/apis/finance/developers_guide_protocol.html">Google Finance Developers Guide</a><br/>
<a href="http://code.google.com/apis/finance/reference.html">Google Finance Reference</a><br/><br/>
<a href="http://www.xfront.com/REST-Web-Services.html">Building Web Services the REST Way</a><br/>
<a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST Wikipedia Entry</a>
<h3>Disclaimer</h3>
<p>I am in no way endorsing any of the companies mentioned in this blog entry and all company references are for example purposes only.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-groovy/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Groovy Metaprogramming – Creating Behavior on the Fly</title>
		<link>http://www.justinspradlin.com/programming/groovy-metaprogramming-creating-behavior-on-the-fly/</link>
		<comments>http://www.justinspradlin.com/programming/groovy-metaprogramming-creating-behavior-on-the-fly/#comments</comments>
		<pubDate>Tue, 08 Jul 2008 04:07:37 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=14</guid>
		<description><![CDATA[In my previous post I talked about dynamically adding behavior to Groovy classes using either the ExpandoMetaClass or Categories.  These techniques are especially useful if you know which methods you would like to add to your classes prior to actually writing any code.  But what if you don't know which methods you will [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.justinspradlin.com/programming/groovy-metaprogramming-adding-behavior-dynamically/">previous post</a> I talked about dynamically adding behavior to Groovy classes using either the <code>ExpandoMetaClass</code> or Categories.  These techniques are especially useful if you know which methods you would like to add to your classes prior to actually writing any code.  But what if you don't know which methods you will need before code writing time?  What if you want to allow yourself the flexibility to call methods arbitrarily without defining their implementation beforehand?</p>
<p>To the average Java programmer (myself included), the idea of generating methods on the fly might seem bizarre at first, but Groovy's built in method interception capabilities allow programmers to easily realize this type of functionality in their Groovy code.  In <a href="http://www.justinspradlin.com/programming/groovy-metaprogramming-adding-behavior-dynamically/">Groovy Metaprogramming - Adding Behavior Dynamically</a>, I discussed how to add a method to the <code>java.math.BigDecimal</code> class to allow for the conversion of U.S. Dollars (USD) into Euros (EUR).  What if, however, I wanted to convert from USD to British Pounds (GBP) or to Japanese Yen (JPY)?  I could certainly write a method for each of these conversions, but what if there was a better, cleaner, and more flexible way to build in this functionality?</p>
<span id="more-14"></span>
<h2>Groovy's <code>methodMissing()</code></h2>
<p>The magic behind Groovy's ability to create methods on the fly comes from the language's built in facilities for intercepting method calls.  In particular, one practice for intercepting calls in Groovy is to implement the <code>methodMissing()</code> method on your Groovy classes.  Before Groovy throws a <code>MissingMethodException</code> for calls that are made to methods not defined within a class, Groovy first routes the calls through an object's <code>methodMissing()</code> method.  This gives programmers a chance to intercept calls to these non-existing methods and define an implementation for them:</p>
<div class="codeBlock">
	<pre><code>import java.text.NumberFormat

def <strong>exchangeRates</strong> = ['GBP':0.501882, 'EUR':0.630159,
                     'CAD':1.0127, 'JPY':105.87] // (7/2/2008)

<strong>BigDecimal.metaClass.methodMissing</strong> = { String methodName, args ->
    conversionType = methodName[2..-1]
    conversionRate = exchangeRates[conversionType]

    if(conversionRate){
        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US)
        nf.setCurrency(Currency.getInstance(conversionType))

        return nf.format(delegate * conversionRate)
    }

    "No conversion for USD to ${conversionType}"
}

println 2500.00.<strong>inGBP()</strong>
println 2500.00.<strong>inJPY()</strong>
println 2500.00.<strong>inXYZ()</strong></code></pre>
</div>
<p>Notice that in the example above we make calls to the methods: <code><strong>inGBP()</strong></code>, <code><strong>inJPY()</strong></code>, and <code><strong>inXYZ()</strong></code> on the <code>BigDecimal</code> object 2500.00.  Also notice however, that we did not actually define any of these methods on the <code>BigDecimal</code> class.  Instead we override <code>BigDecimal's <strong>methodMissing()</strong></code> method which allows us to intercept calls to these methods (<code>inGBP()</code>, <code>inJPY()</code>, etc.) and create an implementation for them.</p>
<p>Within the <code>methodMissing()</code> method we parse the name of the called method and look up the corresponding conversion rate from the <code><strong>exchangeRate</strong> HashMap</code> which stores conversion rate values for various countries.  In the future it might be nice if this code called a remote service to actually lookup the exchange rates, but for these examples I'll just keep it simple.  If no corresponding conversion rate is found then a message is returned stating that there is "No conversion for USD to &lt;the conversion type specified&gt;" (XYZ in our case).</p>
<div class="outputBlock">
<pre>GBP1,254.70
JPY264,675.00
No conversion for USD to XYZ</pre>
</div>
<h2>Method Caching</h2>
<p>One way to improve the performance of the previous example is to cache the implementation of the method calls that we have intercepted.  This will allow future calls to these methods to be invoked directly and prevent them from having to be routed through the <code>BigDecimal</code> class's <code>methodMissing()</code> method:</p>
<div class="codeBlock">
	<pre><code>import java.text.NumberFormat

def exchangeRates = ['GBP':0.501882, 'EUR':0.630159,
                     'CAD':1.0127, 'JPY':105.87] // (7/2/2008)

BigDecimal.metaClass.methodMissing = { String methodName, args ->
    println "method missing called"

    def <strong>cachedMethod</strong> = { Object[] cmArgs ->
        conversionType = methodName[2..-1]
        conversionRate = exchangeRates[conversionType]

        if(conversionRate){
            NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US)
            nf.setCurrency(Currency.getInstance(conversionType))

            return nf.format(delegate * conversionRate)
        }

        "No conversion for USD to ${conversionType}"
    }

    <strong>BigDecimal.metaClass."${methodName}" = cachedMethod</strong>

    return cachedMethod(args)
}

println 2500.00.inJPY()
println 2500.00.inGBP()
println 2500.00.inGBP()</code></pre>
</div>
<p>In the example above notice that the functionality for the called method is implemented and stored within a closure called <code><strong>cachedMethod</strong></code>.  By storing the functionality within a closure we can then assign it to <code>BigDecimal's metaClass</code> so that subsequent method calls are invoked directly.</p>
<p>In the result we can see that the second call to <code>inGBP()</code> does not get routed through <code>BigDecimal's methodMissing()</code>:</p>
<div class="outputBlock">
<pre>method missing called
JPY264,675.00
method missing called
GBP1,254.70
<strong>GBP1,254.70</strong></pre>
</div>
<h2>Conclusion</h2>
<p>It's not too hard to think of ways that the given code samples could be improved.  Imagine that instead of assuming all <code>BigDecimal</code> objects were defined in USD, that they could represent any currency type and that our future method calls could actually look something like this:</p>
<div class="codeBlock">
	<pre><code>2500.00.fromEURtoCAD()</code></pre>
</div>
<p>The examples given in this blog entry are trivial, but they showcase the power and flexibility that can be gained by using Groovy's metaprogramming capabilities.  These metaprogramming techniques give programmers a powerful tool that can be used within their code, but with this power programmers need to show a great deal of caution.  Imagine if the following method was called on the <code>BigDecimal</code> object in our examples above:</p>
<div class="codeBlock">
	<pre><code>2500.00.someRandomMethod()</code></pre>
</div>
<p>I'm guessing the result would not be desirable.  Programmers should always be sure to code defensively and write unit tests when using Groovy's powerful metaprogramming capabilities.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/programming/groovy-metaprogramming-creating-behavior-on-the-fly/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Groovy Metaprogramming &#8211; Adding Behavior Dynamically</title>
		<link>http://www.justinspradlin.com/programming/groovy-metaprogramming-adding-behavior-dynamically/</link>
		<comments>http://www.justinspradlin.com/programming/groovy-metaprogramming-adding-behavior-dynamically/#comments</comments>
		<pubDate>Mon, 30 Jun 2008 02:00:09 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=13</guid>
		<description><![CDATA[I've been fascinated with languages like Ruby and Groovy ever since being exposed to their dynamic capabilities.  I remember attending a No Fluff Just Stuff conference a few years ago and being awestruck while watching Dave Thomas build a full-blown Rails application within a matter of minutes.  Dynamic languages give programmers the ability [...]]]></description>
			<content:encoded><![CDATA[<p>I've been fascinated with languages like Ruby and Groovy ever since being exposed to their dynamic capabilities.  I remember attending a <a href="http://www.nofluffjuststuff.com/home.jsp">No Fluff Just Stuff</a> conference a few years ago and being awestruck while watching <a href="http://pragdave.blogs.pragprog.com/">Dave Thomas</a> build a full-blown Rails application within a matter of minutes.  Dynamic languages give programmers the ability to write powerful and flexible code that is both readable and concise.  But what is it that gives these languages such great power?  The secret is their metaprogramming capabilities.</p>
<p><a href="http://en.wikipedia.org/wiki/Metaprogramming">Metaprogramming</a> is the ability of a computer language to manipulate other programs (including itself) to add or create functionality in a dynamic fashion.  In Groovy, metaprogramming is especially useful because among other things it gives programmers the ability to easily implement <a href="http://en.wikipedia.org/wiki/Domain_Specific_Language">domain specific languages</a>, create <a href="http://groovy.codehaus.org/Builders">builders</a>, or generate mock objects for <a href="http://groovy.codehaus.org/Unit+Testing">unit testing</a>.  Adding functionality to pre-existing Java or Groovy code can be accomplished by using either the <code>ExpandoMetaClass</code> or Categories.</p>
<span id="more-13"></span>
<p><i>Note: the best way to test the code examples from this blog entry yourself is to simply copy and paste them into a text file saved with a <code>.groovy</code> extension and then run them from the command line.  Running these examples in the <code>GroovyConsole</code> may yield unpredictable results.</i></p>
<h3>The <code>ExpandoMetaClass</code></h3>
<p>The <code>ExpandoMetaClass</code> can be used to dynamically add methods, properties, and constructors to Groovy or Java objects.  These tasks can be accomplished by simply assigning a closure to an object's <code>MetaClass</code>.  For instance, let's pretend that we want to add a method to <code>java.math.BigDecimal</code> that will convert a <code>BigDecimal</code> (in U.S. Dollars) to its equivalent value in Euros.</p>
<div class="codeBlock">
	<pre><code>import java.text.NumberFormat

<strong>BigDecimal.metaClass.inEuros</strong> = {
    def EXCHANGE_RATE = 0.634961 // (6/27/2008)
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US)
    nf.setCurrency(Currency.getInstance("EUR"))
    nf.format(<strong>delegate</strong> * EXCHANGE_RATE)
}

println 2500.00.inEuros()</code>
	</pre>
</div>
<p>To access <code>BigDecimal's MetaClass</code> we simply use the following syntax <strong><code>BigDecimal.metaClass.inEuros</code></strong> and assign it a closure.  Within the closure we set an exchange rate, create a <code>NumberFormat</code> instance, set the currency type to "EUR" (Euros), and multiply the <strong><code>delegate</code></strong> (the <code>BigDecimal</code> we specified) by the exchange rate.  Groovy automatically returns the last line of a closure so our call to <strong><code>println 2500.00.inEuros()</code></strong> will yield the following result:</p>
<div class="outputBlock">
<pre>EUR1,587.40</pre>
</div>
<p>It is also possible to make the code a bit more readable by dropping the parenthesis after the call to <code>inEuros()</code>.  This can be accomplished by setting up <code>inEuros</code> as a property on the <code>BigDecimal</code> class instead of as a method:</p>
<div class="codeBlock">
	<pre><code>import java.text.NumberFormat

<strong>BigDecimal.metaClass.getInEuros</strong> = {->
    def EXCHANGE_RATE = 0.634961 //June 27, 2008
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US)
    nf.setCurrency(Currency.getInstance("EUR"))
    nf.format(delegate * EXCHANGE_RATE)
}

<strong>println 2500.00.inEuros</strong></code>
	</pre>
</div>
<p>Notice that instead of writing <code>inEuros</code> we create a property on the <code>MetaClass</code> by writing <code>getInEuros</code>.  This allows us to drop the parenthesis from <strong><code>println 2500.00.inEuros</code></strong> and yields the same result as the method injection technique described above:</p>
<div class="outputBlock">
<pre>EUR1,587.40</pre>
</div>
<p>For detailed information on the <code>ExpandoMetaClass</code> and all of its uses, be sure to check out the <a href="http://groovy.codehaus.org/ExpandoMetaClass">Groovy User Guide</a>.</p>
<h3 id="categories">Categories</h3>
<p>Methods, properties, and constructors that are injected into a class via the <code>ExpandoMetaClass</code> are available anywhere within your application.  This is a convenient feature if you plan on using the method multiple times but could cause confusion if you only want the changes to take place in isolation.  This is where Categories come into play.  Categories allow you to inject functionality into a class, but these changes only take affect while calling the method from within the built in <strong><code>use()</code></strong> method's code block.</p>
<p>In order to take advantage of the <code>use()</code> method you must provide it with a "Category". A Category is simply a class with static methods that you wish to inject into your class.  Again, the scope of the added functionality is limited to the <code>use()</code> method's calling block.  If we take the exchange rate example from above and modify it to be used as a Category the code will be as follows:</p>
<div class="codeBlock">
	<pre><code>import java.text.NumberFormat

class ExchangeRateUtil  {
    def static inEuros(<strong>self</strong>) {
        def EXCHANGE_RATE = 0.634961 //June 27, 2008
        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US)
        nf.setCurrency(Currency.getInstance("EUR"))
        nf.format(self * EXCHANGE_RATE)
    }
}

<strong>use(</strong>ExchangeRateUtil<strong>)</strong>{
    println 2500.00.inEuros()
}

println 10000.00.inEuros() //throws MissingMethodException</code>
	</pre>
</div>
<p>I've created a new class called <code>ExchangeRateUtil</code> and created a static method called <code>inEuros()</code> within this class.  Notice that method takes a parameter called <strong><code>self</code></strong> which is used to represent the <code>BigDecimal</code> that we specified.  The remainder of the code for the conversion is exactly the same.</p>
<p>To use this category we call the <code>use()</code> method and within its block call the <code>inEuros()</code> method the same way we did in the example above.  The output will be the same for the call that is made within the <code>use()</code> calling block, but when we try to call the <code>inEuros()</code> method outside of the <code>use()</code> block a <code>MissingMethodException</code> is thrown.</p>
<div class="outputBlock">
<pre>EUR1,587.40
Caught: groovy.lang.MissingMethodException: ...</pre>
</div>
<h3>Conclusion</h3>
<p>As you can see, using metaprogramming gives static language programmers a whole new set of tools that can be used to creatively and elegantly arrive at solutions that can otherwise be overly complex in static languages.  In my next blog entry, I'll expand upon this current discussion and explain how we can use metaprogramming to not only add functionality to a class, but to actually create it on the fly with no previous knowledge of the methods that will be called on our class.</p><!-- wp hack--><p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/programming/groovy-metaprogramming-adding-behavior-dynamically/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Easy AOP with GroovyInterceptable</title>
		<link>http://www.justinspradlin.com/programming/easy-aop-with-groovyinterceptable/</link>
		<comments>http://www.justinspradlin.com/programming/easy-aop-with-groovyinterceptable/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 18:56:54 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=11</guid>
		<description><![CDATA[Aspect Oriented Programming (AOP) is a technique that can be used to eliminate the repetition of cross-cutting concerns (logging, security, transaction management, etc.) in code.  AOP is useful because it provides programmers with a single point at which code can be modified and take effect across an entire system, but integrating AOP frameworks into [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">Aspect Oriented Programming (AOP)</a> is a technique that can be used to eliminate the repetition of cross-cutting concerns (logging, security, transaction management, etc.) in code.  AOP is useful because it provides programmers with a single point at which code can be modified and take effect across an entire system, but integrating AOP frameworks into traditional Java applications tends to be somewhat cumbersome and complex.  Conversely, adding AOP-like features into <a href="http://groovy.codehaus.org/">Groovy</a> code is as simple as implementing the <code>GroovyInterceptable</code> interface.</p>
<p>Any Groovy object that implements this interface will automatically have all of its method calls routed through its <code>invokeMethod()</code> (assuming of course that this method has been implemented on the Groovy object itself or on its MetaClass).</p>
<span id="more-11"></span>
<h3>A Simple Example</h3>
<p>Let's take a look at a quick example.  Assume that for whatever reason we want to know the time before and after each call to a method in a class called <code>SimplePOGO</code>.  To accomplish this task in Groovy, we simply implement the <code>GroovyInterceptable</code> interface and the <code>invokeMethod()</code> like this:</p>
<div class="codeBlock">
	<pre><code>class SimplePOGO implements GroovyInterceptable {
    void simpleMethod1(){
        System.out.println("simpleMethod1() called")
    }

    void simpleMethod2(String param1, Integer param2){
        System.out.println("simpleMethod2(${param1},${param2}) called")
        System.out.println("sleeping...")
        Timer.sleep(2000)
    }

    def invokeMethod(String name, args){
        System.out.println("time before ${name} called: ${new Date()}")

        //Get the method that was originally called.
        def calledMethod = SimplePOGO.metaClass.getMetaMethod(name, args)

        //The "?" operator first checks to see that the "calledMethod" is not
	//null (i.e. it exists).
        calledMethod?.invoke(this, args)

        System.out.println("time after ${name} called: ${new Date()}\n")
    }
}

simplePogo = new SimplePOGO()
simplePogo.simpleMethod1()
simplePogo.simpleMethod2("stringParam", 24)</code>
	</pre>
</div>
<p>This code will produce the following output:</p>
<div class="outputBlock">
<pre>time before simpleMethod1 called: Wed Jun 18 12:07:06 EDT 2008
simpleMethod1() called
time after simpleMethod1 called: Wed Jun 18 12:07:06 EDT 2008

time before simpleMethod2 called: Wed Jun 18 12:07:06 EDT 2008
simpleMethod2(stringParam,24) called
sleeping...

time after simpleMethod2 called: Wed Jun 18 12:07:08 EDT 2008</pre>
</div>
<p>Because <code>SimplePOGO</code> implements <code>GroovyInterceptable</code> all calls to its methods will first be routed through its <code>invokeMethod()</code>.  Within the <code>invokeMethod()</code> we print the current time, look up the actual method that was called, call that method, and then print out the current time after execution.</p>
<h3>An Example with Nested Methods</h3>
<p>What happens if we nest methods?  Take a look at this example:</p>
<div class="codeBlock">
	<pre><code>class SimplePOGO implements GroovyInterceptable {

    void simpleMethod1(){
        System.out.println("simpleMethod1() called")
        <strong>simpleMethod2Nested("stringParam", 24)</strong>
    }

    void simpleMethod2Nested(String param1, Integer param2){
        System.out.println("simpleMethod2Nested(${param1},${param2}) called")
        System.out.println("\nsleeping...\n")
        Timer.sleep(2000)
    }

    def invokeMethod(String name, args){
        System.out.println("time before ${name} called: ${new Date()}")

        //Get the method that was originally called.
        def calledMethod = SimplePOGO.metaClass.getMetaMethod(name, args)

        //The "?" operator first checks to see that the "calledMethod" is not
	//null (i.e. it exists).
        calledMethod?.invoke(this, args)

        System.out.println("time after ${name} called: ${new Date()}")
    }
}

simplePogo = new SimplePOGO()
simplePogo.simpleMethod1()</code>
	</pre>
</div>
<p>This code will produce the following output:</p>
<div class="outputBlock">
	<pre>time before simpleMethod1 called: Wed Jun 18 12:07:35 EDT 2008
simpleMethod1() called
time before simpleMethod2Nested called: Wed Jun 18 12:07:35 EDT 2008
simpleMethod2Nested(stringParam,24) called

sleeping...

time after simpleMethod2Nested called: Wed Jun 18 12:07:37 EDT 2008
time after simpleMethod1 called: Wed Jun 18 12:07:37 EDT 2008</pre>
</div>
<p>Not too surprising.  When <code>simpleMethod1()</code> is called, the <code>invokeMethod()</code> in <code>SimplePOGO</code> is called which prints the current time stamp and then executes the <code>simpleMethod1()</code>.  Notice however that <code>simpleMethod1()</code> calls <code>simpleMethod2Nested()</code>.  When this call is made <code>invokeMethod()</code> will again be called so that the "before" time stamp will be printed out again.  When <code>simpleMethod2Nested()</code> finishes executing an "after" time stamp is printed to the screen and control returns to <code>simpleMethod1()</code> which also finishes executing and prints the current time to the screen.</p>
<h3>Gotcha?</h3>
<p>You may have noticed that I used <code>System.out.println()</code> instead of the Groovier <code>println()</code> to print the output to the screen.  This is because <code>println()</code> is a method that is built into the <code>GroovyObject</code> which is extended by all other Groovy objects (including <code>SimplePOGO</code>).  If a call to <code>println()</code> is made within one of <code>SimplePOGO's</code> methods then the <code>invokeMethod()</code> on <code>SimplePOGO</code> will be called again which may lead to output that is not quite expected:</p>
<div class="codeBlock">
	<pre><code>class SimplePOGO implements GroovyInterceptable {

    void simpleMethod1(){
        println "simpleMethod1() called"
    }

    void simpleMethod2(String param1, Integer param2){
        println "simpleMethod2(${param1},${param2}) called"
        println "sleeping..."
        Timer.sleep(2000)
    }

    def invokeMethod(String name, args){
        System.out.println("time before ${name} called: ${new Date()}")

        //Get the method that was originally called.
        def calledMethod = SimplePOGO.metaClass.getMetaMethod(name, args)

        //The "?" operator first checks to see that the "calledMethod" is not
	//null (i.e. it exists).
        calledMethod?.invoke(this, args)

        System.out.println("time after ${name} called: ${new Date()}")
    }
}

simplePogo = new SimplePOGO()
simplePogo.simpleMethod1()
simplePogo.simpleMethod2("stringParam", 24)</code>
	</pre>
</div>
<p>This code will produce the following output:</p>
<div class="outputBlock">
	<pre>time before simpleMethod1 called: Wed Jun 18 12:13:32 EDT 2008
<strong>time before println called: Wed Jun 18 12:13:32 EDT 2008</strong>
simpleMethod1() called
<strong>time after println called: Wed Jun 18 12:13:32 EDT 2008</strong>
time after simpleMethod1 called: Wed Jun 18 12:13:32 EDT 2008
time before simpleMethod2 called: Wed Jun 18 12:13:32 EDT 2008
time before println called: Wed Jun 18 12:13:32 EDT 2008
simpleMethod2(stringParam,24) called
time after println called: Wed Jun 18 12:13:32 EDT 2008
time before println called: Wed Jun 18 12:13:32 EDT 2008
sleeping...
time after println called: Wed Jun 18 12:13:32 EDT 2008
time after simpleMethod2 called: Wed Jun 18 12:13:34 EDT 2008</pre>
</div>
<p>Worse still is if you try to place the <code>println()</code> method inside of the <code>invokeMethod()</code> itself.  This will lead to recursive calls and an eventual <code>StackOverflowError</code>:</p>
<div class="codeBlock">
	<pre><code>class SimplePOGO implements GroovyInterceptable {

    void simpleMethod1(){
        System.out.println("simpleMethod1() called")
    }

    def invokeMethod(String name, args){
    	try {
	    <strong>println("time before ${name} called: ${new Date()}")</strong>

	    //Get the method that was originally called.
	    def calledMethod = SimplePOGO.metaClass.getMetaMethod(name, args)

	    //The "?" operator first checks to see that the "calledMethod" is
            //not null (i.e. it exists).
	    calledMethod?.invoke(this, args)

	    <strong>println("time after ${name} called: ${new Date()}\n")</strong>
	} catch (StackOverflowError soe) {
	    System.out.println("A StackOverflowError was caught")
	    System.exit(0)
	}
    }
}

simplePogo = new SimplePOGO()
simplePogo.simpleMethod1()</code>
	</pre>
</div>
<p>This code will produce the following output:</p>
<div class="outputBlock">
	<pre>A StackOverflowError was caught</pre>
</div>
<h3>Conclusion</h3>
<p>The examples listed above are very simple, but they illustrate how easy it is to implement the powerful features of AOP in Groovy.  It's not too difficult to envision how such a capability could be built into an application to handle a lot of the boiler plate code that tends to crowd non AOP applications.</p><!-- wp hack--><p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/programming/easy-aop-with-groovyinterceptable/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Book Review:  Bulletproof Web Design</title>
		<link>http://www.justinspradlin.com/reviews/book-review-bulletproof-web-design/</link>
		<comments>http://www.justinspradlin.com/reviews/book-review-bulletproof-web-design/#comments</comments>
		<pubDate>Fri, 13 Jun 2008 00:06:02 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[Reviews]]></category>
		<category><![CDATA[Web Design]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=8</guid>
		<description><![CDATA[Author: Dan Cederholm Rating: 4/5
When I first started toying around with computers in the mid-90s one of my favorite things to do was create websites using free services like Geocities and Tripod.  Back then I was guilty of all the deadly web design sins:  table based layouts, pointless animated GIFs, heinous font and [...]]]></description>
			<content:encoded><![CDATA[<a href="http://www.justinspradlin.com/reviews/book-review-bulletproof-web-design"><img src="/images/bpwd2.jpg" alt="Bulletproof Web Design" class="rev_left" /></a><p><strong>Author:</strong> <a href="http://www.simplebits.com/about/dan/">Dan Cederholm</a><br/> <strong>Rating:</strong> 4/5</p>
<p>When I first started toying around with computers in the mid-90s one of my favorite things to do was create websites using free services like <a href="http://geocities.yahoo.com/">Geocities</a> and <a href="http://www.tripod.lycos.com/">Tripod</a>.  Back then I was guilty of all the deadly web design sins:  table based layouts, pointless animated GIFs, heinous font and background color choices, and of course using the dreaded “Under Construction” page.  Today I&#8217;m a little smarter about my design choices and feel that while web design as a whole isn&#8217;t quite where it needs to be, it is getting much better and there&#8217;s no doubt it&#8217;s because of books like <a href="http://www.simplebits.com/publications/bulletproof/">Bulletproof Web Design</a> by Dan Cederholm.</p>
<span id="more-8"></span>
<p>The book centers around designing sites to be accessible and flexible.  A lot of the focus is on font sizing which on the surface may seem trivial, but because of differences among browsers, font size actually ends up having some important implications on accessibility.  One of the most commonly used browsers (Internet Explorer 6) limits a user&#8217;s ability to increase or decrease a site&#8217;s font size if the designer of that site specifies the font size using strict pixel values.  This creates a lot of problems for users with poor vision.  Additionally, table based layouts are also targeted by the author for their excessive markup and rigid design constraints.  In Bulletproof Web Design, Cederholm explains in detail some of the techniques designers can use to avoid these and other common design pitfalls.</p>
<p>Other topics included in the book that I found particularly useful were designing using floats, degrading pages nicely when CSS is not available, and a discussion on fluid vs elastic layouts.</p>
<p>While the book does not offer any revolutionary information, the concepts it does present on quality web design are organized in an efficient and easy to read manner.  The book is filled with code examples and color pictures making it a quick and easy read.  I&#8217;d definitely recommend the book to anyone starting out on a new web project or anyone looking for a refresher on best practices in web design.</p>
<p><i>A bit of a disclaimer:</i> I just launched this blog recently and I know that I&#8217;m being a bit of a hypocrite by not following some of the basic web design principles found in the book being reviewed.  I&#8217;m currently using a simple Wordpress theme built by <a href="http://www.blogohblog.com/">Bob</a> that gets the job done for now, but I&#8217;m looking forward to applying a lot of the principles from the book as I create my own custom theme for this site.</p>]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/reviews/book-review-bulletproof-web-design/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hello World!</title>
		<link>http://www.justinspradlin.com/general/hello-world/</link>
		<comments>http://www.justinspradlin.com/general/hello-world/#comments</comments>
		<pubDate>Thu, 12 Jun 2008 01:02:36 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=10</guid>
		<description><![CDATA[Welcome to Justin Spradlin&#8217;s blog.  This is my personal technology blog focusing on the latest trends in software development.  Be sure to check in often for tutorials, news, and my thoughts on the tools and technologies that I am currently using for development.
Feel free to subscribe to the RSS feed to have the [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to Justin Spradlin&#8217;s blog.  This is <a href="/about">my</a> personal technology blog focusing on the latest trends in software development.  Be sure to check in often for tutorials, news, and my thoughts on the tools and technologies that I am currently using for development.</p>
<p>Feel free to subscribe to the <a href="http://www.justinspradlin.com/feed/">RSS feed</a> to have the latest posts from this site appear directly in your favorite RSS reader.</p>
<p>If you&#8217;d like to contact me, just leave a comment on the site or send me a message via my <a href="http://www.linkedin.com/in/jspradlin">LinkedIn Profile</a>.</p>
<p>Thanks for visiting!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.justinspradlin.com/general/hello-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 0.483 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2018-11-06 01:18:15 -->
