<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>Nicksda</title>
	
	<link>http://nicksda.apotomo.de</link>
	<description>Nick Sutterer - respecting local traditions since 1981.</description>
	<lastBuildDate>Mon, 09 Jan 2012 15:47:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Nicksda" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="nicksda" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Ruby On REST 3: One Model, Multiple Representations!</title>
		<link>http://nicksda.apotomo.de/2012/01/ruby-on-rest-3-one-model-multiple-representations/</link>
		<comments>http://nicksda.apotomo.de/2012/01/ruby-on-rest-3-one-model-multiple-representations/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 15:34:11 +0000</pubDate>
		<dc:creator>nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[representation]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[roar]]></category>

		<guid isPermaLink="false">http://nicksda.apotomo.de/?p=1804</guid>
		<description><![CDATA[Happy New Year to all my fellow readers! I hope you had a good party! In this post I wanna clarify why representers in Roar are much more versatile than one might think at first sight. Model != Resource I know, Rails teaches us that every resource is a model with exactly one representation. This [...]]]></description>
			<content:encoded><![CDATA[<p>Happy New Year to all my fellow readers! I hope you had a good party!</p>
<p>In this post I wanna clarify why <a href="https://github.com/apotonick/roar">representers in Roar</a> are much more versatile <a href="http://nicksda.apotomo.de/2011/12/ruby-on-rest-introducing-the-representer-pattern/#comment-5346">than one might think at first sight</a>.</p>
<h3>Model != Resource</h3>
<p>I know, Rails teaches us that every resource is a model with exactly one representation. This is wrong. Not only can a resource be just anything, ranging from simple 1-to-1 mappings of database rows to virtual models like a workflow but also can your business models be represented in completely different <em>contexts</em>.</p>
<p>Let&#8217;s get back to our fruity example to learn more about this.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">orange = Fruit.<span style="color:#9900CC;">find_by_title</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;Orange&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
orange.<span style="color:#9900CC;">extend</span><span style="color:#006600; font-weight:bold;">&#40;</span>FruitRepresenter<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">to_json</span>
<span style="color:#008000; font-style:italic;">#=&gt; {&quot;title&quot;:&quot;Orange&quot;,&quot;colors&quot;:[&quot;orange&quot;]}</span></pre></div></div>

<p><a href="http://nicksda.apotomo.de/2011/12/ruby-on-rest-introducing-the-representer-pattern">In the last discussion</a> we had a <code>Fruit</code> and a <code>Bowl</code> model which were represented in their respective resources. While the fruit just contains some properties the bowl was a composition thereof. This is pretty &#8220;rails-conform&#8221; (I use this word with a negative undertone) and can simply be abstracted to hundreds of projects where people expose users, blog posts or events in their resources. This is what we call a <strong>1-to-1 mapping of model to resource</strong>.</p>
<h3>Let&#8217;s have some Booze!</h3>
<p>We wrote a simple <code>FruitRepresenter</code> for mapping apples, lemons or oranges to documents, and we had the <code>BowlRepresenter</code> to provide documents for fruit collections. That was nice. But you can do more with fruits. Why not open a distillery and make some good booze from pears or grapes?</p>
<p>What that means for our <span class="caps">REST</span> <span class="caps">API</span> is that we have to represent fruits as ingredients. We also want to document what fruits are contained in a bottle of schnaps.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> IngredientRepresenter
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::JSON</span>
&nbsp;
  property <span style="color:#ff3333; font-weight:bold;">:title</span>
  collection <span style="color:#ff3333; font-weight:bold;">:tastes_like</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>The new <code>IngredientRepresenter</code> looks a bit similar to our <code>FruitRepresenter</code>, however, it <em>represents</em> a fruit in another <em>context</em>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">pear = Fruit.<span style="color:#9900CC;">find_by_title</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;Pear&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
pear.<span style="color:#9900CC;">extend</span><span style="color:#006600; font-weight:bold;">&#40;</span>IngredientRepresenter<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">to_json</span>
<span style="color:#008000; font-style:italic;">#=&gt; undefined method `tastes_like'</span></pre></div></div>

<p>An exception. While the pear exposes a <code>#title</code> method it does not have a <code>#tastes_like</code> method. Why did I do that? I wanted to emphasize that the representer doesn&#8217;t guess anything from the represented object (the pear). It is up to the fruit to provide decent accessors like the <code>#tastes_like</code> reader. No magic or implicit semantics in Roar. And this is a good thing.</p>
<h3>Another Context, Another Module.</h3>
<p>We could easily push the missing methods into the <code>IngredientRepresenter</code> itself, but we will learn in an upcoming post that it is better to provide additional accessors in a separate module.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> Ingredient
  <span style="color:#9966CC; font-weight:bold;">def</span> tastes_like
    TastesLike.<span style="color:#9900CC;">query</span><span style="color:#006600; font-weight:bold;">&#40;</span>title<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;"># returns array.</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> tastes_like=<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">*</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>In the reader, we query the world-famous TastesLike™ web service. Since we don&#8217;t need a writer, the second method ain&#8217;t doing nothing.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">pear.<span style="color:#9900CC;">extend</span><span style="color:#006600; font-weight:bold;">&#40;</span>Ingredient, IngredientRepresenter<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">to_json</span>
<span style="color:#008000; font-style:italic;">#=&gt; {&quot;title&quot;:&quot;Pear&quot;,&quot;tastes_like&quot;:[&quot;pear&quot;,&quot;mango&quot;]}</span></pre></div></div>

<p>Cool, this is a fruit represented in a completely different context. What about the parsing, does that work, too?</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">apple = Fruit.<span style="color:#9900CC;">new</span>
apple.<span style="color:#9900CC;">extend</span><span style="color:#006600; font-weight:bold;">&#40;</span>Ingredient, IngredientRepresenter<span style="color:#006600; font-weight:bold;">&#41;</span>
apple.<span style="color:#9900CC;">from_json</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;{<span style="color:#000099;">\&quot;</span>title<span style="color:#000099;">\&quot;</span>:<span style="color:#000099;">\&quot;</span>Apple<span style="color:#000099;">\&quot;</span>,
  <span style="color:#000099;">\&quot;</span>tastes_like<span style="color:#000099;">\&quot;</span>:[<span style="color:#000099;">\&quot;</span>Pear<span style="color:#000099;">\&quot;</span>,<span style="color:#000099;">\&quot;</span>Apple<span style="color:#000099;">\&quot;</span>,<span style="color:#000099;">\&quot;</span>Mango<span style="color:#000099;">\&quot;</span>]}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#008000; font-style:italic;">#=&gt; #&lt;Fruit title=&quot;Apple&quot;, colors=[]&gt;</span></pre></div></div>

<p>Yepp, parsing an ingredient and mapping it to a fruit also works fine.</p>
<h3>Fruits in a Bottle.</h3>
<p>Let&#8217;s see how collections can be represented in different contexts.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> BottleRepresenter
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::JSON</span>
&nbsp;
  collection <span style="color:#ff3333; font-weight:bold;">:fruits</span>, <span style="color:#ff3333; font-weight:bold;">:class</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> Fruit, 
    <span style="color:#ff3333; font-weight:bold;">:extend</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span>Ingredient, IngredientRepresenter<span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>The bottle representer <em>knows</em> that it&#8217;s composed of <code>Fruit</code> instances. It does use the <code>IngredientRepresenter</code> for parsing and rendering, though. <span class="caps">BTW</span>, if you don&#8217;t like the long <code>:extend</code> assignment you are free to &#8220;hard-include&#8221; the modules directly in your models.</p>
<h3>Summary</h3>
<p>So what we&#8217;re doing here is having one model used in two completely different contexts: the conventional &#8220;fruit&#8221; context and the &#8220;ingredient&#8221; context. Imagine you&#8217;d be doing this with <code>#as_json</code> and different hash-parsing algorithms in your controllers &#8211; good luck.</p>
]]></content:encoded>
			<wfw:commentRss>http://nicksda.apotomo.de/2012/01/ruby-on-rest-3-one-model-multiple-representations/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Filters For Your Cells with cells-filters</title>
		<link>http://nicksda.apotomo.de/2012/01/filters-for-your-cells-with-cells-filters/</link>
		<comments>http://nicksda.apotomo.de/2012/01/filters-for-your-cells-with-cells-filters/#comments</comments>
		<pubDate>Sun, 08 Jan 2012 21:35:27 +0000</pubDate>
		<dc:creator>nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Cells]]></category>

		<guid isPermaLink="false">http://nicksda.apotomo.de/?p=1807</guid>
		<description><![CDATA[There&#8217;s nothing like giving a quick update about Cells on a rainy sunday evening. Almost a year ago we were happy to introduce state-args into Cells. State-args help to prevent saving state in instance variables and instead pass variables from #render_cell as arguments, making your code more explicit. One big problem was that filters couldn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s nothing like giving a quick update about <a href="https://github.com/apotonick/cells">Cells</a> on a rainy sunday evening. Almost a year ago we were happy <a href="http://nicksda.apotomo.de/2011/02/cells-3-5-release-party-summary/">to introduce state-args into Cells</a>. State-args help to prevent saving state in instance variables and instead pass variables from <code>#render_cell</code> as arguments, making your code more explicit.</p>
<p>One big problem was that filters couldn&#8217;t take advantage of that feature, thanks to a design flaw in Rails&#8217; callback implementation.</p>
<h3>Example?</h3>
<p>Consider the following call to render a freaky bassist cell.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">render_cell <span style="color:#ff3333; font-weight:bold;">:bassist</span>, <span style="color:#ff3333; font-weight:bold;">:play</span>, <span style="color:#996600;">&quot;C-sharp&quot;</span>, <span style="color:#996600;">&quot;4/4&quot;</span></pre></div></div>

<p>The cell class wants to process the incoming data in a <code>before_filter</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> BassistCell <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">Cell::Rails</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Cell::Filters</span>
&nbsp;
  before_filter <span style="color:#ff3333; font-weight:bold;">:prepare</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> prepare<span style="color:#006600; font-weight:bold;">&#40;</span>state, tone, timing<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@before</span> = <span style="color:#996600;">&quot;In #{tone} and #{timing}&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>What now works with the new <a href="https://github.com/apotonick/cells-filters">cells-filters</a> gem is that filters (here, a before filter) can receive the state-args. The implementation is very simple using the <a href="https://github.com/apotonick/hooks">hooks gem</a> for easy peasy hooks and callbacks in Ruby.</p>
<p>However, we introduce a dependency to another gem, that&#8217;s why cells-filters was released as a separate gem. Go and try it! We might need to add some more behaviour to it, but please don&#8217;t ask me to completely bloat it.</p>
<p>You can still use the old-school filters from the Rails <code>Callbacks</code> module but you won&#8217;t be able to retrieve state-args. I don&#8217;t feel like fixing this in the Rails core itself as <a href="https://github.com/rails/rails/blob/3-2-stable/activesupport/lib/active_support/callbacks.rb#L145">the implementation is a bit too complex</a> for me.</p>
<h3>Cells Development and a Roadmap.</h3>
<p>Dudes, Cells is getting more and more of a standard in Rails development. In the last year, 2011, we had almost <a href="http://gemcutter.org/gems/cells">90.000 downloads</a> &#8211; this is awesome! Thank you so much.</p>
<p>We have more plans with Cells for 2012, here&#8217;s a short summary what we&#8217;re planning.</p>
<ul>
<li>Get rid of the Rails dependency at all. We <a href="http://nicksda.apotomo.de/2011/12/mounting-a-cell-to-a-route-with-cells-3-8/">already got <code>Cell::Base</code> to use cells without a controller</a>. Now we want to go one step further and make cells completely decoupled from Rails. Imagine cells (and, numerous &#8220;helper&#8221; gems like formtastic) being renderable in Sinatra or without a framework at all.</li>
<li>Use <a href="https://github.com/rtomayko/tilt">tilt</a> as an alternative rendering engine. The Rails rendering layer is outdated and should use an abstracting rendering gem like tilt &#8211; until we can achieve this in the core, we will provide this in cells. That&#8217;ll make huge parts of cells completely independent from Rails.</li>
</ul>
<ul>
<li>Screencasts! Yeah, I&#8217;m working on a screencast series about cells, best practices and interesting solutions users sent in over the recent years.</li>
</ul>
<p>Beside that, we&#8217;re permanently trying to incorporate the cells architecture into the Rails core. Let&#8217;s see where this will lead to in Rails 4.0. Happy new year, and&#8230; Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://nicksda.apotomo.de/2012/01/filters-for-your-cells-with-cells-filters/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Mounting a Cell to a Route with Cells 3.8.</title>
		<link>http://nicksda.apotomo.de/2011/12/mounting-a-cell-to-a-route-with-cells-3-8/</link>
		<comments>http://nicksda.apotomo.de/2011/12/mounting-a-cell-to-a-route-with-cells-3-8/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 12:47:17 +0000</pubDate>
		<dc:creator>nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Cells]]></category>
		<category><![CDATA[rack]]></category>

		<guid isPermaLink="false">http://nicksda.apotomo.de/?p=1788</guid>
		<description><![CDATA[Those of you having asked for mountable cells will be happy with the recent 3.8.0 release! We entirely removed the ActionController dependency. That essentially means you can have cells outside of the standard Rails stack. Cool, heh? Cells 3.8.0 Released Two little things in 3.8 changed. Cell::Base and Cell::Rails are now different classes with different [...]]]></description>
			<content:encoded><![CDATA[<p>Those of you <a href="https://github.com/apotonick/cells/issues/15">having asked for mountable cells</a> will be happy with the recent <a href="https://rubygems.org/gems/cells/versions/3.8.0">3.8.0 release</a>! We entirely removed the ActionController dependency. That essentially means you can have cells outside of the standard Rails stack. Cool, heh?</p>
<h3>Cells 3.8.0 Released</h3>
<p>Two little things in 3.8 changed. <b><code>Cell::Base</code> and <code>Cell::Rails</code> are now different classes</b> with different semantics. Don&#8217;t panic &#8211; if you still derive your cells from <code>Cell::Rails</code> and use the <code>#render_cell</code> interface, only, nothing will change for you.</p>
<p>However, we had to tweak the <span class="caps">API</span> of some semi-public methods, here&#8217;s the new signatures.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#6666ff; font-weight:bold;">Cell::Rails</span>.<span style="color:#9900CC;">create_cell_for</span><span style="color:#006600; font-weight:bold;">&#40;</span>name, controller<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#6666ff; font-weight:bold;">Cell::Rails</span>.<span style="color:#9900CC;">render_cell_for</span><span style="color:#006600; font-weight:bold;">&#40;</span>name, state, controller, <span style="color:#006600; font-weight:bold;">*</span>args<span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Well, nothing serious, it&#8217;s just the controller sliding to the end. If you use this anywhere, be sure to change it.</p>
<h3>What&#8217;s new?</h3>
<p>What is new is that <b><code>Cell::Base</code> is now decoupled from the ActionController</b>. There simply is no AC-reference in <code>Base</code> anymore. However, this reference is still managed in <code>Cell::Rails</code> on purpose:</p>
<ul>
<li>Calls to <code>#url_for</code> and friends automatically query the parent controller for host and action name. This makes it easy to embedd cells into a controller view and still having correct links in the cell.</li>
<li>Having the AC reference, people can still use request, params and session &#8211; if they need it. We strongly discourage accessing <span class="caps">HTTP</span> properties from a view component, though.</li>
</ul>
<p>Let&#8217;s see what the new decoupled <code>Base</code> brings us.</p>
<h3>Cells on Routes.</h3>
<p>Deriving your cell from <code>Base</code> makes it <em>routeable</em>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> PostsCell <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">Cell::Base</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> show
    <span style="color:#0066ff; font-weight:bold;">@posts</span> = Post.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:all</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    render
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Routeable? Mountable? Well, let&#8217;s look at <code>config/routes.rb</code> to understand this.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">match <span style="color:#996600;">&quot;/posts&quot;</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#CC0066; font-weight:bold;">proc</span> <span style="color:#006600; font-weight:bold;">&#123;</span> |env|
  content = 
    <span style="color:#6666ff; font-weight:bold;">Cell::Base</span>.<span style="color:#9900CC;">render_cell_for</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:posts</span>, <span style="color:#ff3333; font-weight:bold;">:show</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#006600; font-weight:bold;">&#91;</span> <span style="color:#006666;">200</span>, <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#91;</span> content <span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>How cool is that? You can mount a cell to a route without the ActionController overhead and still use the rendering, the caching and testing you all love from Cells. And, hey, <strong>it&#8217;s super super fast now.</strong></p>
<p>The lack of the AC dependency makes cells even more versatile.</p>
<h3>More on Routing</h3>
<p>Since we got rid of the AC instance we have to take care of our URLs ourself. The cell still has access to all the <span class="caps">URL</span> helpers. Nevertheless, those helpers usually query the controller for host name portions, etc. That&#8217;s actually very simple with cells, too.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> PostsCell <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">Cell::Base</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> default_url_options
    <span style="color:#006600; font-weight:bold;">&#123;</span>:host <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;apotomo.de&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Just override the <code>#default_url_options</code> method as used from AC. This allows using the <span class="caps">URL</span> helpers as usual.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">PostsCell.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">posts_url</span>
<span style="color:#008000; font-style:italic;">#=&gt; &quot;http://apotomo.de/posts&quot;</span></pre></div></div>

<p>Let me know how these changes work for you! I&#8217;m eager to see new cases of applications in the next weeks.</p>
]]></content:encoded>
			<wfw:commentRss>http://nicksda.apotomo.de/2011/12/mounting-a-cell-to-a-route-with-cells-3-8/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Ruby On REST 2: Representers and the DCI Pattern</title>
		<link>http://nicksda.apotomo.de/2011/12/ruby-on-rest-2-representers-and-the-dci-pattern/</link>
		<comments>http://nicksda.apotomo.de/2011/12/ruby-on-rest-2-representers-and-the-dci-pattern/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 14:49:12 +0000</pubDate>
		<dc:creator>nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[DCI]]></category>
		<category><![CDATA[representation]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[roar]]></category>

		<guid isPermaLink="false">http://nicksda.apotomo.de/?p=1762</guid>
		<description><![CDATA[We talked about Representers earlier last week. Today, I wanna describe DCI and how it fits perfectly together with representers in Roar. What is DCI? For years we&#8217;ve been taught that &#8220;Fat Models, Skinny Controllers&#8221; is the way to organize code. Push all your domain code into your ActiveRecord classes. Many people, including me, agree [...]]]></description>
			<content:encoded><![CDATA[<p>We <a href="http://nicksda.apotomo.de/2011/12/ruby-on-rest-introducing-the-representer-pattern/">talked about Representers earlier last week</a>. Today, I wanna describe <span class="caps">DCI</span> and how it fits perfectly together with representers in <a href="https://github.com/apotonick/roar">Roar</a>.</p>
<h3>What is DCI?</h3>
<p>For years we&#8217;ve been taught that &#8220;Fat Models, Skinny Controllers&#8221; is the way to organize code. Push all your domain code into your ActiveRecord classes. <a href="http://qualityonrails.com/archives/33">Many people</a>, including me, agree that this is bullshit. This leads to bloated classes, usually combined with one or two object instances taking care of an entire workflow (aka request).</p>
<p><a href="http://en.wikipedia.org/wiki/Data,_Context_and_Interaction">DCI</a> is an architectural pattern that makes the model &#8220;fat-on-demand&#8221;: Data objects are enhanced with roles at runtime, but only when needed.</p>
<p>The <span class="caps">DCI</span> pattern consists of three concepts.</p>
<ol>
<li><strong>Data</strong> objects are supposed to contain application data. Nothing else. This would be your ActiveRecord row instance, but without any predefined behaviour. Just data.</li>
<li><strong>Context</strong> objects define what is done in the current workflow. In Rails, a controller running an action could be a context object.</li>
<li><strong>Roles</strong> are behaviour for data objects in a particular context. In Ruby, a Rails controller could mixin a module (a &#8220;role&#8221;) into an empty model row and thus let it process something.</li>
</ol>
<h3>Hooray for <span class="caps">DCI</span> &#8211; But Why?</h3>
<p>Now the thing is, I absolutely hate to hype something (except stuff I did, of course). However, <span class="caps">DCI</span> makes code better maintainable, easier to follow and way easier to test. Period.</p>
<p><span class="caps">BTW</span>, did you already check out <a href="https://github.com/apotonick/roar">my new Roar gem</a>? It&#8217;s hip!</p>
<p>Think of a classical model found in many Rails applications with maybe one hundred methods. Or fifty. Fifty methods to interfere with each other. In a <span class="caps">DCI</span> setup, an object has a limited behaviour scope. The limited knowledge makes it easier to debug and predictable.</p>
<h3>One Model, Multiple Faces</h3>
<p>Since <a href="http://nicksda.apotomo.de/2011/12/ruby-on-rest-introducing-the-representer-pattern/">representers are modules</a> they fit perfectly into the <span class="caps">DCI</span> approach, making them <em>roles</em>. Let&#8217;s consider the fruit representer from last week, again.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'roar/representer/json'</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">module</span> FruitRepresenter
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::JSON</span>
&nbsp;
  property <span style="color:#ff3333; font-weight:bold;">:title</span>
  collection <span style="color:#ff3333; font-weight:bold;">:colors</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>You still can include this representer into its &#8220;host&#8221; class directly.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Fruit
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> FruitRepresenter
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>The problem now is that the <code>Fruit</code> class is <strong>limited</strong> to one representation, only. Forever and a day you may only render one particular representation. The key about representations, however, is that <a href="http://nicksda.apotomo.de/2011/12/ruby-on-rest-introducing-the-representer-pattern/#comment-5174">one model may be represented by multiple, yeah, representations</a>.</p>
<p>Now, back to the start, let&#8217;s assume the Fruit class is some empty ActiveRecord class without any prior knowledge of representations at all.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Fruit <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
lemon = Fruit.<span style="color:#9900CC;">from_json</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;{<span style="color:#000099;">\&quot;</span>title<span style="color:#000099;">\&quot;</span>:<span style="color:#000099;">\&quot;</span>Lemon<span style="color:#000099;">\&quot;</span>}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#008000; font-style:italic;">#=&gt; undefined method `from_json' for Fruit:Class</span></pre></div></div>

<p>Yeah, there is no <code>#from_json</code> class method.</p>
<h3>Representers On <span class="caps">DCI</span></h3>
<p>In order to use the <span class="caps">DCI</span> approach, we first need an instance. Here&#8217;s how the lemon instance, and only this instance, can be extended with the fruit representer.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">lemon = Fruit.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">extend</span><span style="color:#006600; font-weight:bold;">&#40;</span>FruitRepresenter<span style="color:#006600; font-weight:bold;">&#41;</span>
lemon.<span style="color:#9900CC;">from_json</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;{<span style="color:#000099;">\&quot;</span>title<span style="color:#000099;">\&quot;</span>:<span style="color:#000099;">\&quot;</span>Lemon<span style="color:#000099;">\&quot;</span>}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
lemon.<span style="color:#9900CC;">title</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;Lemon&quot;</span></pre></div></div>

<p>Awesome! The built-in Ruby <code>#extend</code> method makes the lemon instance aware of its representation and mixes in <code>#from_json</code> and friends.</p>
<p>Naturally, this works in both ways.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">orange = Fruit.<span style="color:#9900CC;">find_by_title</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;Orange&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
orange.<span style="color:#9900CC;">extend</span><span style="color:#006600; font-weight:bold;">&#40;</span>FruitRepresenter<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">to_json</span>
<span style="color:#008000; font-style:italic;">#=&gt; {&quot;title&quot;:&quot;Apple&quot;,&quot;colors&quot;:[&quot;green&quot;]}</span></pre></div></div>

<p>The mixed-in representer also lets us render the <span class="caps">JSON</span> document.</p>
<h3>Gimme Complexity!</h3>
<p>On a flat level with single objects, this works out-of-the-box with recent Roar/representable versions. Problems arise when we have nested setups.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> BowlRepresenter
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::JSON</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::Feature::Hypermedia</span>
&nbsp;
  property <span style="color:#ff3333; font-weight:bold;">:location</span>
  collection <span style="color:#ff3333; font-weight:bold;">:items</span>, <span style="color:#ff3333; font-weight:bold;">:as</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> Fruit,
    <span style="color:#ff3333; font-weight:bold;">:extend</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> FruitRepresenter
&nbsp;
  link <span style="color:#ff3333; font-weight:bold;">:self</span> <span style="color:#9966CC; font-weight:bold;">do</span>
    <span style="color:#996600;">&quot;http://bowl/#{location}&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Using the <code>:extend</code> option we can give representable a hint about the representer to use when rendering/parsing contained objects.</p>
<p>And, hey, this works.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">empty_bowl = Bowl.<span style="color:#9900CC;">new</span>
empty_bowl.<span style="color:#9900CC;">extend</span><span style="color:#006600; font-weight:bold;">&#40;</span>BowlRepresenter<span style="color:#006600; font-weight:bold;">&#41;</span>
emtpy_bowl.<span style="color:#9900CC;">from_json</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;{<span style="color:#000099;">\&quot;</span>location<span style="color:#000099;">\&quot;</span>:<span style="color:#000099;">\&quot;</span>kitchen<span style="color:#000099;">\&quot;</span>, <span style="color:#000099;">\</span>
  <span style="color:#000099;">\&quot;</span>items<span style="color:#000099;">\&quot;</span>:[{<span style="color:#000099;">\&quot;</span>title<span style="color:#000099;">\&quot;</span>:<span style="color:#000099;">\&quot;</span>Lemon<span style="color:#000099;">\&quot;</span>,<span style="color:#000099;">\&quot;</span>colors<span style="color:#000099;">\&quot;</span>:[]}]}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">puts</span> empty_bowl.<span style="color:#9900CC;">items</span>.<span style="color:#9900CC;">first</span>.<span style="color:#9900CC;">title</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;Lemon&quot;</span></pre></div></div>

<h3>Discussion Needed!</h3>
<p>Having representers on an object level makes the whole thing really clean and versatile. You can test document rendering and parsing without polluting classes. And you can have a <code>FruitRepresenter</code>, a <code>RottenVegetableRepresenter</code> and what else you like for your orange instance. <span class="caps">BTW</span>, oranges ain&#8217;t no vegetables.</p>
<p>We still discuss about the <span class="caps">API</span> and need your opinion. Right now, we got this</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">collection <span style="color:#ff3333; font-weight:bold;">:items</span>, <span style="color:#ff3333; font-weight:bold;">:as</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> Fruit,
    <span style="color:#ff3333; font-weight:bold;">:extend</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> FruitRepresenter</pre></div></div>

<p>Here, <code>:as</code> describes the class that encapsulates the contained data. The <code>:extend</code> option helps representable to find the correct module for the nested item. Now, what about this?</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">collection <span style="color:#ff3333; font-weight:bold;">:items</span>, <span style="color:#ff3333; font-weight:bold;">:class</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> Fruit,
    <span style="color:#ff3333; font-weight:bold;">:module</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> FruitRepresenter</pre></div></div>

<p>Does that make sense? These options really just describe what&#8217;s on the right side of the hash rocket. Thanks to Scott for discussion here. Now, tell us your story!</p>
]]></content:encoded>
			<wfw:commentRss>http://nicksda.apotomo.de/2011/12/ruby-on-rest-2-representers-and-the-dci-pattern/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Ruby On REST: Introducing the Representer Pattern</title>
		<link>http://nicksda.apotomo.de/2011/12/ruby-on-rest-introducing-the-representer-pattern/</link>
		<comments>http://nicksda.apotomo.de/2011/12/ruby-on-rest-introducing-the-representer-pattern/#comments</comments>
		<pubDate>Wed, 07 Dec 2011 21:51:57 +0000</pubDate>
		<dc:creator>nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HATEOAS]]></category>
		<category><![CDATA[hypermedia]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[roar]]></category>

		<guid isPermaLink="false">http://nicksda.apotomo.de/?p=1710</guid>
		<description><![CDATA[This post introduces the new Roar gem, a framework-agnostic REST framework for Ruby that puts focus on object-oriented REST documents. More object-orientation? The calls for more object-orientation in Ruby frameworks are growing ever louder. Most web frameworks, like Rails, come with a nice database abstraction, a Rack-like HTTP endpoint, routing, and a template engine. It&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>This post introduces the new <a href="https://github.com/apotonick/roar">Roar gem</a>, a framework-agnostic <span class="caps">REST</span> framework for Ruby that puts focus on object-oriented <span class="caps">REST</span> documents.</p>
<p><strong>More object-orientation?</strong></p>
<p>The calls for more object-orientation in Ruby frameworks are growing ever louder. Most web frameworks, like Rails, come with a nice database abstraction, a Rack-like <span class="caps">HTTP</span> endpoint, routing, and a template engine. <strong>It&#8217;s the lack of additional abstraction layers</strong> that make many programmers ask for &#8220;more OOP&#8221;.</p>
<p>Already yawning? Yeah, I wrote <a href="http://nicksda.apotomo.de/2011/04/rails-misapprehensions-rails-needs-more-abstraction-layers/">about that earlier this year</a>. Let&#8217;s talk about <em>working</em> solutions now. Let&#8217;s talk about <span class="caps">REST</span>.</p>
<h3><span class="caps">REST</span> is about Documents!</h3>
<p><span class="caps">REST</span> is not only about pretty URLs. The problem ain&#8217;t URLs at all. Most frameworks have a decent routing layer to connect resource logic (aka controllers) to URLs. However, the key of <strong><span class="caps">REST</span> is pushing documents between clients and servers</strong>, so why don&#8217;t we finally focus on documents?</p>
<p>It&#8217;s the document parsing, processing and rendering that makes our heads spinning.</p>
<p><strong>Note:</strong> I here use the terms <em>representation</em> and <em>document</em> interchangable just because I can!</p>
<h4>Parsing and Processing</h4>
<p>Both clients and services have to parse incoming documents. Consider this <span class="caps">JSON</span> document.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#996600;">&quot;title&quot;</span>:  <span style="color:#996600;">&quot;Lemon&quot;</span>,
 <span style="color:#996600;">&quot;colors&quot;</span>: <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;green&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>This could be sent to a resource to create a new fruit, or be retrieved by some client which issued a <span class="caps">GET</span> request.</p>
<p>In Rails, and many <span class="caps">HTTP</span> gems, this is automatically parsed using a <span class="caps">JSON</span> gem.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">params = JSON<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'{&quot;title&quot;:  &quot;Lemon&quot;,
                &quot;colors&quot;: [&quot;green&quot;]}'</span><span style="color:#006600; font-weight:bold;">&#93;</span>
&nbsp;
params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;title&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;Lemon&quot;</span>
params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;colors&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span>0<span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;green&quot;</span></pre></div></div>

<p>We&#8217;re using a hash access to read properties from that document. This is handy! Now, assume the sender forgot to include the colors.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">params = JSON<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'{&quot;title&quot;:  &quot;Lemon&quot;}'</span><span style="color:#006600; font-weight:bold;">&#93;</span>
&nbsp;
params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;colors&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span>0<span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#008000; font-style:italic;">#=&gt;NoMethodError: undefined method `[]' for nil:NilClass</span></pre></div></div>

<p>An exception, shit! While processing the parsed document (aka hash), <em>we</em> have to take care of missing keys, wrong types etc. We as the consumer have to know about all the pitfalls with this particular document.</p>
<h4>Rendering</h4>
<p>Now that our parsing and processing code is finished, how do we render outgoing representations? We could use <code>#to_json</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#0066ff; font-weight:bold;">@lemon</span>.<span style="color:#9900CC;">to_json</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:only</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:title</span>, <span style="color:#ff3333; font-weight:bold;">:colors</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Being a quick solution for rendering small models this approach hits the wall when we have nested models but still want a plain <span class="caps">JSON</span> representation, or when we want to embed hypermedia. Also, we put &#8220;REST&#8221; logic into our database layer. It&#8217;s up to you to judge.</p>
<p>What about template languages? Let&#8217;s try <a href="https://github.com/rails/jbuilder">jbuilder</a> for <span class="caps">JSON</span> rendering.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">Jbuilder.<span style="color:#9900CC;">encode</span> <span style="color:#9966CC; font-weight:bold;">do</span> |json|
  json.<span style="color:#9900CC;">title</span>  <span style="color:#0066ff; font-weight:bold;">@lemon</span>.<span style="color:#9900CC;">title</span>
  json.<span style="color:#9900CC;">colors</span> <span style="color:#0066ff; font-weight:bold;">@lemon</span>.<span style="color:#9900CC;">colors</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Nice! But, wait. How do I test this? Can I test this separately? What if I want different representations for the same model? Do I need different templates? And&#8230; is it cool to have format knowledge both in our parsing layer and in our rendering layer? I mean, both need to know about the <code>title</code> property and the <code>colors</code> array.</p>
<h3>Representers: <span class="caps">OOP</span> to our Documents!</h3>
<p>I won&#8217;t further discuss the shown concepts here. Let me just criticize that they are not object-oriented and encourage the distribution of document internals about the entire framework.</p>
<p>Here&#8217;s how <a href="https://github.com/apotonick/roar">representers</a> can handle all that and make you a happy man at the same time!.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'roar/representer/json'</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">module</span> FruitRepresenter
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::Base</span>
&nbsp;
  property <span style="color:#ff3333; font-weight:bold;">:title</span>
  collection <span style="color:#ff3333; font-weight:bold;">:colors</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>This is all we need to <strong>declare the basic syntax</strong> of the fruit document. Note that it resides in a module which can be used anywhere in your app.</p>
<h3>Rendering a Lemon</h3>
<p>Now let&#8217;s say our database layer provides us a class <code>Fruit</code> with ActiveRecord-like behaviour.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">lemon = Fruit.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:title</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Lemon&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> lemon.<span style="color:#9900CC;">title</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;Lemon&quot;</span></pre></div></div>

<p>Since the representer knows everything about the document format it can be used for rendering <span class="caps">JSON</span>. We just have to include the <code>FruitRepresenter</code> module into the class and new methods will be available.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">Fruit.<span style="color:#9900CC;">class_eval</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#008000; font-style:italic;"># DB layer.</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::JSON</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> FruitRepresenter
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
lemon.<span style="color:#9900CC;">to_json</span>
<span style="color:#008000; font-style:italic;">#=&gt; &quot;{\&quot;title\&quot;:\&quot;Lemon\&quot;,\&quot;colors\&quot;:[]}&quot;</span></pre></div></div>

<p>Awesome, the <code>FruitRepresenter</code> module gives us a <code>#to_json</code> method. Internally, this method compiles the <span class="caps">JSON</span> document by asking the represented object (aka <code>lemon</code>) for its properties and values. Remember, the representer <em>knows</em> about those properties, since we declared them. It does <em>not know</em> anything about <code>ActiveRecord</code> and the like.</p>
<p>Now, what about parsing?</p>
<h3>Parsing a Lemon</h3>
<p>The great thing about representers is: <strong>they work bidirectional.</strong> That alone is one of the main advantages to many other gems out there. Bidirectional? Let&#8217;s just see what that is.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">orange = Fruit.<span style="color:#9900CC;">from_json</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;{<span style="color:#000099;">\&quot;</span>title<span style="color:#000099;">\&quot;</span>:<span style="color:#000099;">\&quot;</span>Orange<span style="color:#000099;">\&quot;</span>}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> orange.<span style="color:#9900CC;">inspect</span>
<span style="color:#008000; font-style:italic;">#=&gt; #&lt;Fruit:0x9df73a8 @title=&quot;Orange&quot;, @colors=[]&gt;</span></pre></div></div>

<p>We can parse representations and create objects from it! That&#8217;s <strong>bidirectional: rendering and parsing</strong> is combined in one representer.</p>
<p>Again, the representer does not know anything about the underlying database &#8211; it just creates an object it was mixed into, reads from the document and assigns properties using polite setters. Nothing more, bro.</p>
<p>Don&#8217;t like the class method? If you already have an instance, you can use <code>#from_json</code> on the instance.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">orange.<span style="color:#9900CC;">from_json</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;{<span style="color:#000099;">\&quot;</span>title<span style="color:#000099;">\&quot;</span>:<span style="color:#000099;">\&quot;</span>Yummy Orange<span style="color:#000099;">\&quot;</span>}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
orange.<span style="color:#9900CC;">title</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;Yummy Orange&quot;</span></pre></div></div>

<h3>Nesting Representers</h3>
<p>Now that we have fruits, lets put &#8216;em in a bowl. A fruit bowl contains a list of fruits.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">bowl = Bowl.<span style="color:#9900CC;">new</span>
bowl.<span style="color:#9900CC;">items</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> lemon
bowl.<span style="color:#9900CC;">items</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> orange</pre></div></div>

<p>In order to bind the fruit bowl to a <span class="caps">REST</span> resource we write another representer module.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> BowlRepresenter
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::Base</span>
&nbsp;
  property <span style="color:#ff3333; font-weight:bold;">:location</span>
  collection <span style="color:#ff3333; font-weight:bold;">:items</span>, <span style="color:#ff3333; font-weight:bold;">:as</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> Fruit
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
Bowl.<span style="color:#9900CC;">class_eval</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#008000; font-style:italic;"># DB layer.</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::JSON</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> BowlRepresenter
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Properties can be typed using the <code>:as</code> option. The target class must be a representer, too. That&#8217;s the only requirement.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">bowl.<span style="color:#9900CC;">to_json</span>
<span style="color:#008000; font-style:italic;">#=&gt; {&quot;items&quot;:[</span>
  <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#996600;">&quot;title&quot;</span>:<span style="color:#996600;">&quot;Lemon&quot;</span>,<span style="color:#996600;">&quot;colors&quot;</span>:<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span>,
  <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#996600;">&quot;title&quot;</span>:<span style="color:#996600;">&quot;Orange&quot;</span>,<span style="color:#996600;">&quot;colors&quot;</span>:<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>Typed properties allow us to build more complex representations without breaking with <span class="caps">OOP</span>. The <code>collection</code> assignment makes building lists as easy as possible. And if you still need to tweak things, there are some helpful configuration options around &#8211; more on that in one of the next posts.</p>
<h3>Representers love <span class="caps">HATEOAS</span></h3>
<p>HATEOAS? Check out <a href="http://www.eventials.com/rubyconfbr/recorded/M2UzZTJkMzY2MzdiNTg2NTUxNWM1MzI3NWY1YjRhMzYjIzM3OQ_3D_3D">this talk I gave</a> if you want to learn about Hypermedia and <span class="caps">HATEOAS</span>.</p>
<p>Hypermedia helps clients to operate the <span class="caps">API</span> without having to compute URLs. We want hypermedia in our documents.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> BowlRepresenter
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::Feature::Hypermedia</span>
&nbsp;
  link <span style="color:#ff3333; font-weight:bold;">:self</span> <span style="color:#9966CC; font-weight:bold;">do</span>
    <span style="color:#996600;">&quot;http://bowls/#{location}&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Including the <code>Hypermedia</code> feature dynamically adds a new method <code>#link</code> to our representer module. What does it do?</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">bowl.<span style="color:#9900CC;">location</span> = <span style="color:#ff3333; font-weight:bold;">:desk</span>
bowl.<span style="color:#9900CC;">to_json</span>
<span style="color:#008000; font-style:italic;">#=&gt; {</span>
<span style="color:#996600;">&quot;items&quot;</span>:<span style="color:#006600; font-weight:bold;">&#91;</span>
  <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#996600;">&quot;title&quot;</span>:<span style="color:#996600;">&quot;Lemon&quot;</span>,<span style="color:#996600;">&quot;colors&quot;</span>:<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span>,
  <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#996600;">&quot;title&quot;</span>:<span style="color:#996600;">&quot;Orange&quot;</span>,<span style="color:#996600;">&quot;colors&quot;</span>:<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span>,
<span style="color:#996600;">&quot;links&quot;</span>:<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#996600;">&quot;rel&quot;</span>:<span style="color:#996600;">&quot;self&quot;</span>,<span style="color:#996600;">&quot;href&quot;</span>:<span style="color:#996600;">&quot;http://bowls/desk&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>Seems like an easy way to embed links in our documents. In <code>roar-rails</code> the Rails <span class="caps">URL</span> helpers work like a charm within the <code>link</code> blocks &#8211; making it super simple to provide hypermedia to consumers and still being <em>railsy</em>.</p>
<h3>Representers on the Client Side</h3>
<p>Ok, representers basically are plain modules. Why not use &#8216;em on the client side as well? The client doesn&#8217;t have access to the model layer &#8211; if it does, something&#8217;s wrong! However, it&#8217;s absolutely ok to share the representer modules.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Bowl
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::JSON</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::Feature::HttpVerbs</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> BowlRepresenter <span style="color:#008000; font-style:italic;"># from a gem.</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>See how we simply use an empty class with the mixed-in representer on the client side? Remember, we don&#8217;t want to have access to the database here.</p>
<p>The next step is creating a new fruit bowl.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">bowl = Bowl.<span style="color:#9900CC;">new</span>
bowl.<span style="color:#9900CC;">location</span> = <span style="color:#996600;">&quot;kitchen&quot;</span>
bowl.<span style="color:#9900CC;">post</span>!<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;http://bowls&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>This code is enough to send a <span class="caps">POST</span> request to the specified <span class="caps">URL</span>. The <code>bowl</code> instance will serialize a <span class="caps">JSON</span> document, send it to the <span class="caps">URL</span> using the <code>HttpVerbs</code> feature, receive the new bowl, deserialize it and update its properties accordingly. You may know this behaviour from <span class="caps">REST</span> client gems like <code>ActiveResource</code> &#8211; here, with less code and manageable complexity.</p>
<h3>Consume Hypermedia, it&#8217;s gooood.</h3>
<p>The representer also makes it easy to extract hypermedia links from documents.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">bowl.<span style="color:#9900CC;">links</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:self</span><span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#008000; font-style:italic;">#=&gt; &quot;http://bowls/kitchen&quot;</span></pre></div></div>

<p>No parsing needed, the representer knows where to find your hypermedia. How cool is that?</p>
<h3><span class="caps">XML</span> is not a Crime!</h3>
<p>Roar comes with both <span class="caps">JSON</span> and <span class="caps">XML</span> representers.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> BowlRepresenter
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#6666ff; font-weight:bold;">Roar::Representer::XML</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
bowl.<span style="color:#9900CC;">to_xml</span>
<span style="color:#008000; font-style:italic;">#=&gt; '&lt;bowl&gt;</span>
<span style="color:#008000; font-style:italic;">#  &lt;link rel=&quot;self&quot; href=&quot;http://bowl/kitchen&quot;/&gt;</span>
<span style="color:#008000; font-style:italic;">#&lt;/bowl&gt;'</span></pre></div></div>

<p>Now choose if you want <span class="caps">JSON</span> or <span class="caps">XML</span> &#8211; it&#8217;s up to you! I still don&#8217;t understand the <span class="caps">XML</span> hating &#8211; did I miss something or is it just &#8220;too java&#8221;?</p>
<h3>Roar &#8211; and more?</h3>
<p><a href="http://nicksda.apotomo.de/2011/12/ruby-on-rest-introducing-the-representer-pattern/roar-180/" rel="attachment wp-att-1754"><img src="http://nicksda.apotomo.de/wp-content/uploads/2011/12/Roar-180.png" alt="" title="This awesome logo was made by the awesome @DrummerHead" width="180" height="101" class="alignleft size-full wp-image-1754" /></a> The <a href="https://github.com/apotonick/roar">Roar project</a> is still evolving. However, the current <span class="caps">API</span> is almost stable. New features, new concepts, testing helpers, etc will be added over time just like in every framework. Roar is framework-agnostic and can be used anywhere, as long as it&#8217;s Ruby.</p>
<p>Its modulare feature architecture makes it easy to extend your documents. Currently, we have some exciting on-going brainstorming and hacking on features like client-side caching in the representer instance, generic error handling, validations, DSLs, &#8230; <strong>We need you</strong> to try it out, complain, propose, help, and spread the word. Thank you for reading until here, you rock!</p>
]]></content:encoded>
			<wfw:commentRss>http://nicksda.apotomo.de/2011/12/ruby-on-rest-introducing-the-representer-pattern/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>What was a Classic Tester Became a Mockist…</title>
		<link>http://nicksda.apotomo.de/2011/11/what-was-a-classic-tester-became-a-mockist/</link>
		<comments>http://nicksda.apotomo.de/2011/11/what-was-a-classic-tester-became-a-mockist/#comments</comments>
		<pubDate>Sat, 26 Nov 2011 00:34:06 +0000</pubDate>
		<dc:creator>nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://nicksda.apotomo.de/?p=1681</guid>
		<description><![CDATA[Today I had an interesting experience which I&#8217;d like to share with my friends. No, I didn&#8217;t discover my dark side, I knew that before. What I found out is that mocking as a test method comes in handy once you get it. Why Don&#8217;t You Use RSpec? I&#8217;ve never been an RSpec fan. Not [...]]]></description>
			<content:encoded><![CDATA[<p>Today I had an interesting experience which I&#8217;d like to share with my friends. No, I didn&#8217;t discover my dark side, I knew that before. What I found out is that <strong>mocking as a test method comes in handy</strong> once you get it.</p>
<h3>Why Don&#8217;t You Use RSpec?</h3>
<p>I&#8217;ve never been an RSpec fan. Not that I don&#8217;t like the BDD-approach, which I do appreciate, I was always scared about its internal complexity. I happened to stay with <code>MiniTest</code>, and this has nothing &#8211; and i mean <em>nothing</em> &#8211; to do with <a href="http://www.rubyinside.com/dhh-offended-by-rspec-debate-4610.html">the opinion of Mr. Rails</a>.</p>
<p>Now, I don&#8217;t say that RSpec sucks and is too complex. This would be bullshit and I might even soon switch to using this powerful framework (just to make my friend <a href="http://twitter.com/justinko">Justin</a> happy) but right now, <strong>this test framework still is <em>too powerful</em> for me</strong>.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> StringTest <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">MiniTest::Spec</span>
  describe <span style="color:#996600;">&quot;String&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
    before <span style="color:#9966CC; font-weight:bold;">do</span>
      <span style="color:#0066ff; font-weight:bold;">@string</span> = <span style="color:#996600;">&quot;Be nice.&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    describe <span style="color:#996600;">&quot;#to_xml&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
      it <span style="color:#996600;">&quot;returns a string&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
        assert_kind_of <span style="color:#CC0066; font-weight:bold;">String</span>, <span style="color:#0066ff; font-weight:bold;">@string</span>.<span style="color:#9900CC;">to_xml</span>
      <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>That&#8217;s pure <a href="https://github.com/seattlerb/minitest">MiniTest</a> code, included in Ruby 1.9 and working out-of-the-box.</p>
<h3>Testing with Assertions Is Not A Crime!</h3>
<p>What <code>MiniTest::Spec</code> gives me is basically a <strong><span class="caps">BDD</span> interace for classical testers</strong>. I say <em>classic</em> as I learned that <a href="http://martinfowler.com/articles/mocksArentStubs.html">testers not using expectations are called <em>classic</em></a>. Old school. Yo.</p>
<p>I can use the keyword methods <code>describe</code> and <code>it</code> to phrase my requirements to the object (line 2 and 8). Before and after hooks provide convenient setup and teardown blocks (line 3).</p>
<p>However, I still use assertions rather than matchers as found in RSpec. <strong>I could use matchers, though.</strong> MiniTest provides these.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">  it <span style="color:#996600;">&quot;returns a string&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
    <span style="color:#0066ff; font-weight:bold;">@string</span>.<span style="color:#9900CC;">to_xml</span>.<span style="color:#9900CC;">must_be_kind_of</span> <span style="color:#CC0066; font-weight:bold;">String</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Wow, this is &#8220;better readable&#8221; in many people&#8217;s opinion. I still prefer assertions. But that&#8217;s not the point of this essay. What I was going to talk about is mocking. Right, mocking.</p>
<h3>Who needs Mocking?</h3>
<p>Now let&#8217;s say my <code>#to_xml</code> method accepts an additional parameter to configure the behaviour. We&#8217;d have to test that, too.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">  it <span style="color:#996600;">&quot;accepts the uppercase option&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
    assert_equal <span style="color:#0066ff; font-weight:bold;">@string</span>.<span style="color:#9900CC;">to_xml</span><span style="color:#006600; font-weight:bold;">&#40;</span>uppercase: <span style="color:#0000FF; font-weight:bold;">true</span><span style="color:#006600; font-weight:bold;">&#41;</span>,
      <span style="color:#996600;">&quot;&lt;STRING&gt;BE NICE.&lt;STRING&gt;&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>This could go on forever, and we test all the features that the method provides in numerous test cases &#8211; or <code>it</code>s &#8211; uppercase, lowercase, reverse, whatever.</p>
<p>Until now, I&#8217;ve been testing only using <strong>state verification</strong>. I run the method and test the state of my string instance afterwards using <em>assertions</em>. This is called state verification.</p>
<p>Purposeless, I now decide that my app needs another method. Here&#8217;s the implementation.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#CC0066; font-weight:bold;">String</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> to_exemel<span style="color:#006600; font-weight:bold;">&#40;</span>options=<span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    log <span style="color:#996600;">&quot;stupid phonetic alias called&quot;</span>
    to_xml<span style="color:#006600; font-weight:bold;">&#40;</span>options<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>I told you, it doesn&#8217;t make any sense. What I want to point out is, the method <code>#to_exemel</code> <strong>delegates its arguments to the <code>#to_xml</code> method</strong>, which we already tested thoroughly.</p>
<h3>Expect the Unexpected!</h3>
<p>Testing the logging makes sense, I already use mocking here, as I <em>mock</em> the <code>#log</code> method. More on that in a minute.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="ruby ruby" style="font-family:monospace;">describe <span style="color:#996600;">&quot;#to_exemel&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
  it <span style="color:#996600;">&quot;delegates to #to_xml&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
    <span style="color:#CC0066; font-weight:bold;">String</span>.<span style="color:#9900CC;">any_instance</span>.<span style="color:#9900CC;">expects</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:log</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
    <span style="color:#0066ff; font-weight:bold;">@string</span>.<span style="color:#9900CC;">to_exemel</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>However, <strong>testing all the behaviour of <code>#to_xml</code> <em>again</em> doesn&#8217;t</strong>. Here, I found out that mocking is cool, too.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="ruby ruby" style="font-family:monospace;">describe <span style="color:#996600;">&quot;#to_exemel&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
  it <span style="color:#996600;">&quot;delegates to #to_xml&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
    <span style="color:#0066ff; font-weight:bold;">@string</span>.
      <span style="color:#9900CC;">expects</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:to_xml</span><span style="color:#006600; font-weight:bold;">&#41;</span>.
      <span style="color:#9900CC;">with</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:uppercase</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">false</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
    <span style="color:#0066ff; font-weight:bold;">@string</span>.<span style="color:#9900CC;">to_exemel</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:uppercase</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">false</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>First, we define <em>expectations</em>: In the ongoing test case, the <code>#to_xml</code> method must be called on the <code>@string</code> instance along with the specified options hash (line 3-5).</p>
<p>I then call the actual method which is subject of our test. The method will be run &#8211; and the mocking framework internally checks, if the <code>#to_xml</code> method is really invoked the way we want it (line 7). If it doesn&#8217;t, the test will fail!</p>
<h3>I Never Knew It&#8217;s Called Behaviour Verification!</h3>
<p>What we do here is <strong>behaviour verification</strong> &#8211; we no longer have an assertion checking the final string state (we could do that additionally) but set up an <em>expectation</em>, which changes the workflow of our test slightly.</p>
<ul>
<li>I <strong>saved a lot of lines of test code</strong> since I do not assert all of <code>#to_xml</code>&#8217;s features in the <code>#to_exemel</code> method, again. This is cool.</li>
</ul>
<ul>
<li>Nevertheless, after mocking my test case includes a lot of <strong>knowledge about internal implementation</strong>. The test now&#8217;s aware that <code>#to_exemel</code> forwards to <code>#to_xml</code>. Changing this implementation detail within the class will break the expectation tests, although the second method might still work from the public perspective.</li>
</ul>
<p>It seems to be a matter of careful choice when to use mocking, and when not. I for myself still lack the experience to make smart assumptions here. However, I can call now myself a <em>Mocker</em> <a href="http://martinfowler.com/articles/mocksArentStubs.html">according to Martin Fowler&#8217;s great post</a>, which you should definitely read if you haven&#8217;t, yet!</p>
<h3>Mocking frameworks?</h3>
<p>I found <a href="http://mocha.rubyforge.org/">mocha</a> to be a very simple to use mocking framework integrating seamless into MiniTest. Never peeked at the source, though. <a href="https://github.com/rspec/rspec">RSpec</a> comes with a powerful mocking functionality as well, which most people might know, use and appreciate.</p>
<h3>Outsights?</h3>
<p>The example was stupid, I hope I still could point out the difference between status verification and behaviour verification in this short post. Let me know what you think about it. Good nite, and <strong>Mock&#8217;n&#8216;Roll!</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://nicksda.apotomo.de/2011/11/what-was-a-classic-tester-became-a-mockist/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Apotomo – Screencasts Of Glory – Episode 4</title>
		<link>http://nicksda.apotomo.de/2011/10/apotomo-screencasts-of-glory-episode-4/</link>
		<comments>http://nicksda.apotomo.de/2011/10/apotomo-screencasts-of-glory-episode-4/#comments</comments>
		<pubDate>Sat, 15 Oct 2011 11:13:42 +0000</pubDate>
		<dc:creator>nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Apotomo]]></category>
		<category><![CDATA[screencast]]></category>

		<guid isPermaLink="false">http://nicksda.apotomo.de/?p=1675</guid>
		<description><![CDATA[The 4th episode discusses partial updates of widgets. Using the event instance to transport payload data between widgets. Updating the page by sending back arbitrary JavaScript and markup from trigger states. Extracting partials to separate widget views. Using #render in both views and states for DRY code. BTW, please feel free to send me feedback [...]]]></description>
			<content:encoded><![CDATA[<p>The 4th episode discusses partial updates of widgets.</p>
<ul>
<li>Using the <code>event</code> instance to transport payload data between widgets.</li>
<li>Updating the page by sending back arbitrary JavaScript and markup from trigger states.</li>
<li>Extracting partials to separate widget views.</li>
</ul>
<ul>
<li>Using <code>#render</code> in both views and states for <span class="caps">DRY</span> code.</li>
</ul>
<p><span class="caps">BTW</span>, please feel free to send me feedback or requests for future episodes &#8211; I appreciate!</p>
<p><iframe width="425" height="349" src="http://www.youtube.com/embed/nMv63zr-xxQ?hl=de&#038;fs=1" frameborder="0" allowfullscreen></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://nicksda.apotomo.de/2011/10/apotomo-screencasts-of-glory-episode-4/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Cells 3.7 released, taataa.</title>
		<link>http://nicksda.apotomo.de/2011/10/cells-3-7-released-taataa/</link>
		<comments>http://nicksda.apotomo.de/2011/10/cells-3-7-released-taataa/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 14:49:07 +0000</pubDate>
		<dc:creator>nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Cells]]></category>

		<guid isPermaLink="false">http://nicksda.apotomo.de/?p=1659</guid>
		<description><![CDATA[Is it a good sign when a minor release doesn&#8217;t yield any stunning new features? When there&#8217;s nothing breathtaking to talk about? I guess with Cells it is &#8211; the gem finally seems to get into what it should have been 6 years ago: a mature view components framework for Rails. The 3.7 release, again, [...]]]></description>
			<content:encoded><![CDATA[<p>Is it a good sign when a minor release doesn&#8217;t yield any stunning new features? When there&#8217;s nothing breathtaking to talk about? I guess with Cells it is &#8211; the gem finally seems to get into what it should have been 6 years ago: a mature view components framework for Rails.</p>
<p>The <a href="https://github.com/apotonick/cells/commit/0c0aeedd3d05de571d8265bc2d3bc2582c370a53">3.7 release</a>, again, lost code &#8211; it&#8217;s goal was <strong>getting rid of the <code>#options</code> hang-over</strong> which succeeded. No more state in your cell, except if <em>you</em> choose to do so.</p>
<p>Here&#8217;s what changed.</p>
<h3>Rails 3.x</h3>
<p>Well, needless to say that 3.7 still runs with Rails 3.0 and 3.1. We were able to incorporate a <a href="https://github.com/rails/rails/commit/cbaad674f13067c52fa8c1a24dc498e570db4eed">couple of changes into Rails 3.1</a> to make Cells&#8217; life even easier. Thanks, José for being such a patient maintainer and happy birthday to you <img src='http://nicksda.apotomo.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<h3>Caching Inheritance and Conditionals</h3>
<p><a href="https://github.com/apotonick/cells/commit/30aff3772ccde884468778f0975cbed2f08f5883">Arthur Gunn brought us the <code>:if</code> option</a> for caching. So, if you ever needed conditional caching in your cell, here it is.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> CommentsCell <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">Cell::Base</span>
  cache <span style="color:#ff3333; font-weight:bold;">:show</span>, 
    <span style="color:#ff3333; font-weight:bold;">:if</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#CC0066; font-weight:bold;">proc</span> <span style="color:#006600; font-weight:bold;">&#123;</span> |cell, opts| opts<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:enable_cache</span><span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>To pass in the required options, I&#8217;d use <code>#render_cell</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">render_cell<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:comments</span>, <span style="color:#ff3333; font-weight:bold;">:show</span>, <span style="color:#ff3333; font-weight:bold;">:enable_cache</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">false</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>See how easy it is to bypass (or enable) caching using <code>:if</code>? Also, don&#8217;t forget that the second block parameter is the options passed to <code>#render_cell</code>, which brings us to the next core change.</p>
<p><span class="caps">BTW</span>, as a nice extension and in good <span class="caps">OOP</span> manners <a href="https://github.com/apotonick/cells/commit/4c62dd002add6e5d83df611f9d7b5c6852d05d72">cpb made the cache configurations inheritable</a>. A cell derived from <code>CommentsCell</code> will automatically inherit the cache setting for <code>#show</code> &#8211; no need for redundancy.</p>
<h3>No more Options!</h3>
<p>Luckily, we were able to remove the <code>#options</code> behaviour from Cells &#8211; it added unnecessary state, and we try to avoid internal state wherever possible (unlike the Rails core). Where you used to access the <em>magic</em> <code>options</code> hash in a state method <strong>you now use explicit state-args</strong>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> CommentsCell <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">Cell::Base</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> show<span style="color:#006600; font-weight:bold;">&#40;</span>user, comments<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@user</span>, <span style="color:#0066ff; font-weight:bold;">@comments</span> = user, comments
    render
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Since the method expects arguments (&#8220;state-args&#8221;), here&#8217;s how you&#8217;d pass them into.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">render_cell<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:comments</span>, <span style="color:#ff3333; font-weight:bold;">:show</span>, user, <span style="color:#0066ff; font-weight:bold;">@comments</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Any additional argument after the state name (2nd argument) is passed to the state. The rest is up to you.</p>
<p>If you want the old behaviour with the options hash that was &#8220;simply there&#8221;, just include the <code>Deprecations</code> module.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> CommentsCell <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">Cell::Base</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> Deprecations
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> show
    <span style="color:#0066ff; font-weight:bold;">@user</span> = options.<span style="color:#9900CC;">first</span></pre></div></div>

<h3>Test your View Assigns</h3>
<p>Another small addition is the <code>#view_assigns</code> method in <code>Cell::TestCase</code>. This works just like in conventional controller test (both Test::Unit and RSpec).</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">it <span style="color:#996600;">&quot;should assign correct values&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
  render_cell<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:comments</span>, <span style="color:#ff3333; font-weight:bold;">:show</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  assert_equal <span style="color:#0066ff; font-weight:bold;">@user_1</span>, view_assigns<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:user</span><span style="color:#006600; font-weight:bold;">&#93;</span></pre></div></div>

<p>The <code>view_assigns</code> hash captures all instance variables that were assigned in the rendering cycle. Some people may like that &#8211; I don&#8217;t. However, here it is.</p>
<p>Have fun with Cells! <img src='http://nicksda.apotomo.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://nicksda.apotomo.de/2011/10/cells-3-7-released-taataa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Released Apotomo 1.2</title>
		<link>http://nicksda.apotomo.de/2011/10/released-apotomo-1-2/</link>
		<comments>http://nicksda.apotomo.de/2011/10/released-apotomo-1-2/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 21:26:40 +0000</pubDate>
		<dc:creator>nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Apotomo]]></category>

		<guid isPermaLink="false">http://nicksda.apotomo.de/?p=1643</guid>
		<description><![CDATA[I just released Apotomo 1.2 today. Yeah. People screaming, clapping, hooting, going nuts, I can hear it. Ok, this release is nothing special, but it fixes a severe bug. No, it wasn&#8217;t just a bug, it was more, it was a design flaw! What&#8217;s new? Nothing. I already said that. However, in the last release [...]]]></description>
			<content:encoded><![CDATA[<p>I just <a href="https://github.com/apotonick/apotomo/commit/1212694f9b76d3781186a9a5f412008ca57cdecd">released Apotomo 1.2</a> today. Yeah. People screaming, clapping, hooting, going nuts, I can hear it. Ok, this release is nothing special, but it fixes a severe bug. No, it wasn&#8217;t just a bug, it was more, <strong>it was a design flaw!</strong></p>
<h3>What&#8217;s new?</h3>
<p>Nothing. I already said that. However, in the last release we added some option that allowed the following.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">  responds_to_event <span style="color:#ff3333; font-weight:bold;">:click</span>, <span style="color:#ff3333; font-weight:bold;">:passing</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:root</span></pre></div></div>

<p>The <code>:passing</code> option makes it easier to attach event handlers to other widgets, for instance, <code>:root</code>. This worked fine on a 2-level setup, but having deeper widget trees, <a href="https://github.com/apotonick/apotomo/issues/34">this failed</a> silently.</p>
<p>The problem &#8211; in short &#8211; was that the parent widget <em>sometimes</em> wasn&#8217;t available yet when the child set up its event handlers. The fix: The constructor <code>Widget.new</code> now requires the <strong>parent widget as the first argument</strong>. Makes things way simpler and explicit.</p>
<h3>What can I do with that?</h3>
<p>Well, you now can safely use the <code>:passing</code> option anywhere. You can also use <code>root</code> and <code>parent</code> in your <code>has_widgets</code> blocks now. They will be what you expect.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> CommentsWidget <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">Apotomo::Widget</span>
  has_widgets <span style="color:#9966CC; font-weight:bold;">do</span> |me|
    me.<span style="color:#9900CC;">root</span> <span style="color:#008000; font-style:italic;"># =&gt; returns the real root</span>
    me.<span style="color:#9900CC;">parent</span> <span style="color:#008000; font-style:italic;"># =&gt; well, yeah...</span></pre></div></div>

<p>All in all, the new constructor makes the Apotomo core a lot cleaner and more understandable.</p>
<h3>What changed?</h3>
<p>Be warned that <code>widget</code> doesn&#8217;t return a real widget instance anymore (line 3). Don&#8217;t be worried, you have plenty of ways do to what you want.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="ruby ruby" style="font-family:monospace;">has_widgets <span style="color:#9966CC; font-weight:bold;">do</span> |root|
  root <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> widget<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:comments</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;"># This still works.</span>
  widget<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:comments</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">markup</span>! <span style="color:#008000; font-style:italic;"># This doesn't.</span>
&nbsp;
  root<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:comments</span><span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">markup</span>! <span style="color:#008000; font-style:italic;"># This works, of course.</span>
&nbsp;
  comments = CommentsWidget<span style="color:#006600; font-weight:bold;">&#40;</span>root, <span style="color:#ff3333; font-weight:bold;">:comments</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;"># works.</span>
  comments.<span style="color:#9900CC;">markup</span>! <span style="color:#008000; font-style:italic;"># yepp, works.</span></pre></td></tr></table></div>

<p>Remember, you&#8217;re free to use the real constructor in a <code>has_widgets</code> block (line 7) if you need to grab the created instance for whatever reason. You could also use the block for that.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">  has_widgets <span style="color:#9966CC; font-weight:bold;">do</span> |root|
    root <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> widget<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:comments</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> |comments|
      comments.<span style="color:#9900CC;">markup</span>!
    <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>In short, the <code>&#60;&#60; widget(..)</code> syntax now is a <span class="caps">DSL</span> construction, what happens internally is a call to the actual constructor. Easy.</p>
<p>The second big change is that <strong>we got rid of the <code>after_add</code> hook</strong>. Since widgets receive their parent explicitely in the constructor, there&#8217;s no need for a hook after adding a widget. Use the <code>after_initialize</code> hook for that.</p>
<p>Check the <a href="https://github.com/apotonick/apotomo/blob/1212694f9b76d3781186a9a5f412008ca57cdecd/CHANGES.textile">CHANGELOG</a> for further notes and let me know if the changes work for you.</p>
<p>Kevin- thanks for donating <img src='http://nicksda.apotomo.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  <span class="caps">LOVE</span> to Austin!</p>
]]></content:encoded>
			<wfw:commentRss>http://nicksda.apotomo.de/2011/10/released-apotomo-1-2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Rails Misapprehensions: Helpers are shit.</title>
		<link>http://nicksda.apotomo.de/2011/10/rails-misapprehensions-helpers-are-shit/</link>
		<comments>http://nicksda.apotomo.de/2011/10/rails-misapprehensions-helpers-are-shit/#comments</comments>
		<pubDate>Wed, 05 Oct 2011 08:53:08 +0000</pubDate>
		<dc:creator>nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Cells]]></category>
		<category><![CDATA[Decorator]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://nicksda.apotomo.de/?p=1569</guid>
		<description><![CDATA[When I started using Rails years ago I found helpers extremely cool. I could call a method in a view and it would help me by doing something. The method was simply there, no need to worry about its source and how to access it, just call it. I got older, wiser, and more opinionated. [...]]]></description>
			<content:encoded><![CDATA[<p>When I started using Rails years ago I found helpers extremely cool. I could call a method in a view and it would <em>help</em> me by doing something. The method was simply there, <strong>no need to worry about its source</strong> and how to access it, just call it.</p>
<p>I got older, wiser, and more opinionated. I still like the concept of helpers &#8211; of <em>methods</em>. <strong>However, the way helpers are implemented in Rails sucks.</strong> Also, having object-disoriented functions in your view brings us back to the years where <span class="caps">OOP</span> still had to be invented.</p>
<p>In this post I&#8217;d like to discuss why I dislike Rails helpers and how to get out of that misery.</p>
<h3>What&#8217;s a helper?</h3>
<p>In Rails, a helper is a function.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">&lt;h2&gt;
  Hello, <span style="color:#006600; font-weight:bold;">&lt;%</span>= capitalize <span style="color:#0066ff; font-weight:bold;">@user</span>.<span style="color:#9900CC;">name</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&lt;/h2&gt;</pre></div></div>

<p>Here, the <code>#capitalize</code> method helps me capitalizing the username, which is freaking awesome. As this is pretty simple behaviour, let&#8217;s call helpers like this <strong>utility methods</strong>. They modify the input parameter, compute something or escape strings. Pretty straight-forward.</p>
<p>As a second example, I&#8217;d like to show a more complex helper.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">&lt;div id=&quot;sidebar&quot;&gt;
  <span style="color:#006600; font-weight:bold;">&lt;%</span>= render_news_for <span style="color:#0066ff; font-weight:bold;">@user</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&lt;/div&gt;</pre></div></div>

<p>This helper will iterate through news items for a particular user and <em>render</em> markup, maybe using several partials. Since it actively renders templates, let&#8217;s call this a <strong>view component</strong>.</p>
<h3>Why are helpers shit?</h3>
<p>At first sight, using helpers rocks. Capitalizing a string works like a charm &#8211; I simply call a <em>function</em> and it happens.</p>
<p>However, looking at the first helper I can identify several drawbacks.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> StringHelper
  <span style="color:#9966CC; font-weight:bold;">def</span> capitalize<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">string</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#CC0066; font-weight:bold;">string</span>.<span style="color:#9900CC;">capitalize</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<ul>
<li>Helpers in Rails are modules, which <strong>do not allow inheritance</strong>. If I&#8217;d need a foreign method I&#8217;d have to include another module into the helper module. Not a big deal.</li>
</ul>
<ul>
<li>Using the <code>#capitalize</code> methods happens without a receiver. The method is globally available in the view since Rails <em>somehow</em> mixes the helper into the view. So, what happens if I have <strong>two <code>#capitalize</code> methods in two different helpers</strong> mixed in the same view? I don&#8217;t have a clue. Do you?</li>
</ul>
<p>Before getting to solutions, let me discuss another issue with helpers: <strong>Another real problem is the implementation in Rails</strong> &#8211; how these <em>functions</em> are made available to the view.</p>
<h3>Helpers in Rails</h3>
<p>Again, I&#8217;m not talking about how <code>#form_for</code> or <code>#url_for</code> are written internally, I&#8217;m talking about <strong>how these methods get into the view</strong>.</p>
<p>In Rails 3, all helpers are mixed into the view automatically, you still can insert additional modules using the controller&#8217;s helper facilities.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> HomeController <span style="color:#006600; font-weight:bold;">&lt;</span> ApplicationController
  helper StringHelper</pre></div></div>

<p>It&#8217;s not that the implementation as-it is bad code or something, it is the idea of magically mixing methods into the view instance to make them globally available. This adds complexity to the Rails core, namely <a href="https://github.com/rails/rails/blob/v3.1.0/actionpack/lib/abstract_controller/helpers.rb">around 280</a> <a href="https://github.com/rails/rails/blob/v3.1.0/actionpack/lib/action_controller/metal/helpers.rb">LOCs</a>. <strong>Just to mix some methods into the view.</strong></p>
<h3>Helpers are shit.</h3>
<p>I desperately tried to demonstrate the major disadvantages of helpers in Rails. To summarize.</p>
<ol>
<li>
<strong>I like utility methods</strong>. There is nothing wrong with having those little &#8220;helpers&#8221; in your view. What I don&#8217;t like is that they are called without an obvious receiver &#8211; they look and feel like <em>functions</em>. This is wrong.
</li>
<li>
The way Rails mixes helpers into the view is error-prone and sucks. Following a slightly different approach <strong>there&#8217;s no need for all that complexity</strong>.
</li>
<li>
<strong>Complex helpers suck.</strong> I do believe in view components and the need for those but they shouldn&#8217;t be rendering helper methods.
</li>
</ol>
<p>Moaning is fine, but let&#8217;s see how things could be changed.</p>
<h3>Solution 1: Push Utility Methods into Decorators.</h3>
<p>Luckily, a bunch of people feel uncomfy about the current helper architecture. My friend <a href="http://blog.steveklabnik.com/2011/09/09/better-ruby-presenters.html">Steve Klabnik wrote a nice article</a> about <a href="https://github.com/jcasimir/draper">Jeff Casimir&#8217;s draper gem</a> which introduces the Decorator pattern into Rails&#8217; view layer.</p>
<p>Basically, the draper gem wraps existing model instances and <strong>provides utility (&#8220;helper&#8221;) methods on the decorated instance</strong>. Here&#8217;s an example.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> ArticleDecorator <span style="color:#006600; font-weight:bold;">&lt;</span> ApplicationDecorator
  decorates <span style="color:#ff3333; font-weight:bold;">:article</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> published_at
    model.<span style="color:#9900CC;">published_at</span>.<span style="color:#9900CC;">strftime</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;%A, %B %e&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Now that we defined the Decorator we can use it to wrap the actual model.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#0066ff; font-weight:bold;">@article</span> = ArticleDecorator.<span style="color:#9900CC;">decorate</span><span style="color:#006600; font-weight:bold;">&#40;</span>Article.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>The wrapped model can then be used in the view.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">&lt;li&gt;
  <span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#0066ff; font-weight:bold;">@article</span>.<span style="color:#9900CC;">published_at</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&lt;/li&gt;</pre></div></div>

<p>The interesting point is that we call the utility helper <strong>on the wrapped model</strong> which clearly states a receiver. No need for a homeless, global helper function. This way, we can have <strong>cleanly separated, domain-focused helpers for models</strong>. Decorators also allow inheritance and all other <span class="caps">OOP</span> features, since they are just objects.</p>
<p>Decorators are a solid technique when it comes to &#8211; well &#8211; decorating models. What can we do if there&#8217;s no matching model, for instance, when we need to call <code>#url_for</code>?</p>
<h3>Solution 2: Use the Controller Instance as View Context</h3>
<p>To learn more about that we should peek at the rendering cycle in Rails. What happens when a controller renders a template?</p>
<ol>
<li>An <code>ActionView</code> instance is created (this will be the &#8220;context&#8221;).</li>
<li>The controller manages a magical module that contains all helper methods. This module is now <strong>mixed into the <code>ActionView</code> instance</strong> to make helpers available. I already discussed the need for hundreds of lines of code in order to achieve this &#8220;knowledge transfer&#8221; from the controller to the view.</li>
<li>Next, instance variables from the controller are copied to the view instance as well.</li>
</ol>
<p><strong>These are 3 completely useless steps. Completely.</strong> Every template engine, whether it be Rails&#8217; internal or <a href="https://github.com/rtomayko/tilt">tilt</a> requires a so called <em>view context</em> whenever a template is rendered. Both instance variables and methods (that is, helper calls) used within the template are looked up on this view context instance.</p>
<p>Now, there is absolutely no reason for having a separate <code>ActionView</code> instance as view context! We can simply <strong>use the controller instance as context object</strong> and everything would work. No need to copy over variables, no need to transfer &#8220;helpers&#8221; to the view instance.</p>
<p>&#8220;Helpers&#8221; would be modules mixed into the controller &#8211; and that&#8217;s it.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> HomeController <span style="color:#006600; font-weight:bold;">&lt;</span> ApplicationController
  <span style="color:#9966CC; font-weight:bold;">include</span> UrlMethods
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> show
    <span style="color:#0066ff; font-weight:bold;">@link</span> = link_to<span style="color:#006600; font-weight:bold;">&#40;</span>home_url<span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Notice how we can use the mixed-in &#8220;helper&#8221; methods in the controller instance &#8211; we simply included them.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">&lt;a href=&quot;<span style="color:#006600; font-weight:bold;">&lt;%</span>= home_path <span style="color:#006600; font-weight:bold;">%&gt;</span>&quot;&gt;</pre></div></div>

<p>The cool thing is we can also use the utility methods in the view which will be <strong>invoked on the controller instance, again</strong>. No magic copying, just modules.</p>
<p>The <a href="https://github.com/apotonick/cells">Cells</a> project currently is experimenting with this approach and things work out fine. Will blog.</p>
<p>I can hear people now moan about <strong>too many mixed-in methods in their ActionController</strong> &#8211; and they are right! Again, this is due to Rails&#8217; monolithic view/controller design. If one single controller is responsible for rendering an entire web page, then this controller has a lot of responsibilities &#8211; too many. That&#8217;s why we should use Cells to split up the view into components, which is discussed next.</p>
<h3>Solution 3: Use View Components instead of Complex Helpers.</h3>
<p>Helpers that compute data <em>and</em> render partials are scary. Often, there is too much concerns in the little helper.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> render_news_for<span style="color:#006600; font-weight:bold;">&#40;</span>user<span style="color:#006600; font-weight:bold;">&#41;</span>
  items = user.<span style="color:#9900CC;">find_news</span>
  render <span style="color:#996600;">&quot;shared/news&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:items</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> items
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Let&#8217;s assume the <code>_news</code> partial should be reusable throughout your application, needs some special helper function <code>#sanitize</code> <em>and</em> does caching.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&lt;%</span> cache <span style="color:#9966CC; font-weight:bold;">do</span>
  <span style="color:#006600; font-weight:bold;">&lt;%-</span> <span style="color:#9966CC; font-weight:bold;">for</span> item <span style="color:#9966CC; font-weight:bold;">in</span> items <span style="color:#006600; font-weight:bold;">%&gt;</span>
    <span style="color:#006600; font-weight:bold;">&lt;%</span>= sanitize item.<span style="color:#9900CC;">text</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
  <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span></pre></div></div>

<p>Several problems here.</p>
<ul></p>
<li>Every controller has to take care of requiring the special <code>SanitizerHelper</code> for the partial.</li>
<p></p>
<li><strong>Caching happens by using helpers</strong>, again, <a href="http://nicksda.apotomo.de/2011/02/rails-misapprehensions-caching-views-is-not-the-views-job">which is no good</a> .</li>
<p>
</ul>
</p>
<p>Moving the partial and its behaviour <a href="http://nicksda.apotomo.de/2010/11/lets-write-a-reusable-sidebar-component-in-rails-3/">into a cell</a> would cleanly separate concerns. The cell could be used as view context and thus provide utility methods itself.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> NewsCell <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">Cell::Base</span>
  cache <span style="color:#ff3333; font-weight:bold;">:show</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> show<span style="color:#006600; font-weight:bold;">&#40;</span>items<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@items</span> = items
    render
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> sanitize<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">string</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;"># ...</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>This creates a reusable view component with a defined scope. Intentionally, I keep the cells discussion briefly as this would break the mold.</p>
<h3>Combining Decorators and Cells</h3>
<p>Using draper&#8217;s decorators within cells is what I figure a fantastic option. Where the <strong>decorator cleanly wraps the model object</strong> and provides utility methods for tweaking model data the <strong>cell separates the concern into a reusable view component</strong>, provides a limited scope and generic helper methods (like <code>#url_for</code>), and even caching!</p>
<p>I really don&#8217;t care whether draper, cells, or whatever replaces helpers &#8211; all I want is less magic code, more object-orientation and rock-solid software. This was a long post &#8211; gimme some feedback in the comments section or <a href="http://twitter.com/#!/apotonick">tweet me</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nicksda.apotomo.de/2011/10/rails-misapprehensions-helpers-are-shit/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
	</channel>
</rss>

