<?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>Pivotal Labs &#187; Robbie Clutton</title>
	<atom:link href="http://pivotallabs.com/author/rclutton/feed/" rel="self" type="application/rss+xml" />
	<link>http://pivotallabs.com</link>
	<description>Agility Developed</description>
	<lastBuildDate>Tue, 18 Jun 2013 03:38:22 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>To build a bookmarklet</title>
		<link>http://pivotallabs.com/to-build-a-bookmarklet/</link>
		<comments>http://pivotallabs.com/to-build-a-bookmarklet/#comments</comments>
		<pubDate>Mon, 17 Jun 2013 12:32:25 +0000</pubDate>
		<dc:creator>Robbie Clutton</dc:creator>
				<category><![CDATA[Labs]]></category>
		<category><![CDATA[bookmark]]></category>
		<category><![CDATA[bookmarklet]]></category>
		<category><![CDATA[iframe]]></category>
		<category><![CDATA[ironblogger]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://pivotallabs.com/?p=20340</guid>
		<description><![CDATA[<p>Building a bookmarklet provides an interesting challenge. It involves interaction a website your application does not control where that site could be anything with any number of dependencies on CSS or Javascript libraries. The first choice to make is trying to work with that website and probably setting an !important on every CSS selector used and hope that there&#8217;s no namespace or versioning clashes with any Javascript included; or use an iframe. Iframes seem to have fallen out of favour in recent times but the sandboxed nature of the content inside an iframe mean the worries of CSS and Javascript clashes are gone. However this is replaced with a communications overhead of communicating between the host document and the iframe. I wanted to touch on some of the things our team did on a recent project to try and make this fairly seamless. Getting into the DOM A bookmarklet is&#8230;</p><p>The post <a href="http://pivotallabs.com/to-build-a-bookmarklet/">To build a bookmarklet</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Building a bookmarklet provides an interesting challenge. It involves interaction a website your application does not control where that site could be anything with any number of dependencies on CSS or Javascript libraries. The first choice to make is trying to work with that website and probably setting an <code>!important</code> on every CSS selector used and hope that there&#8217;s no namespace or versioning clashes with any Javascript included; or use an iframe.</p>
<p>Iframes seem to have fallen out of favour in recent times but the sandboxed nature of the content inside an iframe mean the worries of CSS and Javascript clashes are gone. However this is replaced with a communications overhead of communicating between the host document and the iframe. I wanted to touch on some of the things our team did on a recent project to try and make this fairly seamless.</p>
<h2>Getting into the DOM</h2>
<p>A bookmarklet is a small piece of Javascript that a user can drag onto the bookmark bar and upon pressing the link the Javascript will run. Because there is no guarentee what site will be loaded and if that will have any number of Javascript libraries included it&#8217;s best to use plain old Javascript to create an iframe element and append it to the body of the document. Our bookmarklet also needed to have some javascript if for nothing else but to be able to dismiss and remove the newly created elements. This can be done through the creation of a script element and appending to the body just like the iframe itself.</p>
<p>Once the iframe and script tags are appended they are treated the same as any other element. The content is loaded and the script is executed. The next step is getting the window to talk to the iframe.  As a convienence the domain with protocol and port of the iframe is stored in a variable for later use.</p>
<pre><code>element = document.createElement('iframe');
element.id = 'example_iframe';
element.src = 'example.com?referrer=' + window.location;
document.body.appendChild(element);

script = document.createElement('script');
script.src = 'example.com/bookmark.js';
document.body.appendChild(script);
</code></pre>
<p>The location is also sent to the remote server to load the iframe so that it can also store that location for passing messages to the host.</p>
<p>At this point this Javascript could also append a script tag to a version of libraries that may be required for it&#8217;s own application to run. It could also test for the existance of that library before hand so it doesn&#8217;t bring down an incompatible version. For example, bringing in jquery:</p>
<pre><code>if ($ === undefined) {
    var jq = document.createElement('script');
    jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js";
    document.body.appendChild(jq);
}
</code></pre>
<h2>Sending a message</h2>
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage">postmessage</a> method is available to communicate bewtween the window and the iframe.  The host window with a reference to the iframe can call <code>postmessage</code> with a string as a message and as a security measure the target location. We had stored this during the loading of the elements as described above.</p>
<pre><code>iframe.postmessage('hello', 'www.example.com');
</code></pre>
<p>That message won&#8217;t get anywhere unless the iframe is listening for the <code>message</code> event on the other end.</p>
<pre><code>// native Javascript
window.addEventListener('message', function(event){ … });

// jQuery
$(window).on('message', function(event){ … });
</code></pre>
<p>I&#8217;ve used the native Javascript above but really, once in the iframe itself the application has full control and could use JQuery or any other library at this point. Our application needs to listen to messages on both sides though so we needed the above to run in the host anyway.</p>
<h2>RPC</h2>
<p>Sending a message is all well and good but any non-trival application is going to have more than one function to run. We took influence from <a href="http://en.wikipedia.org/wiki/Remote_procedure_call">Remote Procedure Calls (RPC)</a> to call functions within the host and remote sites. The message sent was stringified JSON with a very light &#8216;schema&#8217; of the function to run and parameters to send to the function.</p>
<pre><code>{   
    f: 'theFunction',
    params: {
        ...
    }
}
</code></pre>
<p>The recipient could then parse the string it knew to be JSON, extract the function to call and call it with any optional parameters also sent. This does create a binding between the host and the iframe but as the appliction controlled both sides we deemed it an acceptable risk.  The function can be run from the <code>window</code> like so:</p>
<pre><code>window['theFunction']();

// or from the event listener
var fn = JSON.parse(event.data).['f'];
window[fn]();
</code></pre>
<h2>Dealing with namespaces</h2>
<p>It was mentioned earlier that one of the goals of using an iframe was not to clobber any Javascript namespaces but we did end up including Javascript in the host and to avoid this we used an application namespace. However calling that as a property on the <code>window</code> would no longer work.</p>
<pre><code>// doesn't work
window['my.app.function'](); 

// works
window['my']['app']['function']();
</code></pre>
<p>We looked to <a href="https://github.com/elementaljs">ElementalJS</a> as an example of dealing with namespaced functions to parse the function.</p>
<pre><code>window.addEventListener('message', function(){
    var fn = window; 
    var data = JSON.parse(event.data);
    var namespaced = data['f'].split('.');
    for (var i in namespaced) { 
        fn = fn[namespaced[i]];
    }
    fn(data.params);    
});
</code></pre>
<p>This is natually fairly crude, some defensive code could be added but this demonstrates the intent of the processing. Defense like making sure that function existed, or that &#8216;f&#8217; existed in the data for the window could receive a message from another iframe.</p>
<h2>Putting it all together</h2>
<p>The bookmarket inserts two elements, an iframe and a script. The iframe has the source <code>example.com?referer=bar.com</code>. <code>bar.com</code> is inserted as a variable in the iframe Javascript code.  The iframe inserted has an id of <code>example_iframe</code></p>
<p>The host Javascript listens to the <code>message</code> event</p>
<pre><code>window.addEventListener('message', function(event){
    var fn = window; 
    var data = JSON.parse(event.data);
    var namespaced = (data['f'] || "").split('.');
    for (var i in namespaced) { 
        fn = fn[namespaced[i]];
    }
    if (typoe(fn) === 'function') {
        fn(data.params);    
    }
});
</code></pre>
<p>The host also sets up a namespace and a function to be called.</p>
<pre><code>window.example = window.example || {};

example.hello = function(){ … }   
</code></pre>
<p>When the iframe has loaded, it sends a ready message to the host</p>
<pre><code>$(document).ready(function(){
    var data = JSON.strinify({f: 'example.hello'});
    parent.postMessage(data, referer); // referer set by server from the request param for the iframe
});
</code></pre>
<p>The host from the script loaded in the bookmarket has the <code>example.hello</code> function and it&#8217;s run. This in turn replies to the iframe.</p>
<pre><code>var example.hello = function(){
    var iframe = document.getElementById('example_iframe');
    var data = JSON.stringify({f: 'example.world'})
    iframe.contentWindow.postMessage(data, 'example.com');
};
</code></pre>
<p>The iframe has an event listener which is the same code as the host, and runs the function <code>example.world</code></p>
<pre><code>var example.world = function(){
    // hello, world
};
</code></pre>
<h2>Wrapping up</h2>
<p>This has shown some of the techniques for a &#8216;hello, world&#8217; bookmark with two way communication between host and iframe that uses Javascript namespaces. This was enough to get our application off the ground as the two way communication acted as a solid base to build upon.</p>
<p>The post <a href="http://pivotallabs.com/to-build-a-bookmarklet/">To build a bookmarklet</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://pivotallabs.com/to-build-a-bookmarklet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>API Versioning</title>
		<link>http://pivotallabs.com/api-versioning/</link>
		<comments>http://pivotallabs.com/api-versioning/#comments</comments>
		<pubDate>Fri, 31 May 2013 23:56:05 +0000</pubDate>
		<dc:creator>Robbie Clutton</dc:creator>
				<category><![CDATA[Labs]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[ironblogger]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[versioning]]></category>

		<guid isPermaLink="false">http://pivotallabs.com/?p=19725</guid>
		<description><![CDATA[<p>How to version an API has been a thoroughly discussed topic in the last several years regardless of protocol or approach, be that SOAP, REST or Hypermedia. Why contribute another post to the topic? My last post on avoiding breaking changes through better design led to conversations in the office and online about versioning. @moonmaster9000 @robb1e @jaderubick you should version using a vendor string in the Accept header. &#8212; David Celis (@davidcelis) May 16, 2013 I wanted to dig a little deeper into versioning and look at some of the different ways people are using versioning for their resources on the web. Compatibility as version control Mark Nottingham has written a lot of the subject of API versioning and it&#8217;s difficult to disagree with the high level arguments outlined in his API evolution post. keep compatible changes out of names avoid new major versions makes changes backwards-compatible think about forwards-compatibility&#8230;</p><p>The post <a href="http://pivotallabs.com/api-versioning/">API Versioning</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>How to version an API has been a thoroughly discussed topic in the last several years regardless of protocol or approach, be that SOAP, REST or Hypermedia. Why contribute another post to the topic? My <a href="http://pivotallabs.com/stop-leaky-apis">last post on avoiding breaking changes through better design</a> led to conversations in the office and online about versioning.</p>
<blockquote class="twitter-tweet"><p>@<a href="https://twitter.com/moonmaster9000">moonmaster9000</a> @<a href="https://twitter.com/robb1e">robb1e</a> @<a href="https://twitter.com/jaderubick">jaderubick</a> you should version using a vendor string in the Accept header.</p>
<p>&mdash; David Celis (@davidcelis) <a href="https://twitter.com/davidcelis/status/335040861995933696">May 16, 2013</a></p></blockquote>
<p><script async src="//platform.twitter.com/widgets.js?48a6bc" charset="utf-8"></script></p>
<p>I wanted to dig a little deeper into versioning and look at some of the different ways people are using versioning for their resources on the web.</p>
<h2>Compatibility as version control</h2>
<p><a href="http://en.wikipedia.org/wiki/Mark_Nottingham">Mark Nottingham</a> has written a lot of the subject of API versioning and it&#8217;s difficult to disagree with the high level arguments outlined in his <a href="http://www.mnot.net/blog/2012/12/04/api-evolution">API evolution post</a>.</p>
<ul>
<li>keep compatible changes out of names</li>
<li>avoid new major versions</li>
<li>makes changes backwards-compatible</li>
<li>think about forwards-compatibility</li>
</ul>
<p>In another post Nottingham adds that we <a href="http://www.mnot.net/blog/2012/07/11/header_versioning">shouldn&#8217;t use a custom header for versioning</a> and touches on versioning through the Accept header but there is a fundamental thread here: try as hard as possible to not introduce breaking changes so that versioning isn&#8217;t a big issue.</p>
<p>One of the issues to content with when considering versioning is often building APIs requires more thought up front that an agile developer might be used to. URIs, Data structure, meta-data and extensibility are important and would be best considered up front. Once those decisions have been made changes to the structure often result in breaking older versions of the API. Anyone at an early stage of building an API would do well to put some thought into the API design and setting some rules for future consistency.</p>
<h2>Accept header</h2>
<p>The Twitter comment above pointed me towards using the Accept header as part of content negotiation and I found a number of blog posts covering the subject as well as some companies using this approach.</p>
<p><a href="http://tools.ietf.org/html/rfc4288#section-3.2">RFC4288 section 3.2</a> outlines how a vendor, i.e. an application, can make use of customisable MIME types in the Accept header. <a href="http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http#i_want_my_api_to_be_versioned">Steve Klabnik</a> shows how an application can make use of this to include a version number as part of the Accept header used for content negotiation.</p>
<p>Looking at some concrete examples through the <a href="http://developer.github.com/v3/media/">well documented Github API</a> shows how the Accept header can be used with their services:</p>
<p><code>Accept: application/vnd.github[.version].param[+json]</code></p>
<p><code>curl -v -H 'Accept:application/vnd.example.v1+json' localhost:3000</code></p>
<p>The <code>vnd</code> part is the vendor definition as outlined in <a href="http://tools.ietf.org/html/rfc4288#section-3.2">RFC4288</a>. Let&#8217;s take a look at a number of options to make use of this header.</p>
<h3>Parsing the Accept header</h3>
<p>Within an application, headers can be inspected from a HTTP request. Extracting the version number would require some regular expression matching, something along the lines of the following in an <code>application_controller</code> perhaps:</p>
<pre><code>def api_version
request.headers["Accept"][/^application\/vnd\.github\.v(\d)/, 1].to_i
end
</code></pre>
<p>Once the application has this version number it can decide how to behave for the response.</p>
<h3>Registering the MIME type</h3>
<p>An application could alternatively register a <a href="https://en.wikipedia.org/wiki/Internet_media_type">MIME type</a> for each and use the <code>respond_to</code> blocks to decide how to render a response.</p>
<p>To register a MIME type in <code>config/initializers/mime_types.rb</code></p>
<pre><code>Mime::Type.register "application/vnd.github.com.v1+json", :json_v1
Mime::Type.register "application/vnd.github.com.v2+json", :json_v2
</code></pre>
<p>MIME types also allows parameters but would require registration for each one also:</p>
<pre><code>Mime::Type.register "application/vnd.github.com+json; version=1", :json_v1
Mime::Type.register "application/vnd.github.com+json; version=2", :json_v2
</code></pre>
<p>So a controller could look something like the following and deal with the request  appropriately.</p>
<pre><code>posts = Api::Posts.all

respond_to do |format|
    format.json_v1 { posts.v1.as_json }
    format.json_v1 { posts.v2.as_json }
end
</code></pre>
<h2>Version via a request parameter</h2>
<p>The thing with the version in an Accept header is the URI is difficult to share. If I wanted to share the URI with version information with a college I would have to send instructions on what <code>curl</code> arguments to send to the server to get the right response. It&#8217;s can be as frustrating as trying to share a holiday on a website that renders pages based on what&#8217;s in the session for the individual.  I would want to share a URI that someone can paste into a web browser address bar and see an appropriate response. Let&#8217;s compare the two approaches:</p>
<p><code>curl -v -H 'Accept:application/vnd.example.v1+json' localhost:3000</code></p>
<p>vs</p>
<p><code>curl -v localhost:3000/?version=v1</code></p>
<p>or</p>
<p><code>curl -v localhost:3000/?version=20130603</code></p>
<h2>Version number as a date</h2>
<p>The <a href="https://developer.foursquare.com">Foursquare API</a> allows clients to send a version as a date in the format <code>yyyymmdd</code> which conveniently is an always increasing number. When a client starts to use the API they can use that days date and the response will always be in that format. I like this concept as it removes the burden of having to know what endpoint to use or what version to send in a header. The client uses a known point in time and the response will always match if that is sent. If nothing is sent then the latest version of the resource is returned.</p>
<p>With this in mind, I wrote a very small <a href="http://rubygems.org/gems/simple-versioner">gem</a> to put this into practice to demonstrate how I thought this could be achieved which boils down to the following. Given a number (i.e. the version sent in the request) and a list of numbers (i.e. known versions with some change in an application), find the previous closest number in the list from the version number given. For example, if the date <code>20130101</code> is passed and the list contains two dates of <code>20130101</code> and <code>20130601</code>, then <code>20130101</code> is returned.</p>
<pre><code>def find_version_for version, list
    return list.last if version.nil?
    list.select { |i| i <= version }.last || list.first
end
</code></pre>
<p>Using the returned number, the server can decide how to render the response to the client as defined in my previous post.</p>
<h2>Robustness principle</h2>
<p><a href="http://en.wikipedia.org/wiki/Jon_Postel">Jon Postel</a> says "<a href="http://en.wikipedia.org/wiki/Robustness_principle">Be conservative in what you do, be liberal in what you accept from others</a>", so perhaps we could allow our clients to do both?</p>
<p>Perhaps using the Accept header makes you a better denizen of the Internet, adhering to <a href="http://en.wikipedia.org/wiki/HATEOAS">HATEAOS</a> principles but I think using a version request parameter makes for a better Web experience. As a developer, I want to be able to put a URI into a browser and see a response rendered and for that I'd lean more towards the version parameter.</p>
<p>This approach can be generalised across other information sent from a client to a server. Clients like web browsers send information in every request, and these should honored as the defaults. The information sent includes what language, data and encoding formats the client would like. Using request parameters can offer overrides and support compatibility between different types of clients who want to use an API and <a href="http://www.w3.org/Provider/Style/URI.html">cool</a> <a href="http://www.w3.org/Provider/Style/Bookmarkable.html">bookmarkable</a> URIs.</p>
<p>The post <a href="http://pivotallabs.com/api-versioning/">API Versioning</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://pivotallabs.com/api-versioning/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Stop leaky APIs</title>
		<link>http://pivotallabs.com/stop-leaky-apis/</link>
		<comments>http://pivotallabs.com/stop-leaky-apis/#comments</comments>
		<pubDate>Thu, 16 May 2013 01:30:25 +0000</pubDate>
		<dc:creator>Robbie Clutton</dc:creator>
				<category><![CDATA[Labs]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[ironblogger]]></category>
		<category><![CDATA[object-design]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://pivotallabs.com/?p=19228</guid>
		<description><![CDATA[<p>There are many blogs about how to expose an API for a Rails application and many times I look at this and am concerned about how these examples often leak the application design and the schema out through the API. When this leak occurs a change to the application internals can ripple out and break clients of an API, or force applications to namespace URI paths which I feel is unnecessary and ugly. When the only consumer of application data models are the views within the same application then the object design can be fluid and malleable. Once an application exposes an API to more than one client, and especially if that client is on a different release cycle to the server, such as iPhone application, data models become rigid. Rails tends discouraged N-tier architecture to the benefit of development speed but APIs are contracts between a server and it&#8217;s&#8230;</p><p>The post <a href="http://pivotallabs.com/stop-leaky-apis/">Stop leaky APIs</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>There are many blogs about how to expose an API for a Rails application and many times I look at this and am concerned about how these examples often leak the application design and the schema out through the API. When this leak occurs a change to the application internals can ripple out and break clients of an API, or force applications to namespace URI paths which I feel is unnecessary and ugly.</p>
<p>When the only consumer of application data models are the views within the same application then the object design can be fluid and malleable. Once an application exposes an API to more than one client, and especially if that client is on a different release cycle to the server, such as iPhone application, data models become rigid. Rails tends discouraged N-tier architecture to the benefit of development speed but APIs are contracts between a server and it&#8217;s client and can be difficult to change once they start being used.</p>
<p>Passing an object into the Rails JSON serialisation methods will work for a time, but relying on this will only get you so far. At some point a refactor will take place that will cause a breaking change. It could be something simple such as renaming a column, moving responsibilities from one class to another or adding extra meta-data to a response. Either way, adding this information into your model class starts to place more responsibilities into one place.</p>
<p>There are a few ways out of this potential issue. Let&#8217;s take a look at the classic blog application and its <code>Post</code> object. The Rails rendering engine will call <code>as_json</code> on an object if the request has sent the <code>content-type</code> of <code>application\json</code> to the server.  Here we override the implementation from <code>ActiveRecord</code> to provide a stable, known version:</p>
<pre><code>def as_json(options={})
    {
        author_id: author.id
        title: title
    }
end
</code></pre>
<p>A second option is to model the object explicitly and serialise the internal model into a public representation. We can duck-type the object to respond how <code>ActiveRecord</code> objects behave during a serialisation call. Although this can be seen as a step towards a N-tier architecture, it&#8217;s also a step towards service dependent abstraction:</p>
<pre><code>class Api::Post
  attr_reader :post

  def initialize(post)
    @post = post
  end

  def as_json(options={})
    {
      author_id: post.author.id
      title: post.title
    }
  end
end
</code></pre>
<p>The benefit of doing this is a separation of concerns between your data model and the data presentation. An application model doesn&#8217;t need to know how it&#8217;ll be represented by an API, command line interface or any other outside communication mechanism. If an application were tending more towards <a href="http://en.wikipedia.org/wiki/HATEOAS">HATEOAS</a> for instance this separation could help resolve hyperlinks relevant to the interface. You may lose some of the Rails <code>respond_with</code> goodness with this:</p>
<pre><code>respond_to :html, :json

def show
  post = Post.find(params[:id])
  respond_to |format| do
    format.html { @post = post }
    format.json { render json: Api::Post.new(post) }
  end
end
</code></pre>
<p>That can be regained with the help of a presenter:</p>
<pre><code>respond_to :html, :json

def show
  post = Post.find(params[:id])
  @presenter = PostPresenter.new(post)
  respond_with @presenter
end
</code></pre>
<p>Where <code>PostPresenter</code> may look something like:</p>
<pre><code>class PostPresenter &lt; SimpleDelegator
  def as_json(options={})
    Api::Post.new(self).as_json(options)
  end
end
</code></pre>
<p>What&#8217;s the difference between this and putting the <code>as_json</code> method into <code>Post</code> directly? More control, separation of concerns with application modeling vs presentation and the big win is when breaking changes occur within the API. Now we can put version relevant information into new objects, or into the serialised class itself.</p>
<pre><code>class Api::Post
  attr_reader :post, :version

  def initialize(post, version)
    @post = post
    @version = version
  end

  def as_json(options={})
    send("v#{:version}")
  end

  private
  def v20130505
    # version specific JSON
  end

  def v20121206
    # version specific JSON
  end
end
</code></pre>
<p>Through this we have versioning information in one place and through a request parameter of something like <code>v=20130506</code> the application can handle multiple versions in one object. For me, this ultimately removes URIs like <code>/v1/posts</code>, but why is that important? The URI is an identifier which points to a resource and having <code>v1</code> or <code>v2</code> in the URI muddies the fact that the two identifiers are pointing to the same resource. Using a request parameter, much like pagination is handled, means we can ask for a representation of that resource rather than having to specify different resources. Then we can do away with needing controllers such as <code>Api::V1::PostsController</code> and just deal with <code>Api::PostsController</code> or even just <code>PostsController</code> and deal with the versioning within the object instead of the URI path.</p>
<p>The post <a href="http://pivotallabs.com/stop-leaky-apis/">Stop leaky APIs</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://pivotallabs.com/stop-leaky-apis/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>ElementalJS and SimpleBDD open source updates</title>
		<link>http://pivotallabs.com/elementaljs-simplebdd-open-source-updates/</link>
		<comments>http://pivotallabs.com/elementaljs-simplebdd-open-source-updates/#comments</comments>
		<pubDate>Tue, 14 May 2013 23:11:47 +0000</pubDate>
		<dc:creator>Robbie Clutton</dc:creator>
				<category><![CDATA[Labs]]></category>
		<category><![CDATA[elementaljs]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[simplebdd]]></category>

		<guid isPermaLink="false">http://pivotallabs.com/?p=19215</guid>
		<description><![CDATA[<p>Thanks to the benefits of Open Source software and working with great people, I&#8217;m pleased to announce some updates to both ElementalJS and to SimpleBDD. ElementalJS Thanks to Ian Zabel who made a performance improvement to ElementalJS after fighting a large DOM in Internet Explorer. Elemental will now load the behaviours much quicker if the document is passed as no filtering will take place. If another node is passed, filtering will be applied but the thought is that DOM will be much smaller so hopefully won&#8217;t hit this issue. SimpleBDD Thanks to Adam Berlin who made two improvements to SimpleBDD. First was the addition to also to the syntax and second was NoMethodError is replaced by pending if using RSpec. More improvements were made by Daniel Finnie which allow use of some non alphanumeric characters that get turned into method names.</p><p>The post <a href="http://pivotallabs.com/elementaljs-simplebdd-open-source-updates/">ElementalJS and SimpleBDD open source updates</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Thanks to the benefits of Open Source software and working with great people, I&#8217;m pleased to announce some updates to both <a href="https://github.com/elementaljs/elementaljs" title="ElementalJS" target="_blank">ElementalJS</a> and to <a href="https://github.com/robb1e/simple_bdd" title="SimpleBDD" target="_blank">SimpleBDD</a>.</p>
<h2>ElementalJS</h2>
<p>Thanks to <a href="http://pivotallabs.com/author/izabel/" title="Ian Zabel" target="_blank">Ian Zabel</a> who made a <a href="https://github.com/elementaljs/elementaljs/commit/da1f8d682611677a5dd0778a8f209b43c63c75a0" target="_blank">performance improvement to ElementalJS</a> after fighting a large DOM in Internet Explorer. Elemental will now load the behaviours much quicker if the <code>document</code> is passed as no filtering will take place. If another node is passed, filtering will be applied but the thought is that DOM will be much smaller so hopefully won&#8217;t hit this issue.</p>
<h2>SimpleBDD</h2>
<p>Thanks to <a href="http://pivotallabs.com/author/aberlin/" title="Adam Berlin" target="_blank">Adam Berlin</a> who made two improvements to SimpleBDD. <a href="https://github.com/robb1e/simple_bdd/commit/d1a61a422a398613f507a6b6c09051fdc0982b35" title="Commit" target="_blank">First was the addition</a> to <code>also</code> to the syntax and second was <code>NoMethodError</code> is replaced by <a href="https://github.com/robb1e/simple_bdd/commit/fc615e8635ac6262d6d57302028333c3a9686427" title="Commit" target="_blank">pending if using RSpec</a>.</p>
<p>More improvements were made by <a href="https://github.com/danfinnie" title="Daniel Finnie" target="_blank">Daniel Finnie</a> which allow use of <a href="https://github.com/robb1e/simple_bdd/commit/1163b7aeed1e4eb756fb6d135ef1eb4428ac5be1" title="commit" target="_blank">some non alphanumeric characters</a> that get turned into method names.</p>
<p>The post <a href="http://pivotallabs.com/elementaljs-simplebdd-open-source-updates/">ElementalJS and SimpleBDD open source updates</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://pivotallabs.com/elementaljs-simplebdd-open-source-updates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stop leaking ActiveRecord throughout your application</title>
		<link>http://pivotallabs.com/stop-leaking-activerecord/</link>
		<comments>http://pivotallabs.com/stop-leaking-activerecord/#comments</comments>
		<pubDate>Tue, 07 May 2013 01:11:13 +0000</pubDate>
		<dc:creator>Robbie Clutton</dc:creator>
				<category><![CDATA[Labs]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[ironblogger]]></category>
		<category><![CDATA[object-design]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://pivotallabs.com/?p=18901</guid>
		<description><![CDATA[<p>Extending ActiveRecord::Base leaks a powerful API throughout an application which can lead to tempting code which breaks good design. Take the classic blog example where you may want to retrieve the latest posts by a given author. You may have seen, or even written code that gets the dataset you need straight into the controller or view: Post.where(author_id: author_id).limit(20).order("created_at DESC").each { ... } For me this is a design violation as well as breaking the &#8220;Law of Demeter&#8221;[Edit: Current Pivot Adam Berlin and former Pivot John Barker pointed out that chaining with the same object was not a Demeter violation]. The example above tells me structure of the schema that the calling class has no business knowing. It also makes testing using stubs ugly and encourages testing against the database directly. A test would have to chain three methods to stub a return value. It&#8217;s brittle, as in it&#8217;s susceptible&#8230;</p><p>The post <a href="http://pivotallabs.com/stop-leaking-activerecord/">Stop leaking ActiveRecord throughout your application</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Extending <code>ActiveRecord::Base</code> leaks a powerful API throughout an application which can lead to tempting code which breaks good design. Take the classic blog example where you may want to retrieve the latest posts by a given author.  You may have seen, or even written code that gets the dataset you need straight into the controller or view:</p>
<pre><code>Post.where(author_id: author_id).limit(20).order("created_at DESC").each { ... }
</code></pre>
<p>For me this is a design violation <del datetime="2013-05-11T20:20:05+00:00">as well as breaking the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter" title="Law of Demeter" target="_blank">&#8220;Law of Demeter&#8221;</a></del><em>[Edit: Current Pivot <a href="http://pivotallabs.com/author/aberlin" target="_blank">Adam Berlin</a> and former Pivot <a href="https://twitter.com/excepttheweasel/status/331733299523358720" target="_blank">John Barker</a> pointed out that chaining with the same object was not a Demeter violation]</em>. The example above tells me structure of the schema that the calling class has no business knowing. It also makes testing using stubs ugly and encourages testing against the database directly. A test would have to chain three methods to stub a return value. It&#8217;s brittle, as in it&#8217;s susceptible to breaking due to changes outside of the class.  For me it also fails from a narrative perspective in that it doesn&#8217;t succinctly reveal the intent of this part of the application.</p>
<p>If we were testing this and attempting to use stubs, we&#8217;d have to write something like the below.  You can see how this is at best cumbersome, but also fragile.</p>
<pre><code>where = stub(:where)
limit = stub(:limit)
order = stub(:order)

Post.stub(:where).with(author_id: author_id) { where }
where.stub(:limit).with(20) { limit }
limit.stub(:order).with("created_at DESC").and_yield(post1, post2, post3)
</code></pre>
<p>You may be forgiven for thinking you could chain the stubs like below, but the arguments are ignored<del datetime="2013-05-11T20:20:05+00:00"> and this just serves to highlight the breaking of the &#8216;Law of Demeter&#8217;.</del></p>
<pre><code>Post.stub_chain(:where, :limit, :order).and_yield(post1, post2, post3)
</code></pre>
<p>I&#8217;d much rather see that as a message to the <code>Post</code> class.</p>
<pre><code>def self.latest_for_author id
  where(author_id: id).limit(20).order("created_at DESC")
end

Post.latest_for_author(1)
</code></pre>
<p>If there were variations of the limit and perhaps offset, they can be passed as option parameters of as an options hash:</p>
<pre><code>def self.latest_for_author id, limit = 20, offset = 0
  where(author: id).limit(limit).offset(offset).order("created_at DESC")
end

Post.latest_for_author(1)
Post.latest_for_author(1, 20, 0)
</code></pre>
<p>or</p>
<pre><code>def self.latest_for_author id, options
  limit = options[:limit] || 20
  offset = options[:offset] || 0
  where(author: id).limit(limit).offset(offset).order("created_at DESC")
end

Post.latest_for_author(1, offset: 20)
</code></pre>
<p>In order to get the dataset the call looks like the following, and I think is more informative than using the ActiveRecord DSL directly.</p>
<pre><code>Post.latest_for_author(author_id).each { ... }
</code></pre>
<p>Testing is also easier, as it puts more emphasis on the messages being sent to objects rather than a chain of calls having to be correct.</p>
<pre><code>Post.should_receive(:latest_for_author).with(1).and_yield(post1, post2, post3)
</code></pre>
<p>There are a few advantages to this refactor:</p>
<ul>
<li>Only the <code>Post</code> class knows about the schema</li>
<li>Any changes to the implementation of what <code>latest_for_author</code> are encapsulated in one place</li>
<li>The method describes the intent more than the implementation</li>
<li>Stubbing in the tests are easier as there is one clear dependency</li>
<li>Testing the database is encouraged only in the class hitting the database</li>
</ul>
<p>One further refactor could be done here, and that is to move the query logic out of the Post class once more, but this time into a purpose built query Object:</p>
<pre><code>class LatestPosts
  attr_reader :author_id

  def initialize author_id
    @author_id = author_id
  end

  def find_each(&amp;block)
    Post.where(author_id: author_id).limit(20).order("created_at DESC").find_each(&amp;block)
  end

end
</code></pre>
<p>Where using the class looks like:</p>
<pre><code>LatestPosts.new(author_id).find_each { ... }
</code></pre>
<p>Here&#8217;s what <a href="http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/">Bryan Helmkamp has to say on query objects</a> in his excellent write up on fat ActiveRecord models. Bryan here rightfully points out that once in a single purpose object, they warrant little attention to unit testing. Now is the right time to use the database to ensure the right data set is being returned and that N+1 queries are not being performed. This means that database testing would only occur within the class actually hitting the database and not the rest of application which has a dependency on the database.</p>
<p>All of these techniques discussed serve to improve the design of an application by preventing leaking responsibilities from one class throughout the rest of the application. I&#8217;m also not saying that developers shouldn&#8217;t be using ActiveRecord or even Rails, but to use the tools responsibly.</p>
<p>The post <a href="http://pivotallabs.com/stop-leaking-activerecord/">Stop leaking ActiveRecord throughout your application</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://pivotallabs.com/stop-leaking-activerecord/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Single resource REST Rails routes</title>
		<link>http://pivotallabs.com/single-resource-rest-rails-routes/</link>
		<comments>http://pivotallabs.com/single-resource-rest-rails-routes/#comments</comments>
		<pubDate>Tue, 16 Apr 2013 20:19:11 +0000</pubDate>
		<dc:creator>Robbie Clutton</dc:creator>
				<category><![CDATA[Labs]]></category>
		<category><![CDATA[ironblogger]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[routing]]></category>

		<guid isPermaLink="false">http://pivotallabs.com/?p=18250</guid>
		<description><![CDATA[<p>REST principles by default is a fantastic convention within Rails applications. The documentation for how to route HTTP requests are comprehensive and give examples about photo resources within an application. If you&#8217;ve got photo and tag as first class resources of your application, Rails has you covered. But what if you are building an application with a focus on one type of resource, do you really want /resource_type as a prefix to all of your application paths? I certainly don&#8217;t and I&#8217;ll show you how to remove that without diverging from Rails core strenghts. For better or worse, I&#8217;m always conscience of making sure applications I&#8217;m involved in have Cool URIs and sometimes that does mean fighting the Rails conventions. However Rails routing is very flexible and can provide me with the application paths that make me happy. Take Twitter as an example. Every user has their username as a&#8230;</p><p>The post <a href="http://pivotallabs.com/single-resource-rest-rails-routes/">Single resource REST Rails routes</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>REST principles by default is a fantastic convention within Rails applications. The <a href="http://guides.rubyonrails.org/routing.html">documentation</a> for how to route HTTP requests are comprehensive and give examples about <code>photo</code> resources within an application. If you&#8217;ve got <code>photo</code> and <code>tag</code> as first class resources of your application, Rails has you covered. But what if you are building an application with a focus on one type of resource, do you really want <code>/resource_type</code> as a prefix to all of your application paths? I certainly don&#8217;t and I&#8217;ll show you how to remove that without diverging from Rails core strenghts.</p>
<p>For better or worse, I&#8217;m always conscience of making sure applications I&#8217;m involved in have <a href="http://www.w3.org/Provider/Style/URI.html">Cool URIs</a> and sometimes that does mean fighting the Rails conventions. However Rails routing is very flexible and can provide me with the application paths that make me happy.</p>
<p>Take Twitter as an example. Every user has their username as a top level path, so instead of having <code>/users/robb1e</code>, they simply have <code>/robb1e</code>. When dealing with an application where there is one core resource it can make a lot of sense to strip the resource prefix. This can be achieved through <code>scopes</code> in the routing configuration.</p>
<pre><code>Your::Application.routes.draw do
  scope ":username" do
    get '', to: 'users#show'
  end
end
</code></pre>
<p>Gives you routes which look like</p>
<pre><code>           GET  /:username(.:format)                users#show
</code></pre>
<p>If you wanted to see the followers and followees of that user, you have two options. Return to the default <code>resource</code> or use HTTP verb contraints. I&#8217;ll show you both.</p>
<pre><code>Your::Application.routes.draw do
  scope ":username" do
    get '', to: 'users#show'
    resource :following, only: [:show]
    resource :followers, only: [:show]
  end
end
</code></pre>
<p>This adds the routes</p>
<pre><code>following GET  /:username/following(.:format)      followings#show
followers GET  /:username/followers(.:format)      followers#show
</code></pre>
<p>Alternatively <a href="http://guides.rubyonrails.org/routing.html#http-verb-constraints">HTTP verb constrains</a> can be used to achieve a similar result.</p>
<pre><code>Your::Application.routes.draw do
  scope ":username" do
    get '', to: 'users#show'
    get '/following', to: 'user#following'
    get '/followers', to: 'user#followers'
  end
end
</code></pre>
<p>This gives the paths</p>
<pre><code>          GET  /:username/following(.:format)      user#following
          GET  /:username/followers(.:format)      user#followers
</code></pre>
<p>If you are trending into paths unknown, you always have the safety of tests to help you out. Both <a href="http://guides.rubyonrails.org/routing.html#testing-routes">Rails</a> and <a href="https://github.com/rspec/rspec-rails#routing-specs">RSpec</a> have ways to test your application routes.</p>
<p>One gotcha which using the default resource routing removes is clashing paths. If you decide to build an admin page and want to put that at <code>/admin</code>, that needs to be in the routes config before the scoped block and if a user has given themselves the name of <code>admin</code> then you may be in for some fun.</p>
<p>So the next time a need arises for an unconventional route, check the <a href="http://guides.rubyonrails.org/routing.html">documentation</a>, it&#8217;s probably possible although almost always warants thinking about.</p>
<p>The post <a href="http://pivotallabs.com/single-resource-rest-rails-routes/">Single resource REST Rails routes</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://pivotallabs.com/single-resource-rest-rails-routes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Failed attempt at trying to use refinements</title>
		<link>http://pivotallabs.com/failed-attempt-at-trying-to-use-refinements/</link>
		<comments>http://pivotallabs.com/failed-attempt-at-trying-to-use-refinements/#comments</comments>
		<pubDate>Tue, 09 Apr 2013 00:23:13 +0000</pubDate>
		<dc:creator>Robbie Clutton</dc:creator>
				<category><![CDATA[Labs]]></category>
		<category><![CDATA[ironblogger]]></category>
		<category><![CDATA[refinements]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://pivotallabs.com/?p=18294</guid>
		<description><![CDATA[<p>I was pretty interested in refinements in Ruby 2.0, and after listening to the latest Ruby Rouges podcast where some serious doubts were raised about the viability of refinements I thought I&#8217;d build a little example of how I was thinking I could use it. I failed first time out and I tried copying and pasting examples without success. After some time poking around I found a blog post about why this wasn&#8217;t working. Ultimately, refinements are sort of left in the language, but not fully supported and are marked as experimental. Here&#8217;s what I wanted to achieve. Coming from Scala in my previous job, I thought I could use refinements as a proxy for implicit conversions. Here I refine the Fixnum class to allow it to respond to a to_currency message. When called it converts the Fixnum instance to a Currency instance. class Currency attr_reader :units def initialize units&#8230;</p><p>The post <a href="http://pivotallabs.com/failed-attempt-at-trying-to-use-refinements/">Failed attempt at trying to use refinements</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>I was pretty interested in <code>refinements</code> in Ruby 2.0, and after listening to the latest <a href="http://rubyrogues.com/099-rr-ruby-2/">Ruby Rouges podcast</a> where some serious doubts were raised about the viability of refinements I thought I&#8217;d build a little example of how I was thinking I could use it.</p>
<p>I failed first time out and I tried copying and pasting <a href="http://timelessrepo.com/refinements-in-ruby">examples</a> without success. After some time poking around I found a blog post about why this <a href="http://gistflow.com/posts/743-hey-where-re-refinements">wasn&#8217;t working</a>. Ultimately, refinements are sort of left in the language, but not fully supported and are marked as experimental.</p>
<p>Here&#8217;s what I wanted to achieve. Coming from Scala in my previous job, I thought I could use refinements as a proxy for <a href="http://www.scala-lang.org/node/130">implicit conversions</a>. Here I refine the Fixnum class to allow it to respond to a <code>to_currency</code> message. When called it converts the Fixnum instance to a Currency instance.</p>
<pre><code>class Currency
  attr_reader :units

  def initialize units
    @units = units
  end
end

module CurrencyExtensions
  refine Fixnum do
    def to_currency
      Currency.new(self)
    end
  end
end

class App
  using CurrencyExtensions

  def initialize
    puts 3.to_currency
  end
end

App.new
</code></pre>
<p>Why is this interesting to me? Well, I think being able to write <code>3.to_currency</code> can result in nicer to read code than the alternative <code>Currency.new(3)</code>. Small difference perhaps.</p>
<p>There is a way to get this to work by having the <code>using</code> keyword in the global context, but it doesn&#8217;t deliver the full impact I was hoping for.</p>
<pre><code>class Currency
  attr_reader :units

  def initialize units
    @units = units
  end
end

module CurrencyExtensions
  refine Fixnum do
    def to_currency
      Currency.new(self)
    end
  end
end

using CurrencyExtensions
puts 3.to_currency
</code></pre>
<p>I&#8217;ve got other ideas to build upon this if it ever makes it into the full specification. I&#8217;ll keep watching for now.</p>
<p>The post <a href="http://pivotallabs.com/failed-attempt-at-trying-to-use-refinements/">Failed attempt at trying to use refinements</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://pivotallabs.com/failed-attempt-at-trying-to-use-refinements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NY Standup: Documentation interpolation and RVM, Brew and autolibs FTW</title>
		<link>http://pivotallabs.com/documentation-interpolation-and-rvm-brew-autolibs/</link>
		<comments>http://pivotallabs.com/documentation-interpolation-and-rvm-brew-autolibs/#comments</comments>
		<pubDate>Tue, 02 Apr 2013 13:18:46 +0000</pubDate>
		<dc:creator>Robbie Clutton</dc:creator>
				<category><![CDATA[Standup]]></category>
		<category><![CDATA[autolibs]]></category>
		<category><![CDATA[brew]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[rvm]]></category>

		<guid isPermaLink="false">http://pivotallabs.com/?p=18131</guid>
		<description><![CDATA[<p>Interestings Grant Hutchins / David Lee If you wrap the opening name of a Ruby heredoc in single quotes, its insides will act like a single-quoted string. If you wrap the opening name in backticks, the heredoc will be immediately executed through system() &#60;&#60;-HEREDOC 1 + 2 = #{1 + 2} HEREDOC =&#62; &#34;1 + 2 = 3\n&#34; &#60;&#60;-&#39;HEREDOC&#39; 1 + 2 = #{1 + 2} HEREDOC =&#62; &#34;1 + 2 = #{1 + 2}\n&#34; &#60;&#60;-HEREDOC uname date HEREDOC =&#62; &#34;Darwin\nMon Apr 1 17:50:43 EDT 2013\n&#34; Found at http://jeff.dallien.net/posts/optional-behavior-for-ruby-heredocs rvm autolibs https://rvm.io/rvm/autolibs/ In the latest versions of RVM, you can have RVM build dependencies automatically for you. For instance, if you use Homebrew, you can run $ rvm autolibs brew and from then on, RVM will automatically build any packages it needs via Homebrew. As always, read &#34;brew doctor&#34; to get more info about how to set up your particular&#8230;</p><p>The post <a href="http://pivotallabs.com/documentation-interpolation-and-rvm-brew-autolibs/">NY Standup: Documentation interpolation and RVM, Brew and autolibs FTW</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></description>
				<content:encoded><![CDATA[<h2>Interestings</h2>
<h3>Grant Hutchins / David Lee</h3>
<p>If you wrap the opening name of a Ruby heredoc in single quotes, its insides will act like a single-quoted string.</p>
<p>If you wrap the opening name in backticks, the heredoc will be immediately executed through system()</p>
<p>&lt;&lt;-HEREDOC<br />
1 + 2 = #{1 + 2}<br />
HEREDOC<br />
=&gt; &quot;1 + 2 = 3\n&quot;</p>
<p>&lt;&lt;-&#39;HEREDOC&#39;<br />
1 + 2 = #{1 + 2}<br />
HEREDOC</p>
<h1>=&gt; &quot;1 + 2 = #{1 + 2}\n&quot;</h1>
<p>&lt;&lt;-<code>HEREDOC</code><br />
uname<br />
date<br />
HEREDOC</p>
<h1>=&gt; &quot;Darwin\nMon Apr  1 17:50:43 EDT 2013\n&quot;</h1>
<p>Found at <a href="http://jeff.dallien.net/posts/optional-behavior-for-ruby-heredocs">http://jeff.dallien.net/posts/optional-behavior-for-ruby-heredocs</a></p>
<h3>rvm autolibs</h3>
<p><a href="https://rvm.io/rvm/autolibs/">https://rvm.io/rvm/autolibs/</a></p>
<p>In the latest versions of RVM, you can have RVM build dependencies automatically for you. For instance, if you use Homebrew, you can run</p>
<p>$ rvm autolibs brew</p>
<p>and from then on, RVM will automatically build any packages it needs via Homebrew.</p>
<p>As always, read &quot;brew doctor&quot; to get more info about how to set up your particular system.</p>
<p>The post <a href="http://pivotallabs.com/documentation-interpolation-and-rvm-brew-autolibs/">NY Standup: Documentation interpolation and RVM, Brew and autolibs FTW</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://pivotallabs.com/documentation-interpolation-and-rvm-brew-autolibs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Thoughts on Simple BDD</title>
		<link>http://pivotallabs.com/thoughts-on-simple-bdd/</link>
		<comments>http://pivotallabs.com/thoughts-on-simple-bdd/#comments</comments>
		<pubDate>Sat, 30 Mar 2013 16:26:07 +0000</pubDate>
		<dc:creator>Robbie Clutton</dc:creator>
				<category><![CDATA[Labs]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[ironblogger]]></category>
		<category><![CDATA[rspec]]></category>
		<category><![CDATA[simplebdd]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://pivotallabs.com/?p=18009</guid>
		<description><![CDATA[<p>A small number of projects here in New York have adopted my extremely simple behaviour driven development library, SimpleBDD, and I thought I&#8217;d share some of the emerging patterns those teams have developed while using it. SimpleBDD, is a way of using a Gherkin like specification language and turning into a method call with Ruby. It takes the approach of tools like Cucumber but reduces it down the smallest set of features. Essentially taking a method call: Given "a logged in user" and calling an underlaying function: a_logged_in_user If that method is in the scope of the executing test, that method is executed, if the method isn&#8217;t in scope or doesn&#8217;t exist the standard method not found exception is raised. It enables a developer to produce Gherkin like specifications while staying in Ruby, using the test framework of choice. I generally try and follow the advise of my colleague, Matt&#8230;</p><p>The post <a href="http://pivotallabs.com/thoughts-on-simple-bdd/">Thoughts on Simple BDD</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>A small number of projects here in New York have adopted my extremely simple behaviour driven development library, <a href="https://github.com/robb1e/simple_bdd">SimpleBDD</a>, and I thought I&#8217;d share some of the emerging patterns those teams have developed while using it. </p>
<p><a href="https://github.com/robb1e/simple_bdd">SimpleBDD</a>, is a way of using<a href="http://pivotallabs.com/author/jt/"></a> a Gherkin like specification language and turning into a method call with Ruby. It takes the approach of tools like Cucumber but reduces it down the smallest set of features. Essentially taking a method call:</p>
<p><code>Given "a logged in user"</code></p>
<p>and calling an underlaying function:</p>
<p><code>a_logged_in_user</code></p>
<p>If that method is in the scope of the executing test, that method is executed, if the method isn&#8217;t in scope or doesn&#8217;t exist the standard method not found exception is raised. It enables a developer to produce Gherkin like specifications while staying in Ruby, using the test framework of choice.</p>
<p>I generally try and follow the advise of my colleague, <a href="http://pivotallabs.com/author/mparker">Matt Parker</a>, with his excellent post on steps as <a href="http://pivotallabs.com/cucumber-step-definitions-are-not-methods/">teleportation devises</a>.  We try and create a reusable and stateless domain specific language (DSL) for our tests and our steps call into the DSL and hold state pertinent to that particular test run.   </p>
<p>At first on my current project we have had three separate areas for our request specs. We have the request spec itself which used <a href="https://github.com/robb1e/simple_bdd">SimpleBDD</a> to describe the behavior of the application. We then had a &#8216;steps&#8217; file which had the methods calls from the <a href="https://github.com/robb1e/simple_bdd">SimpleBDD</a> and translated those into the reusable DSL for the application. The steps file was reused across all request specs and was becoming big pretty quickly.</p>
<p><a href="http://pivotallabs.com/author/dkelly/">Dirk</a>, on another project which is also using <a href="https://github.com/robb1e/simple_bdd">SimpleBDD</a>, skipped the &#8216;steps&#8217; file and placed those methods straight into the rspec feature files underneath the scenario blocks. Then after some discussions with <a href="http://pivotallabs.com/author/jt/">JT</a> on where to keep the state our tests depended on, <a href="http://pivotallabs.com/author/bwheeldon/">Brent</a> and our team started using rspecs &#8216;let&#8217; methods and the &#8216;steps&#8217; within the scope of the feature block to keep the intention of the test in one place.</p>
<p>By also putting more responsibility onto the DSL, these methods are pretty dumb, leaving the test describing what the test is attempting to achieve through <a href="https://github.com/robb1e/simple_bdd">SimpleBDD</a> method calls and the how through calling the DSL via the &#8216;step&#8217; methods within the feature block in the same file. </p>
<pre><code>
require 'spec_helper'

feature 'homepage' do

  scenario 'happy path' do
    Given "an existing user with one widget"
    When "the user visits the homepage"
    Then "the user can see their widget"
  end

  let(:user) { FactoryGirl.create(:user) }
  let(:widget) { FactoryGirl.create(:widget) }

  def an_existing_user_with_one_widget
    user.widgets << widget # Using the application code to create initial state
    login user # Application DSL
  end

  def the_user_visits_the_homepage
    visit root_path # Capybara DSL
  end

  def the_user_can_see_their_widget
    can_see_widget widget # Application DSL
  end

end
</code></pre>
<p>This has been working out fairly well for us and if you're interested in a simple version for BDD for your project I hope you check this out.</p>
<p>The post <a href="http://pivotallabs.com/thoughts-on-simple-bdd/">Thoughts on Simple BDD</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://pivotallabs.com/thoughts-on-simple-bdd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Surprisingly Simple Epic Wins</title>
		<link>http://pivotallabs.com/surprisingly-simple-epic-wins/</link>
		<comments>http://pivotallabs.com/surprisingly-simple-epic-wins/#comments</comments>
		<pubDate>Sat, 16 Mar 2013 20:30:47 +0000</pubDate>
		<dc:creator>Robbie Clutton</dc:creator>
				<category><![CDATA[Labs]]></category>
		<category><![CDATA[ironblogger]]></category>
		<category><![CDATA[lean]]></category>
		<category><![CDATA[startup architecture]]></category>
		<category><![CDATA[sustainable archtiecture]]></category>
		<category><![CDATA[yagni]]></category>

		<guid isPermaLink="false">http://pivotallabs.com/?p=15973</guid>
		<description><![CDATA[<p>A surprising amount of simple can get an application over a number of speed bumps. We’re going to look up and down the whole application stack and use stories to show what simple things people have done to build a sustainable system without re-architecting. You’re gonna need a bigger boat One of my favourite stories from a colleague was when they consulted for a previous company. The application was struggling to scale and the answer from the development team was vertical scaling. Buying bigger servers, or putting in more RAM would buy more time for the application to keep ticking over until next time. My diligent colleague when joining this team spent some time digging around trying to find bottlenecks in the application. They discovered that there was not a single index on the database and that pretty much every transaction was doing a full table scan to get the&#8230;</p><p>The post <a href="http://pivotallabs.com/surprisingly-simple-epic-wins/">Surprisingly Simple Epic Wins</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>A surprising amount of simple can get an application over a number of speed bumps. We’re going to look up and down the whole application stack and use stories to show what simple things people have done to build a sustainable system without re-architecting.</p>
<h2>You’re gonna need a bigger boat</h2>
<p>One of my favourite stories from a colleague was when they consulted for a previous company. The application was struggling to scale and the answer from the development team was vertical scaling. Buying bigger servers, or putting in more RAM would buy more time for the application to keep ticking over until next time. My diligent colleague when joining this team spent some time digging around trying to find bottlenecks in the application. They discovered that there was not a single index on the database and that pretty much every transaction was doing a full table scan to get the result. The previous answer to get more RAM was so that the entire database could fit within it, in an effort to increase the performance.</p>
<p>OK, so no indexes at all seems like an extreme case, but it can be easy to skip an index or over index. Small companies don’t tend to have database administrators and if a test isn’t failing and no-one is complaining in production it’s easy to see that this area can be skipped without realising. There are some tools out there like ‘Rails Best Practices’ which can help identify where indexes are missing. Some simple changes and checks and drastically improve performance and delay that re-architecting we’re all afraid (or excited depending who you are) to do.</p>
<h2>Instrument, Instrument, Instrument</h2>
<p>A different colleague started their previous job just as a major rewrite was nearing its completion. There was some stress as a move from ColdFusion to Ruby was not paying off the dividends the team had sold to the product owners; the application performance wasn’t good enough to go live with. Tests were green and no bugs were reported so no light was shed on the troubled areas of the application. By adding instrumentation using a tool such as <a href="http://newrelic.com/">NewRelic</a>, slow processes and queries were found and refactored. Over the course of a week, working on and off the problems the performance was brought up to an acceptable level where the application could go live.</p>
<p>In a way, this was not a terrible position to be in. Performance is one of those things that it isn’t a problem until it is, and just before pushing a release out of the door seems like an ideal time to do some performance testing. The tool NewRelic itself can be used locally for this and can run as a hosted service against real production requests. On teams I’ve been involved in, I like to go through the slowest requests on and identify and fix any problem areas as a Friday afternoon chore. Instrumentation doesn’t have to come through a tool like NewRelic, it can be looking at logs of web request times and slow database queries, but taking some time to fix these can make some significant improvements.</p>
<h2>Caching in</h2>
<p>There are a number of caching techniques I’ve heard about and seen. Some have been effective, others have created more problems they had set out to resolve. First a cautionary tale.</p>
<p>Like scaling a database by putting the entire database into memory, caching can obscure underlying issues. On a recent project caching mechanisms were scattered through the code, where to cache, where to invalidate. This meant that when caching something, either through the application or even changing code, we couldn’t be sure if the caches would be affected.  In one instance, our production environment was showing some strange behaviour that we could not replicate. After digging around, we found that the caches were being invalidated by the last update of the object being cached, but we had changed the template within the cache, leaving some objects being presented with the old template, and others with the newer one.</p>
<p>Phil Karlton’s quote “there are only two hard things in Computer Science: cache invalidation and naming things” springs to mind.  The lesson here is caching can increase performance significantly but can hide issues. By caching the result of slow running code, are you hiding code that could be improved?</span></p>
<p>Rails 4 has tried to solve some of these issues by suggesting that applications generally only cache the results of rendered views. It also takes away the cache invalidation part by using the objects name, last updated time and the MD5 of the template being rendered as part of the keys. Using a caching system which automatically drops the least used cached entries should be sufficient to deal with this.</p>
<h2>Caching out</h2>
<p>Sometimes the responsibility of caching can be handed to another part of an applications’ infrastructure. This is exactly what we had done on some projects when I was working on the Guardian. The applications we were writing depended heavily on external services for data and these services, being good citizens of the web, had returned appropriate cache headers in the HTTP responses. For this given application, we didn’t want to model the data coming back, we merely wanted to transform the response and place in a HTML template. Using a HTTP caching proxy like <a href="http://www.squid-cache.org/">Squid</a> installed on the same server as the application making outbound calls meant we could rely on Squid to do the caching. There was the HTTP request out, but as this never left the server, it was a small hit.</p>
<h2>201 Created</h2>
<p>Donald Knuth said that “premature optimization is the root of all evil” but there are a series of small optimisations that can be worthwhile. When making a request to a web server or external service, an application is either changing or reading state, sometimes both at the same time. When reading back state at the same time in the same request as changing it, if an application performs only the work necessary for the response and puts the rest of the work in a background job of some implementation, the application can respond more quickly. <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC 2616 HTTP</a> response codes <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2">201</a> and <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.3">202</a> were made for this sort of operation. </span></p>
<p>The response code 201 is useful for letting the client know a resource has been created. In one of my first projects in telecommunications, we would send a 201 to indicate a phone call had been started. The client would request a call be made between two phone numbers, but we didn’t want the request to be tied up during the actual phone call and maybe returning only when the call was finished.  A 201 with a location header for the client to get the status of a call was an idea choice. A resource (the call) had been created and had an address which the client could use.</p>
<p>A more web based example could be signing users up to a new website. If there are welcome emails to be sent and mailing lists to be joined it’s not in the applications interest to make the user wait while SMTP gateways respond and third party services give their OK to a request. If this is spun out into a thread or background job the application can return to the user and allow them to carry on. The less essential processes will happen, but the delay that occurs is acceptable and the user gets a more performant experience.</p>
<h2>Perceived performance</h2>
<p>Steve Saunders and the Performance Group at Yahoo have done great work with tools like <a href="http://developer.yahoo.com/yslow/">YSlow</a> and highlighting the issues with perceived performance. When discussing this issues, Saunders said &#8220;Optimize front-end performance first, that&#8217;s where 80% or more of the end-user response time is spent&#8221;. So much of the advice YSlow suggests is so simple to implement that I recommend just setting it up at the beginning of the project and checking the advice every now and then.  Some of the suggestions are one off and can be done at the start of a project, others require some ongoing checking, but these techniques will give a faster experience for the end users.</span></p>
<p>An interesting example is where this has been taken to an interesting level has been the recent rewrite of the <a href="http://m.guardian.co.uk">Guardian mobile website</a>.  The application focuses on the most important aspect: the content. Javascript has been stripped back to only what is required to load the content, there’s no jQuery in sight.</p>
<p>The main Guardian website with an empty cache downloaded 1.06mb with 212 requests. It took 2.5 seconds for the DOM to download it’s content and 4.3 seconds before ‘onload’ was fired.  For the mobile version of the website, it downloaded 25k of data with 77 requests with the DOM content load event happening after 260ms and ‘onload’ being fired after 950ms.  That’s a pretty big difference and sometimes that effort is warranted.</p>
<p>Another technique used by the new Guardian mobile website is conditional loading of content. Say on a sports team page, after the main content has been downloaded and the reader is celebrating or sobbing depending on their team news, asynchronous calls are made for extra content. In this case, fixture/schedule information, results and related content. This information isn’t required for the reader to achieve the main purpose of their visit to the page, but it might help keep them there. Using conditional loading, the page loads quickly, the reader can start reading the article without having to wait longer for a bigger DOM or synchronous loading of the extra content.</p>
<h2>Real-time vs Near-time</h2>
<p>One important I’ve personally learnt is when asked to build something in ‘real-time’, it to ask the product owner to define real-time. Real-time can mean something very different to a developer than to a product owner or user. For the longest time I equated real-time with ‘immediately’. When I discovered the actual requirement was ‘within a reasonable time but not necessarily immediately’, this changed many assumptions I’d made about the application.</p>
<p>A company that perform complex calculations to give a user a view to potential savings when switching to a different service provider, the product team had requested the price update in real-time. The developers knew that crunching the numbers can actually take a non-trivial amount of time, so they put the processing in a background job and used the HTTP meta-refresh element to refresh the page and ultimately hold the user in place, followed by a redirect to a page with the crunched numbers.</p>
<p>This may sound crude, but when considered against the time to build a better, more ‘real-time’ experience, it was an easy choice. Consider too that this pattern is often employed during a checkout experience, especially when booking something like a flight. After your credit card information is taken, you’re taking to a holding page until the payment is confirmed and a seat reserved.</p>
<p>Meanwhile, in another part of town, a team was content with itself after building a ‘real-time’ application that displayed government bond finances and gave 10 second updates. They relied on a message queue publish-subscribe architecture to get the very latest information to the users. When they went out to watch the application in the wild, they found that those people watching these bonds would take a look every few minutes in-between doing other tasks. It turns out that working on bonds is not the same as working on the stock exchange. The application had been over-engineered for a problem that didn’t exist. After realising this, they could correct their course and remove complexities from the application while remaining ‘near-time’ for their users.</p>
<h2>Take a breath</h2>
<p>We’ve looked at some simple changes that can bring big benefits and how user perception of performance is probably more important that server side performance. We’ve also seen how asking the right questions can lead to simplicity in itself.</p>
<p>Step two to a successful business: know the product, embrace the tools that show weaknesses and learn where best to invest your time.</p>
<p>The post <a href="http://pivotallabs.com/surprisingly-simple-epic-wins/">Surprisingly Simple Epic Wins</a> appeared first on <a href="http://pivotallabs.com">Pivotal Labs</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://pivotallabs.com/surprisingly-simple-epic-wins/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic (Feed is rejected)
Page Caching using apc
Database Caching using apc
Object Caching 1215/1326 objects using apc

 Served from: pivotallabs.com @ 2013-06-18 01:45:40 by W3 Total Cache -->