<?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>The Carbon Emitter</title>
	<atom:link href="http://blog.carbonfive.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.carbonfive.com</link>
	<description>The blog of Carbon Five</description>
	<lastBuildDate>Mon, 23 Jan 2012 18:38:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Monkey-Patching iOS with Objective-C Categories Part I: Simple Extensions and Overrides</title>
		<link>http://blog.carbonfive.com/2012/01/23/monkey-patching-ios-with-objective-c-categories-part-1-simple-extensions-and-overrides/</link>
		<comments>http://blog.carbonfive.com/2012/01/23/monkey-patching-ios-with-objective-c-categories-part-1-simple-extensions-and-overrides/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 18:38:45 +0000</pubDate>
		<dc:creator>Rudy Jahchan</dc:creator>
				<category><![CDATA[Mobile]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[monkey-patching]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=5851</guid>
		<description><![CDATA[Have you ever wanted to introduce new functionality to base classes in the iOS SDK? Or just make them work a little bit differently? In order to do so, you must enter the wild and dangerous world of monkey-patching. Monkey-patching &#8230; <a href="http://blog.carbonfive.com/2012/01/23/monkey-patching-ios-with-objective-c-categories-part-1-simple-extensions-and-overrides/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Have you ever wanted to introduce new functionality to base classes in the iOS SDK? Or just make them work a <strong>little bit</strong> differently? In order to do so, you must enter the wild and dangerous world of monkey-patching.</p>

<p>Monkey-patching is extending or modifying the behavior of code at runtime <strong>without</strong> changing its original source code. You can monkey-patch any code, it doesn&#8217;t matter whether it&#8217;s your own code or not. This is distinctly different than traditional sub-classing because you are not creating a new class, instead, you are reopening an existing class and changing its behavior.</p>

<p>Monkey-patching is possible in Objective-C by using <a href="http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html">categories</a>. In fact, the definition of a category practically matches that of monkey-patching:</p>

<p><code>"A category allows you to add methods to an existing class—even to one for which you do not have the source."</code></p>

<p>In this series of posts, we&#8217;ll use categories to add and change methods, to add new instance variables and properties, and introduce swizzling, a technique that allows us to extend and preserve existing functionality.<span id="more-5851"></span> <a href="#tldr"><strong>TL;DR &raquo;</strong></a></p>

<h2>Category Basics</h2>

<p>To modify an existing class specify the category in both its interface and implementation definitions:</p>

<h4>Interface Definition</h4>

<script src="https://gist.github.com/1660134.js?file=AClassACategoryImplementation.h"></script>

<h4>Implementation</h4>

<script src="https://gist.github.com/1660134.js?file=AClassACategoryImplementation.m"></script>

<h2>Adding Simple Methods</h2>

<p>The most basic usage of categories is to add a new method to an existing class.</p>

<p>Suppose in our application we want to output dates relative to the current time, e.g., &#8220;13 minutes ago&#8221;, &#8220;4 hours ago&#8221;, &#8220;just now&#8221;, etc. Traditional object-oriented solutions would have us introducing a new class that either extends <code>NSDate</code> (e.g., creating a <code>RelativeDescriptionDate</code> subclass with a <code>timeAgoInWords</code> instance method) or is a standalone helper/utility class (e.g., <code>[NSDateHelper timeAgoInWordsFromDate:myDate]</code>).</p>

<p>But with categories, we can reopen the <code>NSDate</code> class and simply add a new instance method:</p>

<h4>NSDate+Formatting.h</h4>

<script src="https://gist.github.com/1660134.js?file=NSDateFormatting.h"></script>

<h4>NSDate+Formatting.m</h4>

<script src="https://gist.github.com/1660134.js?file=NSDateFormatting.m"></script>

<p>Now <strong>every</strong> <code>NSDate</code> object will have the new method available to it. The following code:</p>

<script src="https://gist.github.com/1660134.js?file=UsingNSDateFormatting.m"></script>

<p>Will print out the following on the console:</p>

<script src="https://gist.github.com/1660134.js?file=gistfile1.sh"></script>

<h2>The Dangers of Simply Overriding Methods</h2>

<p>We can take this a step further and instead of adding new behavior we&#8217;ll override existing behavior. Continuing with our example, what if we wanted the default description of a <code>NSDate</code> object to include the time ago in words? We could simply do the following:</p>

<script src="https://gist.github.com/1660134.js?file=NSDateFormatting2.m"></script>

<p>However, this is <strong>strongly discouraged</strong> for two reasons.</p>

<ol>
<li>Other frameworks may rely on the expected behavior of the original method. We now have to go through the trouble of re-implementing that behavior, in addition to the new functionality we wanted to introduce, or risk strange side effects and possibly even crashing out. </li>
<li>If multiple categories implement the same method, the last one loaded wins! The load order is consistent within an application, but it&#8217;s arbitrary, out of our hands, and fragile. For all we know, our implementation could itself be overwritten by an internal framework category!</li>
</ol>

<p>Because of these reasons, this blunt approach to overriding methods should only be used for the simplest of cases. Later in this series, we&#8217;ll explore how swizzling allows us to override a method while preserving all implementations.</p>

<h2>Including Your Monkey-Patches</h2>

<p>Categories are not automatically &#8220;picked up&#8221; in a project. Any code that relies on the behavior will need to <code>#import</code> the necessary header files:</p>

<script src="https://gist.github.com/1660134.js?file=EntryCell.m"></script>

<p>However, including the same set of headers over and over again is redundant. We should first create a single header file that imports all of our most frequently used categories:</p>

<script src="https://gist.github.com/1660134.js?file=Extensions.h"></script>

<p>We can then import this single header file into a prefix header that is added to all source files. XCode projects often have a <code>.pch</code> file in the Supporting Files group for this very purpose.</p>

<script src="https://gist.github.com/1660134.js?file=pc.h"></script>

<h2>Next Up</h2>

<p>While adding and overriding classes is straightforward, there is one very big caveat when using Categories; you <strong>cannot add new instance variables</strong> to a class. We&#8217;ll take a look at working around this limitation in the next post.</p>

<h2><a name="tldr"></a> tl;dr</h2>

<ul>
<li>Use Objective-C categories to add functionality to existing classes without subclassing.</li>
<li>Avoid simple overrides with categories as it can cause problems with other frameworks.</li>
<li>Use prefix headers to easily import your extensions.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2012/01/23/monkey-patching-ios-with-objective-c-categories-part-1-simple-extensions-and-overrides/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Display Line Numbers on Embedded Gists</title>
		<link>http://blog.carbonfive.com/2012/01/12/display-line-numbers-on-embedded-gists/</link>
		<comments>http://blog.carbonfive.com/2012/01/12/display-line-numbers-on-embedded-gists/#comments</comments>
		<pubDate>Thu, 12 Jan 2012 22:59:45 +0000</pubDate>
		<dc:creator>Steven Harms</dc:creator>
				<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=5763</guid>
		<description><![CDATA[I've been working on a post here for C5 and in order to make my points, I was referencing gists hosted by GitHub. When those gists were shown as embeds, the line numbers, and thus the clarity of my documentation, &#8230; <a href="http://blog.carbonfive.com/2012/01/12/display-line-numbers-on-embedded-gists/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><script type="text/javascript"></p>
<p>/*
  * Add this to the top of your post.  This will get interpreted in and applies to your page
  * e.g.
  * 
  * (this code)
  *
  * # My Summer Vacation
  *
  * ## Grandma's House
  * 
  * We left for Grandma's house at 2pm on Friday.  I was so excited to see her pet Bear and Fox!
*/</p>
<p>var fixGistRules = [
".gist .gist-highlight {  border-left: 3ex solid #eee;  position: relative;}",
".gist .gist-highlight pre { counter-reset: linenumbers;}",
".gist .gist-highlight pre div:before { color: #aaa; content: counter(linenumbers); counter-increment: linenumbers;  left: -3ex; position: absolute; text-align: right; width: 2.5ex;}" ];</p>
<p>var head = document.getElementsByTagName('head')[0],
    style = document.createElement('style');</p>
<p>rules = new Array();
var i=0;
for ( i=0; i< fixGistRules.length; i++ ){
  var fullrule = document.createTextNode(fixGistRules[i]);
  rules.push(fullrule);
}</p>
<p>style.type = 'text/css';</p>
<p>for ( var i=0; i< rules.length; i++ ){
  if(style.styleSheet){
    style.styleSheet.cssText = rules[i].nodeValue;
  }else {
    style.appendChild(rules[i]);
    head.appendChild(style);
  }
}
</script></p>
<p>I've been working on a post here for C5 and in order to make my points, I was referencing gists hosted by <a href="http://github.com">GitHub</a>.  When those gists were shown as embeds, the line numbers, and thus the clarity of my documentation, was lost.  We use Markdown for the creation of the texts so I needed something I could write inside of a Markdown post that would be applied as CSS.</p>
<p>Thanks to these tips:</p>
<ol>
<li><a href="http://www.whyhat.com/2012/01/line-numbers-on-embedded-gists">http://www.whyhat.com/2012/01/line-numbers-on-embedded-gists</a></li>
<li><a href="http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript">http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript</a></li>
</ol>
<p>I was able to come up with the following:</p>
<p><script src="https://gist.github.com/1603633.js"> </script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2012/01/12/display-line-numbers-on-embedded-gists/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Does My Rails App Need a Service Layer?</title>
		<link>http://blog.carbonfive.com/2012/01/10/does-my-rails-app-need-a-service-layer/</link>
		<comments>http://blog.carbonfive.com/2012/01/10/does-my-rails-app-need-a-service-layer/#comments</comments>
		<pubDate>Tue, 10 Jan 2012 17:28:33 +0000</pubDate>
		<dc:creator>Jared Carroll</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[service]]></category>
		<category><![CDATA[service layer]]></category>
		<category><![CDATA[service-oriented design]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=5664</guid>
		<description><![CDATA[Sometimes during domain modeling you come across something that isn&#8217;t a thing. These operations that don&#8217;t quite belong to an object are called services. Services often live in a separate, service layer. The service layer lies between controllers and models, &#8230; <a href="http://blog.carbonfive.com/2012/01/10/does-my-rails-app-need-a-service-layer/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>
Sometimes during domain modeling you come across something that isn&#8217;t a thing. These operations that don&#8217;t quite belong to an object are called <strong>services</strong>. Services often live in a separate, service layer. The <strong>service layer</strong> lies between controllers and models, defining an application&#8217;s interface, its API.
</p>
<p>
Designing with services and a service layer is popular in the Java J2EE/Spring community. However, it&#8217;s not common in the Rails world. Is this because of the Ruby community&#8217;s general backlash against the complexity of Java? Or has the rise of HTTP-based JSON APIs made this architecture obsolete? To answer these questions, let&#8217;s take a deeper look at services and the benefits of a service layer.
</p>
<p><span id="more-5664"></span></p>
<h2>What is a Service?</h2>
<p>
In <a href="http://domaindrivendesign.org/books/evans_2003">Domain-Driven Design</a>, Evans defines a <strong>service</strong> as an operation offered as an interface that stands alone in the model. In other words, a service is an action, not a thing. And instead of forcing the operation into an existing object, we should encapsulate it in a separate, stateless service.
</p>
<p>
It&#8217;s not always clear what logic constitutes a service. Taken to the extreme, domain models could be stripped entirely of their domain logic, and turned into nothing but simple data structures (an <a href="http://martinfowler.com/bliki/AnemicDomainModel.html">AnemicDomainModel</a>). A good heuristic is to look for large, domain objects doing too much work and try to break their multiple responsibilities into separate services. At other times it may be your own intuition telling you that some logic just doesn&#8217;t feel to be in the right place. To get started, it&#8217;s helpful to classify services into different types.
</p>
<h2>Types of Services</h2>
<p>
<a href="http://domaindrivendesign.org/books/evans_2003">Evans</a> defines three types of services:
</p>
<ul>
<li>Application</li>
<li>Domain</li>
<li>Infrastructure</li>
</ul>
<h2>Application Services</h2>
<p>
An <strong>application service</strong> is a service that provides non-infrastructure related operations that wouldn&#8217;t come up when discussing the domain model outside the context of software, i.e., in its natural environment.
</p>
<p>
Exporting account transactions as a CSV file in a banking app is an example of an application service because a file format, CSV, has no meaning in the domain of banking.
</p>
<p><script src="https://gist.github.com/1575859.js"> </script></p>
<p>
Application services improve the cohesiveness of your domain model by preventing &#8220;software&#8221; implementation details from leaking into it.
</p>
<h2>Domain Services</h2>
<p>
A <strong>domain service</strong> scripts a use-case involving multiple domain objects. Forcing this logic into a domain object is awkward because these use-cases often involve rules outside the responsibility of any single object.
</p>
<p>
Continuing with the banking app, a funds transfer would be an example of a domain service. Transferring funds doesn&#8217;t quite fit in either of the involved account objects, or perhaps a customer object, so it becomes a standalone service.
</p>
<p><script src="https://gist.github.com/1575860.js"> </script></p>
<p>
An alternative implementation, could be an instance method on <code>Account</code>, taking the amount and destination account as parameters. However, transferring money between accounts feels like the responsibility of another object, not a core responsibility of an account. Domain services like this one really help maintain the core responsibilities of your domain objects.
</p>
<p>
Another example of a domain service is a sitewide search across multiple domain models. Since it searches across multiple domain models it doesn&#8217;t conceptually fit in any one particular model. Instead, it should live in a separate search service.
</p>
<p><script src="https://gist.github.com/1575862.js"> </script></p>
<p>
Simple CRUD operations are <strong>not</strong> domain services. For example, I would consider the following an anti-pattern:
</p>
<p><script src="https://gist.github.com/1575866.js"> </script></p>
<p>
Sure, this does make the <code>UserController</code> independent of the domain model, but this type of flexibility is premature. Instead, the controller should interact directly with the domain model when creating a new <code>User</code>. Domain services should be short scripts, not simple 1-liners that delegate to an almost identical domain model interface.
</p>
<h2>Infrastructure Services</h2>
<p>
An <strong>infrastructure service</strong> encapsulates access to an external system. Infrastructure services are often used by application and domain services.
</p>
<p>
E-mailing and message queuing are two examples of infrastructure logic that has no place in a domain model.
</p>
<p><script src="https://gist.github.com/1575867.js"> </script></p>
<p>
Infrastructure services make your domain model more reusable by separating out non-domain, &#8220;software&#8221; concerns.
</p>
<h2>What is a Service Layer?</h2>
<p>
In <a href="http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420">PoEAA</a>, Stafford defines a <strong>service layer</strong> as an application&#8217;s boundary and set of available operations from the perspective of interfacing client layers. In other words, it&#8217;s your application&#8217;s API.
</p>
<p>
Let&#8217;s take a look at some of the benefits of a service layer to see if they are useful in the Rails world.
</p>
<h2>Supporting Multiple Clients</h2>
<p>
In most web apps, the API mainly consists of simple CRUD use-cases. Encapsulating your application&#8217;s API, allows it to be reused across multiple client controllers, for example, an HTML and a Thrift client. The resulting controllers are thinner, and more cohesive.
</p>
<p>
I see this reuse across multiple clients as less and less of a benefit because of the popularity of HTTP-based JSON APIs. Most apps will typically have an HTML client and a few additional clients, for example, an iPhone and a console app, but the same controllers will serve both HTML and JSON. In a way, the controllers have become the services because all clients talk to the app over HTTP.
</p>
<p>
This reuse was more valuable when you could have non-HTTP based clients, for example, an Adobe Flash app using <a href="http://hessian.caucho.com/ria/">Hessian</a>.
</p>
<h2>Encapsulating Application Logic</h2>
<p>
<a href="http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420">Stafford</a> separates business logic into domain and application logic. <strong>Domain logic</strong> being purely the problem domain. <strong>Application logic</strong> dealing with technical responsibilities, for example, coordinating a workflow or sending an email.
</p>
<p>
In order to build a more cohesive and reusable domain model, application logic should be handled by infrastructure services, possibly in a service layer. Putting application logic into a domain model that&#8217;s used by multiple clients may have unwanted side effects. For example, if you want HTML clients to be emailed after user registration but don&#8217;t want your JSON API clients to be notified at all. So instead of emailing users from the domain model&#8230;
</p>
<p><script src="https://gist.github.com/1575868.js"> </script></p>
<p>
&#8230;let your controller ask a service to do it.
</p>
<p><script src="https://gist.github.com/1575869.js"> </script></p>
<p>
The Rails community definitely has gone back and forth on where to put application logic. Creating a service layer for it is too much though. Instead, put it the appropriate <code>respond_to</code> block in your controllers.
</p>
<h2>Applying Cross-Cutting Concerns</h2>
<p>
Java web apps using the <a href="http://www.springsource.org/">Spring Framework</a>, commonly use services to apply cross-cutting concerns, for example, transaction management and security.
</p>
<p>
Transaction management is a common justification for a service layer, specifically transaction management spanning multiple transactional resources. For example, in the Spring Framework, it&#8217;s possible to atomically write to a database, send an email, and enqueue a message.
</p>
<p>
In a Rails app, <code>ActiveRecord</code> provides automatic, and if necessary manual, transaction management. I can&#8217;t say I&#8217;ve ever thought much about transaction management across multiple transactional resources, but I see no reason for it not to belong in a controller. I&#8217;m not entirely sure why Spring discouraged transaction management at the controller level. Maybe for easier testing.
</p>
<h2>When Should I Use A Service Layer</h2>
<p>
<strong>The only reason to use a service layer is if you have to support multiple clients using different protocols.</strong>  HTTP and JSON have become the de facto client communication protocol and format, eliminating the need for a service layer. The additional indirection and flexibility of a service layer should only be considered when you have to add a client that doesn&#8217;t speak HTTP. However, it&#8217;s still beneficial to use Evans-like services from your controllers in order to encapsulate domain, application, and infrastructure logic and preserve the cohesiveness of your domain model. Always remember to only build for today, not what could happen tomorrow.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2012/01/10/does-my-rails-app-need-a-service-layer/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Exploring Client-side MVC with Backbone.js</title>
		<link>http://blog.carbonfive.com/2011/12/19/exploring-client-side-mvc-with-backbonejs/</link>
		<comments>http://blog.carbonfive.com/2011/12/19/exploring-client-side-mvc-with-backbonejs/#comments</comments>
		<pubDate>Mon, 19 Dec 2011 16:55:48 +0000</pubDate>
		<dc:creator>Jared Carroll</dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[backbonejs]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=5609</guid>
		<description><![CDATA[Backbone.js continues to gain popularity in the JavaScript MVC community. I decided to give it a try by creating a simple, single-page app to CRUD a single domain model. While it wasn&#8217;t as trivial as a traditional server-side implementation in &#8230; <a href="http://blog.carbonfive.com/2011/12/19/exploring-client-side-mvc-with-backbonejs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://documentcloud.github.com/backbone">Backbone.js</a> continues to gain popularity in the JavaScript MVC community. I decided to give it a try by creating a simple, single-page app to CRUD a single domain model.
</p>
<p>
While it wasn&#8217;t as trivial as a traditional server-side implementation in Rails, it did turn out relatively clean. This is a long post, and if you make it through it, let me know what you think.
</p>
<p><span id="more-5609"></span></p>
<h2>Server-side Setup</h2>
<p>
Our server-side is a stock Rails 3.1 app. We&#8217;ll go with a classic blog app consisting of a single <code>Post</code> model to CRUD.
</p>
<p><script src="https://gist.github.com/1493846.js?file=gistfile1.sh"></script></p>
<p>
We&#8217;ll use the <a href="https://github.com/meleyal/backbone-on-rails">backbone-on-rails</a> Ruby gem to add <em>backbone.js</em> and <em>underscore.js</em> (backbone.js&#8217;s only dependency) to our Rails app.
</p>
<p><script src="https://gist.github.com/1493848.js"></script></p>
<p>
The <em>backbone.js</em> and <em>underscore.js</em> files are <strong>not</strong> copied into your Rails app&#8217;s directory. They&#8217;re both automatically loaded by the <code>backbone-on-rails</code> gem (the <code>jquery-rails</code> Ruby includes <em>jquery.js</em> and <em>jquery_ujs.js</em> the same way).
</p>
<p>
Let&#8217;s use the scaffold generator from <code>backbone-on-rails</code> to generate our client-side Backbone.js objects.
</p>
<p><script src="https://gist.github.com/1493849.js"> </script></p>
<p>
We&#8217;ll be using CoffeeScript, the Rails default client-side language, throughout our Backbone app.  CoffeeScript&#8217;s cleaner, Ruby-like syntax will help make the code more readable and understandable.
</p>
<h2>Listing Posts</h2>
<p>
We&#8217;ll start our app by implementing a &#8220;Read&#8221; action, the homepage. The homepage will be a list of all our posts. The <code>backbone-on-rails</code> scaffold generator has already created for us a router, an index view and template, a collection, and a model. To wire up the homepage we&#8217;ll need to modify our router.
</p>
<p>
Backbone routers are like controllers in Rails. They map routes to actions. The empty route represents the default action, in our case, the homepage.
</p>
<p><em>app/assets/javascripts/routers/posts_router.js.coffee</em><br />
<script src="https://gist.github.com/1493850.js"> </script></p>
<p>
In our <code>index</code> action, we create a <code>Posts</code> collection, a view for the collection, and then tell the collection to fetch its posts from the server. We don&#8217;t tell the view to render itself because the fetch is asynchronous. We&#8217;ll see later how the view uses an event handler to render itself after the fetch.
</p>
<p>
The <code>Posts</code> collection is configured to make server-side requests to our Rails app at &#8220;/posts&#8221; and to contain <code>Post</code> models.
</p>
<p><em>app/assets/javascripts/collections/posts.js.coffee</em><br />
<script src="https://gist.github.com/1493863.js"> </script></p>
<p>
Our <code>Post</code> model is as simple as it gets. It&#8217;s just a <code>Backbone.Model</code> subclass and contains no custom logic.
</p>
<p><em>app/assets/javascripts/models/post.js.coffee</em><br />
<script src="https://gist.github.com/1493865.js"> </script></p>
<p>
Before we take a look at the <code>PostsIndex</code> view, let&#8217;s first quickly go over the Rails layout used on the server-side.
</p>
<p><em>app/views/layouts/application.html.erb</em><br />
<script src="https://gist.github.com/1493867.js"> </script></p>
<p>
The only change we&#8217;ve made to this default Rails layout is the addition of a single &#8220;#app&#8221; <code>&lt;div&gt;</code>. This <code>&lt;div&gt;</code> will act as the container for our app. Each Backbone view will replace its contents.
</p>
<p>
Now we can take a look at the Backbone view.
</p>
<p><em>app/assets/javascripts/views/posts/posts_index.js.coffee</em><br />
<script src="https://gist.github.com/1493868.js"> </script></p>
<p>
On initialization, the view binds its <code>render</code> method as a handler to its collection&#8217;s <code>reset</code> event (this is the <code>Posts</code> collection we created in the <code>Blog.Routers.Posts#index</code> action). The <code>Posts</code> collection will trigger a <code>reset</code> event after successfully fetching its posts from the server. When the event is fired, the view will render its template and create and render another view for each <code>Post</code> in its collection.
</p>
<p>
Here&#8217;s the template used by the <code>PostsIndex</code> view:
</p>
<p><em>app/assets/templates/posts/index.jst.eco</em><br />
<script src="https://gist.github.com/1493870.js"> </script></p>
<p>
This table will be populated by the view used for each post in the collection:
</p>
<p><em>app/assets/javascripts/views/posts/posts_item.js.coffee</em><br />
<script src="https://gist.github.com/1493874.js"> </script></p>
<p>
And its template:
</p>
<p><em>app/assets/templates/posts/item.jst.eco</em><br />
<script src="https://gist.github.com/1493879.js"> </script></p>
<p>
There&#8217;s one last thing we need to do before we can view our homepage in a browser: we have to bootstrap our app&#8217;s router.
</p>
<p><em>app/assets/javascripts/blog.js.coffee</em><br />
<script src="https://gist.github.com/1493882.js"> </script></p>
<p>
An <code>onDOMReady</code> event handler invokes an <code>init</code> function that creates a <code>PostsRouter</code> and tells Backbone to start monitoring all hashchange events. All our client-side pages will use hash fragments as URLs. Backbone will listen for hash fragment changes and route them using the routes specified in our <code>PostsRouter</code>.
</p>
<p>
Finally we can now start our Rails server and hit our app at <a href="http://localhost:3000/posts">http://localhost:3000/posts</a>. Unfortunately, we don&#8217;t have any posts yet. So let&#8217;s move on to creating a post.
</p>
<h2>Creating a Post</h2>
<p>
At the bottom of our existing home template is a link to create a new post:
</p>
<p><em>app/assets/templates/posts/index.jst.eco</em><br />
<script src="https://gist.github.com/1493885.js"> </script></p>
<p>
This means we need to add another route and action to our <code>PostsRouter</code>.
</p>
<p><em>app/assets/javascripts/routers/posts_router.js.coffee</em><br />
<script src="https://gist.github.com/1493888.js"> </script></p>
<p>
In our <code>new</code> action, we create a <code>Post</code> model, then create a <code>Posts</code> collection and bind an anonymous handler to its <code>add</code> event. A collection will fire an <code>add</code> event whenever a new model is added to it. Our <code>add</code> event handler performs the equivalent of a server-side redirect by navigating the router to the &#8220;empty&#8221; router (the homepage). Finally we create and render a view to submit a new post.
</p>
<p><em>app/assets/javascripts/views/posts/posts_new.js.coffee</em><br />
<script src="https://gist.github.com/1493889.js"> </script></p>
<p>
The element (<code>PostsNew#el</code>) used in our new post view is the global &#8220;#app&#8221; <code>&lt;div&gt;</code>. The new post view will replace the contents of this <code>&lt;div&gt;</code> with its own template containing a form to submit a new post.
</p>
<p>
The view also registers a handler to the submit event from the <code>&lt;form&gt;</code> in its template. This handler stops the default form submission behavior and then asks its posts collection to create a new post. This will result in an HTTP POST request to the server and, if successful, the collection will fire an <code>add</code> event. This is the same event our <code>PostsRouter</code>, in its <code>new</code> action, bound an anonymous &#8220;redirect&#8221; handler to.
</p>
<p>
And here is the new post view&#8217;s template:
</p>
<p><em>app/assets/templates/posts/new.jst.eco</em><br />
<script src="https://gist.github.com/1493891.js"> </script></p>
<p>
Great, we can now create posts. However, we can&#8217;t let people create posts without a title and a body. Let&#8217;s see what we can do to validate our new posts.
</p>
<h2>Validating a Post</h2>
<p>
Adding some client-side validation will help improve the responsiveness of our UI. We&#8217;ll still validate posts on the server-side, but for the user&#8217;s sake, I feel this duplication is worth the tradeoff.
</p>
<p>
Backbone models include a <code>validate</code> method that can be used to perform custom validations. However, as Rails developers we&#8217;re used to <code>ActiveRecord</code>&#8216;s high-level, declarative approach to validation. And thanks to the <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery validation plugin</a>, we can have declarative validation on the client-side too.
</p>
<p>
First, download the plugin (<strong>after downloading and unzipping it, remember to restart your Rails server</strong>).
</p>
<p><script src="https://gist.github.com/1493892.js"> </script></p>
<p>
Next, add the plugin to our application&#8217;s JavaScript manifest file.
</p>
<p><em>app/assets/javascripts/application.js</em><br />
<script src="https://gist.github.com/1493895.js"> </script></p>
<p>
Now we can add some validation to our new posts.
</p>
<p><em>app/assets/javascripts/views/posts/posts_new.js.coffee</em><br />
<script src="https://gist.github.com/1493896.js"> </script></p>
<p>
The jQuery validate plugin allows you to specify per-attribute validation rules. Here we&#8217;re requiring a title and a body.  The <code>validate</code> method will stop the form submission when validation fails. This will also prevent the new post view&#8217;s form submission handler, <code>#create</code>, from executing as well.
</p>
<p>
Go and give it a try in the browser. Submitting a post without a title and body will now fail and display an error message(s).
</p>
<h2>Viewing a Post</h2>
<p>
Ok, so far we can display a list of posts, create a post, and validate a post. Next up is: viewing an individual post.
</p>
<p>
On our home page, each post row included the following link for viewing the post:
</p>
<p><em>app/assets/templates/posts/item.jst.eco</em><br />
<script src="https://gist.github.com/1493897.js"> </script></p>
<p>
Let&#8217;s add a route and action to our router for this post page (i.e., <code>#show</code>).
</p>
<p><em>app/assets/javascripts/routers/posts_router.js.coffee</em><br />
<script src="https://gist.github.com/1493898.js"> </script></p>
<p>
This newest route includes a named parameter, <code>:id</code>. Backbone will automatically pass the named parameter&#8217;s value as an argument to our <code>#show</code> action.
</p>
<p>
Currently in Backbone, fetching an individual model isn&#8217;t very elegant. Above is one of the cleanest ways. You first create a model with the requested id, then add the model to a collection, and finally, tell the model to <code>fetch</code> itself.
</p>
<p>
Our <code>#show</code> action also creates an instance of the following <code>PostsShow</code> view for the individual post.
</p>
<p><em>app/assets/javascripts/views/posts/posts_show.js.coffee</em><br />
<script src="https://gist.github.com/1493900.js"> </script></p>
<p>
During initialization, the view adds a handler to its <code>Post</code>&#8216;s <code>change</code> event. The <code>Post</code> will fire a <code>change</code> event after it has been successfully <code>fetch</code>ed.
</p>
<p>
The element (<code>PostsShow#el</code>) for this view is the same global &#8220;#app&#8221; <code>&lt;div&gt;</code> container that was used by the post list and new post views. And like those two views, an individual post view will also replace the contents of this <code>&lt;div&gt;</code>.
</p>
<p>
And here&#8217;s the posts show view&#8217;s template:
</p>
<p><em>app/assets/templates/posts/show.jst.eco</em><br />
<script src="https://gist.github.com/1493901.js"> </script></p>
<p>
The &#8220;back&#8221; link goes back to our homepage.
</p>
<h2>Client-side MVC</h2>
<p>
Backbone.js brings the power and maintainability of MVC to the client-side. Routers can be used like Rails server-side controllers to create responsive, single-page apps. Views are also like controllers, but instead of responding to url changes, they respond to DOM level events, such as link clicks and form submissions. Templates contain the app&#8217;s markup, they&#8217;re what Rails calls views. Models and collections round out Backbone.js, providing traditional class-based, client-side domain modeling.
</p>
<p>
We&#8217;ve only covered the first two letters in CRUD, but it was a lot!  I hope this article can give you some direction in implementing the rest of them. The client-side JavaScript MVC space is growing rapidly. Backbone&#8217;s quick and easy Rails integration makes it an easy sell but there are other options. Be sure to research other frameworks before evaluating what works best for you.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2011/12/19/exploring-client-side-mvc-with-backbonejs/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Configuration for Rails, the Right Way</title>
		<link>http://blog.carbonfive.com/2011/11/23/configuration-for-rails-the-right-way/</link>
		<comments>http://blog.carbonfive.com/2011/11/23/configuration-for-rails-the-right-way/#comments</comments>
		<pubDate>Wed, 23 Nov 2011 23:19:16 +0000</pubDate>
		<dc:creator>Mike Perham</dc:creator>
				<category><![CDATA[Everything Else]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=5589</guid>
		<description><![CDATA[I still see people promoting various gems and plugins to handle miscellaneous configuration elements for your application. One little known secret is that Rails 3 allows you to define your own configuration elements trivially. In this case, I wanted to &#8230; <a href="http://blog.carbonfive.com/2011/11/23/configuration-for-rails-the-right-way/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I still see people promoting various gems and plugins to handle miscellaneous configuration elements for your application.  One little known secret is that Rails 3 allows you to define your own configuration elements trivially.</p>
<p>In this case, I wanted to use the nifty <code>wkhtmltopdf</code> utility to create a PDF.  I was able to call the binary just fine with Homebrew on OSX but found that I had to use a custom binary checked into git for our production environment on Heroku.  So I created a configuration variable to store where <code>wkhtmltopdf</code> could be found in the current environment.</p>
<p>First, we define a default value for all environments in <code>config/application.rb</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
module Configurator
  class Application &lt; Rails::Application
    # By default, let OSX resolve the path to the binary
    config.wkhtmltopdf = &quot;wkhtmltopdf&quot;
  end
end
</pre>
<p>Then we override the default setting as necessary in <code>config/environments/</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
Configurator::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # Point Heroku explicitly to the binary we need to use
  config.wkhtmltopdf = &quot;#{Rails.root}/bin/wkhtmltopdf&quot;
end
</pre>
<p>Lastly, we access the configuration element in our code:</p>
<pre class="brush: ruby; title: ; notranslate">
  cmd = [Configurator::Application.config.wkhtmltopdf, url, tmpfile.path]
</pre>
<p>Yes, that&#8217;s it.  Just use Rails&#8217;s environment support and <code>config</code> to store your own configuration elements.  They&#8217;re trivial to set, trivial to access and require no third-party gems or custom text files.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2011/11/23/configuration-for-rails-the-right-way/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Why We Are an Agile Shop</title>
		<link>http://blog.carbonfive.com/2011/11/22/agile-at-carbon-five/</link>
		<comments>http://blog.carbonfive.com/2011/11/22/agile-at-carbon-five/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 17:30:20 +0000</pubDate>
		<dc:creator>Christian Nelson</dc:creator>
				<category><![CDATA[Process]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[extreme programming]]></category>
		<category><![CDATA[xp]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=5551</guid>
		<description><![CDATA[Last week we had a lively discussion about Agile development at Carbon Five. It was fun telling the story of how we got started with Agile nearly a decade ago. We discussed how it helps us deliver value and deal &#8230; <a href="http://blog.carbonfive.com/2011/11/22/agile-at-carbon-five/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Last week we had a lively discussion about Agile development at Carbon Five. It was fun telling the story of how we got started with Agile nearly a decade ago. We discussed how it helps us deliver value and deal with the challenges we face as a services company. Here&#8217;s a summary of that conversation&#8230;</p>
<p><strong>How does Agile help us to do better work for our clients?</strong></p>
<p>To answer that question, I think it&#8217;s important to reflect on what makes building a product hard. Here&#8217;s a clue: <em>Everything</em>.</p>
<p><span id="more-5551"></span></p>
<p>There are technical challenges, but those are the least of your worries in practically every case (especially early on). There are product questions: who are you building for? what features do your customers really want? how can we validate our hunches in a meaningful way? what incarnation of those features will be both useful and a delight to use? There&#8217;s time pressure. And to add fuel to the fire, the team is made of people. You know&#8230; with ideas, egos, personalities and feelings. It&#8217;s amazing successful products happen, period.</p>
<p>We wanted a process that&#8217;s effortless when it&#8217;s working awesome while also giving us signals when something is broken. We&#8217;re not interested in process just for process&#8217;s sake. It turns out that Agile can help navigate these challenges and gives us pretty clear warning signals.</p>
<h2>At the Core</h2>
<p>In trying to distill out the most important parts of our Agile process, I came up with my take on the essential ingredients. I&#8217;m not saying other aspects aren&#8217;t important too, just that these make a strong foundation.</p>
<ul>
<li>Small units of work</li>
<li>Optimize for value</li>
<li>Iteration</li>
<li>Product owner involvement</li>
<li>Feedback</li>
<li>Honesty and trust</li>
</ul>
<p>If any one of these is missing or broken, the project has a much higher risk of running into trouble. That doesn&#8217;t necessarily mean complete failure, but it does mean the project and overall experience will fall short of its potential.</p>
<p><strong>Small units of work</strong> keep the team focused and allow for greater flexibility when planning. We write user stories and every one of them captures single workflow framed from the user&#8217;s perspective. A story should be whole, meaning it delivers value to the user on its own. Stories normally take a couple of minutes to a couple of days to deliver. When they&#8217;re small it&#8217;s easy to move them around and make tactical decisions during planning. It&#8217;s also easier to avoid needless yak-shaving when the stories are small.</p>
<p>Small units of work aren&#8217;t enough, they must deliver <strong>Value</strong>. We typically measure value in terms of user-facing functionality. We know that some amount of infrastructure, architecture, meetings, etc needs to happen to build a product. However, that&#8217;s not what first draws a customer to a product. It has to solve a customer&#8217;s problem. Getting everyone on the same page about value is crucial, otherwise folks may be optimizing for different things.</p>
<p>Software products evolve over time through the addition of new features, the enhancement of existing features, and removal of unused features. It&#8217;s inherently <strong>Iterative</strong>. We start the process of iteration from week one. By the time a product sees its first ray of light, the team has executed the process of planning, designing, building, and deploying many times. The structure of the process is in place and the team has enough experience with it that it can be repeated confidently.</p>
<p>Knowing that there&#8217;s always an opportunity to iterate on a feature allows us to build the right-sized version of the feature for where we are in the lifecycle of the product. Not every feature needs to have all of the bells and whistles when it&#8217;s born. The time saved can be spent on something that is more valuable.</p>
<p>Every one of our projects has a <strong>Product Owner</strong> who&#8217;s part of the client team. Our goal is to guide and empower the product owner so that they can direct the team&#8217;s focus on what&#8217;s important. Some product owners are very involved and others minimally so. The low bar of involvement includes two important activities: prioritization of stories and acceptance of the stories once they&#8217;re complete. Without these, there&#8217;s no one at the helm and the chance that the client isn&#8217;t going to be happy with the engagement goes up a ton.</p>
<p>There&#8217;s internal and external <strong>Feedback</strong>. <em>External</em> feedback on the product can be collected via a wide array of techniques. Until ideas are validated by customers, they&#8217;re just assumptions. Building features on top of untested assumptions drives up the chance that we&#8217;re building a dud. It might be high-quality code with an extensive set of automated tests, but who cares if no one wants to use it. Building a product without integrating external feedback is like betting everything on your first hand of poker when you haven&#8217;t yet learned the rules.</p>
<p><em>Internal</em> feedback comes from the team and improves the process itself. Reflecting on how it&#8217;s going and making changes to better suit the reality on the ground is critical to keeping the process a good fit throughout the lifetime of the product. Otherwise, the process starts getting in the way when things are going awesome or it starts failing to give signals when it should.</p>
<p>It should go without saying: <strong>Transparency and trust</strong> are key to building a team that can overcome the challenges of building a product. If there&#8217;s bad news, we want to deliver it early so that we&#8217;re in the best position to do something about it and reap the benefits. Without trust, it&#8217;s hard to stay psyched about the people with whom you&#8217;re working. When every action comes from a place of honesty and your intentions true, trust grows naturally.</p>
<h2>Signals</h2>
<p>Here are a couple of the common signals that suggest something&#8217;s up:</p>
<p><strong>Low velocity</strong> &#8211; Velocity is the rate at which the team is completing stories that deliver user-facing value. Really low velocity can be a sign that stories are too big, there are inefficiencies in how work gets done, or the team is spending a lot of time on &#8220;infrastructure&#8221;.</p>
<p><strong>Erratic velocity</strong> &#8211; Often the result of inconsistent planning. When the backlog is well thought out, things move fast. When the team gets to stories that are poorly written or vetted, productivity grinds to a halt.</p>
<p><strong>Slow acceptance</strong> &#8211; The product owner isn&#8217;t providing the team with the feedback it needs to know it&#8217;s doing a good job. Sure, developers move on to the next story, but they may be building on building blocks that miss the mark. It can be a real drag on morale and velocity.</p>
<p><strong>Big bug fix session before a release</strong> - Rather than finding and fixing bugs continuously, the team is delivering stories that are buggy. That debt has to be paid down before the software gets into the hands of users. This creates a false sense of velocity which is knocked down periodically before a release.</p>
<p>Others: Running out of stories, stories are frequently blocked, need for big refactors.</p>
<p>The more experience you have the easier it is to pick up on the signals and figure out what to do about them.</p>
<h2>What about the Developer Practices?</h2>
<p>I&#8217;m leaving developer practices out of this conversation deliberately. Testing, continuous integration, pairing, sustained schedule, etc are all second nature for us. There&#8217;s enough content there for a another article (or several).</p>
<h2>Conclusion</h2>
<p>My experience has shown that if the process includes the above components, we&#8217;re able to rapidly build valuable features. When something isn&#8217;t right and we&#8217;re being perceptive, it becomes apparent quickly and we&#8217;re able to reflect and make the changes necessary to fix the problem. In the end, Agile lets us welcome feedback that inspires course correction while also making it really hard to overlook issues when they come up.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2011/11/22/agile-at-carbon-five/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Event: Our Experience Building OVEE on 12/6</title>
		<link>http://blog.carbonfive.com/2011/11/21/event-our-experience-building-ovee-on-126/</link>
		<comments>http://blog.carbonfive.com/2011/11/21/event-our-experience-building-ovee-on-126/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 18:23:41 +0000</pubDate>
		<dc:creator>Christian Nelson</dc:creator>
				<category><![CDATA[Process]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=5544</guid>
		<description><![CDATA[We just wrapped up the first phase of a project for ITVS, the Independent Television Service, and want to share the experience. We built OVEE, the online video engagement experience, on a short schedule with a small team. OVEE is &#8230; <a href="http://blog.carbonfive.com/2011/11/21/event-our-experience-building-ovee-on-126/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We just wrapped up the first phase of a project for ITVS, the Independent Television Service, and want to share the experience. We built OVEE, the online video engagement experience, on a short schedule with a small team. OVEE is a highly-interactive application built using node.js, mongodb, and a slew of other new tools/frameworks.</p>
<p>Our talk is going to cover product design, process and technology. We want to share the whole experience of building a product, not just the technical details.</p>
<p><strong>Product Design Topics</strong></p>
<ul>
<li>Design and development process</li>
<li>Usability testing</li>
<li>Prioritizing features to match a budget</li>
</ul>
<p><strong>Technical Topics</strong></p>
<ul>
<li>Overview of the architecture and technical stack (node.js, express, jade, socket.io, flash, etc)</li>
<li>Using development spikes to reduce technical risk</li>
<li>Testing node.js</li>
<li>Lessons learned</li>
</ul>
<p>After our talk we&#8217;ll turn it around and open the floor for those in attendance to share their relevant experience, in 5-10 minute mini-talks.</p>
<p>Additional details and RSVP: <a href="http://c5-the-ovee-story.eventbrite.com/">http://c5-the-ovee-story.eventbrite.com/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2011/11/21/event-our-experience-building-ovee-on-126/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Explorations in Go: solving the Instagram engineering challenge</title>
		<link>http://blog.carbonfive.com/2011/11/17/explorations-in-go-solving-the-instagram-engineering-challenge/</link>
		<comments>http://blog.carbonfive.com/2011/11/17/explorations-in-go-solving-the-instagram-engineering-challenge/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 00:37:41 +0000</pubDate>
		<dc:creator>Jon Cooper</dc:creator>
				<category><![CDATA[Everything Else]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=5527</guid>
		<description><![CDATA[The good folks at Instagram posted a fun challenge on their engineering blog recently: "Your challenge, if you choose to accept it, is to write a simple script that takes a shredded image in as input and outputs an unshredded &#8230; <a href="http://blog.carbonfive.com/2011/11/17/explorations-in-go-solving-the-instagram-engineering-challenge/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><script type="text/javascript"></p>
<p>/*
  * Add this to the top of your post.  This will get interpreted in and applies to your page
  * e.g.
  * 
  * (this code)
  *
  * # My Summer Vacation
  *
  * ## Grandma's House
  * 
  * We left for Grandma's house at 2pm on Friday.  I was so excited to see her pet Bear and Fox!
*/</p>
<p>var fixGistRules = [
".gist .gist-highlight {  border-left: 3ex solid #eee;  position: relative;}",
".gist .gist-highlight pre { counter-reset: linenumbers;}",
".gist .gist-highlight pre div:before { color: #aaa; content: counter(linenumbers); counter-increment: linenumbers;  left: -3ex; position: absolute; text-align: right; width: 2.5ex;}" ];</p>
<p>var head = document.getElementsByTagName('head')[0],
    style = document.createElement('style');</p>
<p>rules = new Array();
var i=0;
for ( i=0; i< fixGistRules.length; i++ ){
  var fullrule = document.createTextNode(fixGistRules[i]);
  rules.push(fullrule);
}</p>
<p>style.type = 'text/css';</p>
<p>for ( var i=0; i< rules.length; i++ ){
  if(style.styleSheet){
    style.styleSheet.cssText = rules[i].nodeValue;
  }else {
    style.appendChild(rules[i]);
    head.appendChild(style);
  }
}
</script></p>
<p>The good folks at <a href="http://instagr.am/">Instagram</a> posted a fun challenge on their engineering blog recently:</p>
<blockquote>
<p>"Your challenge, if you choose to accept it, is to write a simple script that takes a shredded image in as input and outputs an unshredded and reconstituted image. That is, imagine if you took an image, divided it into an even number of columns and shuffled those columns randomly to produce a shredded image. Then, take that image into the script and output the original image."</p>
</blockquote>
<p>(The original post is here: <a href="http://instagram-engineering.tumblr.com/post/12651721845/instagram-engineering-challenge-the-unshredder">Instagram Engineering Challenge: The Unshredder</a>).</p>
<p>This struck me as a great opportunity to hack out some code in <a href="http://www.golang.org/">Go</a> (rev 60.1) as part of my continuing exploration of the language and its packages.</p>
<p><span id="more-5527"></span></p>
<h2>The problem</h2>
<p>Here are the input and target output images:</p>
<h3>The shredded version</h3>
<p><img src="http://media.tumblr.com/tumblr_luigsoCv3s1qm4rc3.png" title="shredded" class="alignnone" width="500" height="280" /></p>
<h3>The unshredded version</h3>
<p><img src="http://media.tumblr.com/tumblr_luih7og6QM1qm4rc3.png" title="unshredded" class="alignone" width="500" height="280" /></p>
<p>They offer the following tips:</p>
<ol>
<li>Don’t overthink it. Use of really complex algorithms isn’t needed. Our solution WITH the bonus exercise comes in at just over 150 lines of python.</li>
<li>Think about how you would quantify whether or not two shreds ‘fit’ together by using pixel data</li>
<li>Assume you’re using the source image, or other normal photographs without edge-case patterns.</li>
<li>There are edge cases where the script we wrote with our approach will not work because of repeating patterns. This is OK in your script as well. Don’t worry about special cases – focus on making the sample images work that we’ve provided.</li>
</ol>
<p>Great. The simplest approach that occurred to me was this:</p>
<ol>
<li>Assume the left-most shred is in the right place.</li>
<li>Search the other shreds, find the one that fits best to the right of the first one, then stick it there.</li>
<li>Repeat until you run out of shreds.</li>
<li>Figure which shred is actually the left-most one, then reorder to that configuration by rotating the ring of shreds.</li>
</ol>
<p>As it turns out, this works. My solution is on Github here: <a href="https://github.com/joncooper/instashred">https://github.com/joncooper/instashred</a>. They've run out of t-shirts, though <img src='http://blog.carbonfive.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> , so no soup for me.</p>
<p>Here's a quick tour of the standard library's packages that I used:</p>
<h2>image</h2>
<p>The <code>image.Image</code> interface from the <a href="http://golang.org/pkg/image">image</a> package provides what the docs describe in their typically awesome and laconic manner as "a finite rectangular grid of Colors drawn from a ColorModel."</p>
<p><script src="https://gist.github.com/1374302.js?file=image.Image.go"></script></p>
<p>Basically, the <code>image.Image</code> interface defines a read-only grid of pixels expressed as <code>image.Color</code>, upon which you can call <code>RGBA()</code> to get out a tuple containing alpha-premultiplied channel intensities.</p>
<p>At first the read-only nature of <code>image.Image</code> made me scratch my head a bit. But it ends up being pretty neat. You can do things like create a procedural image which can then be sampled, like this:</p>
<p><script src="https://gist.github.com/1374302.js?file=RandomColorImage.go"></script></p>
<p>The standard library also implements <a href="http://golang.org/pkg/image/#Tiled">image.Tiled</a>, which acts like an infinitely (okay, just extremely large) large tiling of a source image. See the source <a href="http://golang.org/src/pkg/image/names.go?s=1443:1492#L39">here</a>--it's just pretty.</p>
<h2>image/png</h2>
<p>Image file support is minimal but useful at the moment. There are <code>image</code> subpackages that implement decoding/encoding for JPEG and PNG, and decode only for BMP, GIF and TIFF.</p>
<p>Here's an example for how you write an image.Image to a PNG file:</p>
<p><script src="https://gist.github.com/1374302.js?file=WritePNGFile.go"></script></p>
<h2>image/draw</h2>
<p>This package implements image compositing functions and little else. In particular, it doesn't implement vector art staples like line, circle, rectangle, etc.</p>
<p>It's deals solely with compositing images by copying <code>image.Color</code> pixels from one <code>image.Image</code> and pasting them into a <code>draw.Image</code>, optionally using a mask and a <a href="http://en.wikipedia.org/wiki/Alpha_compositing">Porter-Duff</a> compositing operator.</p>
<p>See the golang blog's post on this package here: <a href="http://blog.golang.org/2011/09/go-imagedraw-package.html">The Go image/draw package</a>.</p>
<p>The primary operation I used is <code>image.Draw</code>, which has the following function signature:</p>
<p><code>func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op)</code></p>
<p>This copies a region the size of <code>r</code> from <code>src</code> into <code>dst</code> with the top left corner at <code>sp</code>.</p>
<p>Here's an example combining tying the last three together:</p>
<p><script src="https://gist.github.com/1374302.js?file=main.go"></script></p>
<h2>An aside on Go interfaces</h2>
<p>The relationship between image.Image and draw.Image is extremely representative of idiomatic Go. In Go, a type doesn't declare that it implements an interface, it just does so, and it gets checked statically at compile time.</p>
<p>A <code>draw.Image</code> is just like an <code>image.Image</code>, but you can draw into it. The interface requirements are a superset of those defined in <code>image.Image</code>. Taking a look at the source to <code>draw.Image</code> reveals the neat way that interface inheritance happens in Go:</p>
<p><script src="https://gist.github.com/1374302.js?file=Image.go"></script></p>
<h2>Wrap</h2>
<p>This implementation was enjoyable; I am really warming up to Go.</p>
<p>So far, the standard libraries are uniformly sensible and in many cases beautiful. It's clearly an opinionated language and set of packages, but so far, I seem to agree with those opinions. <img src='http://blog.carbonfive.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Cheers,<br />
Jon</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2011/11/17/explorations-in-go-solving-the-instagram-engineering-challenge/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Generating realistic-looking stories in Pivotal Tracker</title>
		<link>http://blog.carbonfive.com/2011/11/16/generating-realistic-looking-stories-in-pivotal-tracker/</link>
		<comments>http://blog.carbonfive.com/2011/11/16/generating-realistic-looking-stories-in-pivotal-tracker/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 20:02:22 +0000</pubDate>
		<dc:creator>Jon Cooper</dc:creator>
				<category><![CDATA[Everything Else]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=5494</guid>
		<description><![CDATA[We are heavy users of Pivotal Tracker here at Carbon Five, and each project evolves workflows around its use. I recently spent some time writing a Chrome extension to help support some of the common interaction patterns that come up &#8230; <a href="http://blog.carbonfive.com/2011/11/16/generating-realistic-looking-stories-in-pivotal-tracker/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We are heavy users of Pivotal Tracker here at Carbon Five, and each project evolves workflows around its use. I recently spent some time writing a Chrome extension to help support some of the common interaction patterns that come up in our workflows.</p>
<p>This blog post is not about that.</p>
<p>I started to write up a post about the Chrome extension and how I developed it (forthcoming), but realized that I needed to show screenshots. Unfortunately, I can&#8217;t use images of a client&#8217;s production tracker. Hmm.</p>
<p>I quickly whacked together a Ruby script to generate realistic-looking stories in a tracker project. Here it is!</p>
<p><span id="more-5494"></span></p>
<p>github: <a href="https://github.com/joncooper/lorem-tracker">Lorem Tracker</a></p>
<p>A populated tracker looks like this:</p>
<div class="thumbnail"><a href="https://skitch.com/jdc/gjrer/lorem-tracker-example-pivotal-tracker"><img style="max-width: 638px;" src="https://img.skitch.com/20111116-nu94cpwgbxmricy8b9q2jtaya9.medium.jpg" alt="Lorem Tracker Example - Pivotal Tracker" /></a></div>
<p>This might be a useful starting point if you need to</p>
<ul>
<li>Teach a friend, client or coworkers how to use tracker without touching production data</li>
<li>Import a bunch of stories that you wrote in a text file</li>
<li>Dump a bunch of stories for analysis in Excel</li>
</ul>
<p>I use <a href="https://github.com/jsmestad">Justin Smestad</a>&#8216;s lovely gem, <a href="https://github.com/jsmestad/pivotal-tracker">pivotal-tracker</a>. This gem provides an ActiveRecord-ish wrapper around the Pivotal Tracker API.</p>
<p>Adding a story using his gem is as easy as:</p>
<p><script type="text/javascript" src="https://gist.github.com/1371094.js?file=gistfile1.rb"></script>Also check out the pivotal-tracker gem&#8217;s <a href="https://github.com/jsmestad/pivotal-tracker/wiki/API">API docs</a> for more details on how to use it. Anyway, here&#8217;s the source, if you&#8217;re interested:<script type="text/javascript" src="https://gist.github.com/1371148.js?file=lorem-tracker.rb"></script></p>
<p>Cheers,<br />
Jon</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2011/11/16/generating-realistic-looking-stories-in-pivotal-tracker/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Modern Cucumber and Rails: No More Training Wheels</title>
		<link>http://blog.carbonfive.com/2011/11/07/modern-cucumber-and-rails-no-more-training-wheels/</link>
		<comments>http://blog.carbonfive.com/2011/11/07/modern-cucumber-and-rails-no-more-training-wheels/#comments</comments>
		<pubDate>Mon, 07 Nov 2011 17:40:51 +0000</pubDate>
		<dc:creator>Jared Carroll</dc:creator>
				<category><![CDATA[Process]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[cucumber]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://blog.carbonfive.com/?p=5397</guid>
		<description><![CDATA[Last month, cucumber-rails 1.1 was released. This release removed web_steps.rb, a collection of step definitions for interacting with a web app. For months, web_steps.rb contained a warning of its negative effects on feature maintenance. Like most developers, I ignored the &#8230; <a href="http://blog.carbonfive.com/2011/11/07/modern-cucumber-and-rails-no-more-training-wheels/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>
Last month, <a href="https://github.com/cucumber/cucumber-rails"><code>cucumber-rails</code></a> 1.1 was released. This release removed <code>web_steps.rb</code>, a collection of step definitions for interacting with a web app.
</p>
<p>
For months, <code>web_steps.rb</code> contained a warning of its negative effects on feature maintenance. Like most developers, I ignored the warning. During a recent upgrade of an existing Rails app, I realized it was now gone. Instead of copying and pasting it from an older app or using the newly created <a href="https://github.com/cucumber/cucumber-rails-training-wheels"><code>cucumber-rails-training-wheels</code></a> gem, I decided to accept the challenge and refactor its steps out of the app&#8217;s existing features.
</p>
<p>
After the refactor, the features read much better. They were simpler, less verbose, and felt more maintainable.  I also cleaned up my <code>factory_girl</code> usage, which was causing issues similar to <code>web_steps.rb</code>. Here&#8217;s a short overview of the main refactorings.
</p>
<p><span id="more-5397"></span></p>
<h2>Removing Domain Leakage</h2>
<p>
The first step in writing a scenario is establishing its context. This usually involves creating some domain objects.  For setup, I use <a href="http://rubygems.org/gems/factory_girl"><code>factory_girl</code></a>. <code>factory_girl</code> includes <a href="https://github.com/thoughtbot/factory_girl/blob/master/lib/factory_girl/step_definitions.rb">step definitions</a> for calling your app&#8217;s custom factories from scenarios.
</p>
<p>
The following scenario is from a simple CMS. The domain model consists of a single <code>Page</code> class with a <code>page_type</code> attribute. <code>factory_girl</code> factories exist for creating various types of pages e.g., a home page, a category page, a topic page, etc. A hierarchy of pages can be created by associating a page with a parent page. This scenario is for creating a subtopic page.
</p>
<p><script src="https://gist.github.com/1344259.js?file=gistfile1.feature"></script></p>
<p>
<code>factory_girl</code> generated the three &#8220;And the following &lt;factory-name&gt; exists:&#8221; steps from the app&#8217;s existing factories. Each of these steps includes a table with the names and values of attributes to be passed to the corresponding factory.
</p>
<p>
The table in both the category and topic step includes an association. For example, in the topic step <code>factory_girl</code> will set the topic&#8217;s parent association to the existing page named &#8220;Mind&#8221;, or if that page does not exist, to a new page with that name.
</p>
<p>
There are two problems with this scenario:
</p>
<ol>
<li>
    <strong>Dependent on the domain model.</strong> This scenario contains the names of classes, their attributes, and even their associations. This is brittle and could break due to domain changes as minor as renaming a database column.
  </li>
<li>
    <strong>Includes too much detail.</strong> This scenario is about creating a subtopic, the actual test data should not matter. The fact that the name of the topic is &#8220;Stress&#8221; is distracting and irrelevant. The home and category pages are also unnecessary; only a topic page should be required to create a subtopic page. Factories should handle any required associations. These nonessential elements are known as <a href="http://skillsmatter.com/podcast/home/refuctoring-your-cukes">incidental details</a>.
  </li>
</ol>
<p>
Let&#8217;s refactor to something simpler.
</p>
<p><script src="https://gist.github.com/1344260.js?file=gistfile1.feature"></script></p>
<p>
This refactored version replaces the former setup with a single step, also provided by <code>factory_girl</code>.<code>factory_girl</code> generates a &#8220;Given a &lt;factory-name&gt; exists&#8221; for each of your factories. This simpler step definition excludes the ascii table filled with implementation details, eliminating distracting test data, and making the scenario more readable overall.
</p>
<p>
Strive to use <code>factory_girl</code>&#8216;s simpler step definitions to create more maintainable scenarios. Avoid writing scenarios with the more verbose table based steps by eliminating incidental details. Don&#8217;t hesitate to create custom steps if <code>factory_girl</code>&#8216;s steps are too low level for a scenario.
</p>
<h2>Thinking Declaratively</h2>
<p>
<code>web_steps.rb</code> provides a lot of low level step definitions for performing actions on a web page, e.g., clicking a link, filling in form fields, clicking buttons, etc.
</p>
<p>
Here&#8217;s a scenario from the same simple CMS project using various action steps provided by <code>web_steps.rb</code>.
</p>
<p><script src="https://gist.github.com/1344261.js?file=gistfile1.feature"></script></p>
<p>
There are two problems with this scenario:
</p>
<ol>
<li>
    <strong>Dependent on the UI.</strong> Changes to the UI could result in corresponding changes to this feature. Scenarios written in this step-by-step style are known as <a href="http://benmabey.com/2008/05/19/imperative-vs-declarative-scenarios-in-user-stories.html">imperative scenarios</a>.
  </li>
<li>
    <strong>Contains too many incidental details.</strong>  A stakeholder doesn&#8217;t care about the test data, they just want to verify that you can create a slide.
   </li>
</ol>
<p>
Let&#8217;s refactor and fix these two issues.
</p>
<p><script src="https://gist.github.com/1344263.js?file=gistfile1.feature"></script></p>
<p>
A single custom step has eliminated our UI dependency and removed insignificant data. This scenario is much more readable and as a result, more likely to be read.
</p>
<p>
The important point is to not be lazy and lean on <code>web_steps.rb</code>. Instead, write in a declarative style by creating custom steps that focus on &#8220;what&#8221; should happen, not &#8220;how&#8221; it should happen.
</p>
<h2>Simpler Verification</h2>
<p>
<code>web_steps.rb</code> also provides several step definitions for verifying page content and form field values.
</p>
<p>
The omitted verification step of the previous &#8220;Create a slide&#8221; scenario uses these steps to verify a success message and form field values:
</p>
<p><script src="https://gist.github.com/1344264.js?file=gistfile1.feature"></script></p>
<p>
This scenario implies that after creating a slide you&#8217;re shown a success message and redirected to the new slide&#8217;s edit page. Again, this creates a dependency on the UI and distracts with its &#8220;interesting data&#8221;.
</p>
<p>
Let&#8217;s refactor by first moving the success message verification into the &#8220;And I create a slide&#8221; step. Then we can introduce a new higher-level step to summarize the redirection and expected form field values.
</p>
<p><script src="https://gist.github.com/1344266.js?file=gistfile1.feature"></script></p>
<h2>Make the Effort</h2>
<p>
The removal of <code>web_steps.rb</code> was a controversial move but also a good one. Like most developers, I ignored the warnings in <code>web_steps.rb</code> and my scenarios suffered from unexpected failures and UI dependencies.  By eliminating <code>web_steps.rb</code>, you&#8217;re forced to think declaratively and write your features at a much-higher level. Take the same approach during setup when using <code>factory_girl</code>. I abused <code>factory_girl</code>&#8216;s step definitions and my features soon became lost in ascii tables.
</p>
<p>
You will have to write more code, but the improved readability and maintenance make it worth the effort.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.carbonfive.com/2011/11/07/modern-cucumber-and-rails-no-more-training-wheels/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>

