<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Julián Pinzón Eslava's blog]]></title><description><![CDATA[Julián Pinzón Eslava's blog]]></description><link>https://dev.julianpinzon.com</link><generator>RSS for Node</generator><lastBuildDate>Fri, 06 Nov 2026 23:15:05 GMT</lastBuildDate><atom:link href="https://dev.julianpinzon.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Year in Review - 2024]]></title><description><![CDATA[Inspired by Tim Riley’s year in review, I wanted to reflect a bit on what I did this year. It’s not going to be as impressive as his but I’m hoping it’ll…]]></description><link>https://dev.julianpinzon.com/year-in-review-2024</link><guid isPermaLink="true">https://dev.julianpinzon.com/year-in-review-2024</guid><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[hotwire]]></category><category><![CDATA[Turbo]]></category><category><![CDATA[buildkite]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Sun, 29 Dec 2024 18:54:54 GMT</pubDate><content:encoded><![CDATA[<p>Inspired by <a target="_blank" href="https://timriley.info/posts/2024-in-review">Tim Riley’s year in review</a>, I wanted to reflect a bit on what I did this year. It’s not going to be as impressive as his but I’m hoping it’ll serve as a way to push me forward into 2025.</p>
<h1 id="heading-work-cashapp">Work - CashApp</h1>
<p>I started 2024 working my third year at CashApp (part of Block) and was made redundant in a round of mass redundancies. Contrary to popular opinion on layoffs, I think it was a great move by the company (not forgetting it’s a problem they got themselves into by overhiring and overbuying companies). The inefficiencies and the sluggishness were very noticeable in several parts of the company; including the area I was working on. I learned a lot during my time there though; specially the inner workings of a huge product with many teams, lots of politics, and mircoservices to maintain. I learned Kotlin (which is actually great!), Kafka, gRPC and had a taste of a very difficult monolith and nice and also difficult microservices and all the gears needed to make both work.</p>
<p>I’m particularly proud of helping the <a target="_blank" href="https://github.com/cashapp/misk/tree/master/misk-hotwire">Foundation team there adopt Hotwire with Kotlin</a>. I didn’t do any dev work for that but I contributed to the overall vision of it by sharing my experiences with Rails and Hotwire.</p>
<p>I’m grateful for my time there but it was not the best place for a person like me. Thankfully my life was quite simple at the moment so being laid off wasn’t disruptive to me. I also managed to time my exit very well because I landed an amazing job shortly after that.</p>
<h1 id="heading-work-buildkite">Work - Buildkite</h1>
<p>I got an amazing job at Buildkite as Staff Software Engineer for the Package Registries product. I’d never worked in the devtools domain so it’s been quite a challenge to change from Fintech and consumer products to such a technical one but Buildkite’s bet on going Full Rails Monolith has made it incredibly pleasant. It’s such an easy and delightful codebase to work on!</p>
<p>After a very thrilling and fast paced 6 months, <a target="_blank" href="https://buildkite.com/platform/package-registries/">we launched Package Registries</a> as part of the launch of <a target="_blank" href="https://buildkite.com/platform/">Buildkite’s Scale-Out Delivery Platform</a>.</p>
<p>In these 9 months, I’ve also been carrying the Hotwire torch and lighting the way for the company to keep investing in a simpler way of making web apps. I made Package Registries the first section of the app to fully adopt all the advancements of Turbo 8 and Stimulus (as opposed to enabling it in specific sections like we do in other parts of the app) while making way for small React components where needed. I was very lucky that the company had already declared bankruptcy on the React SPA approach and had put a lot of effort into de-reactifying big chunks of the app.</p>
<p>To do so I’ve done a few things including:</p>
<ul>
<li><p>Going all in on Hotwire for Package Registries. It’s the only section/product to fully embrace it.</p>
</li>
<li><p>Organising a one-day party to gather multiple engineers to pay some front end tech debt. We managed to dereactify more stuff, adopt Lookbook to document our components, pave the way to get rid of legacy stylesheets and script files etc.</p>
</li>
<li><p>Helping revitalise the front end “guild” to get engineers excited about Hotwire</p>
</li>
<li><p>Paring with engineers from other teams to reinforce the Hotwire/Rails way.</p>
</li>
<li><p>Sharing Hotwire goodies constantly in company-wide engineering forums.</p>
</li>
</ul>
<p>It has been both a technical challenge and people one too and I’m loving it. We’ve made great progress this year and I’m sure we’ll continue to slash more complexity next year!</p>
<h1 id="heading-speaking-writing-and-oss">Speaking, Writing and OSS</h1>
<p>I had a bunch of personal stuff going on this year so I didn’t achieve as much as I wanted in this area. I gave a couple of talks this year at local meetups in Melbourne: <a target="_blank" href="https://x.com/melbjs/status/1756889310983503940">an intro to Turbo at MelbJS</a> and look into <a target="_blank" href="https://youtu.be/bxOqXLL06Sg?si=PRooDeIFA_vJ3A2V">Oaken at Melbourne Ruby</a>. I didn’t write much on my blog but I did record my <a target="_blank" href="https://youtu.be/5-LwKbHkLGg?si=fgx3-z4Ckf2qvHGN">first screencast on a gotcha I found with Turbo.</a></p>
<h1 id="heading-personal-life">Personal life</h1>
<p>It was a good year full of milestones! My girlfriend and I got engaged (with a very elaborate plan 😂), we bought a house, a car and visited our families back home. I also made a solo trip to New Zealand’s south island; it’s a ridiculously beautiful country.</p>
<p>The first half of the year I was super into working out but the second half was practically void of exercise which resulted in a massive back spasm that took me out for days. I’m trying to organise my life in a way in which movement is obligatory so I’m ditching working from home and I’m working from my local co-working space and I’m loving it.</p>
<h1 id="heading-whats-on-for-2025">What’s on for 2025?</h1>
<p>I have a few plans for next year… let’s see how I go with that:</p>
<ul>
<li><p>Writing a talk about how we’ve adopted Hotwire at Buildkite and submitting it to Rails World!</p>
</li>
<li><p>Working more on my <a target="_blank" href="https://pinzonjulian.hashnode.dev/the-attribute-builders-gem-and-playground">proposal for action view attribute builders</a></p>
</li>
<li><p>Record more screencasts and blog posts.</p>
</li>
<li><p>Build a product using Hotwire Native. I haven’t built anything native since the Turbolinks native days.</p>
</li>
<li><p>Exercise and write regularly.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Customising Single Table Inheritance mapping in Active Record]]></title><description><![CDATA[A guide on how to teach Active Record models to use different values when using Single Table Inheritance]]></description><link>https://dev.julianpinzon.com/customising-single-table-inheritance-mapping-in-active-record</link><guid isPermaLink="true">https://dev.julianpinzon.com/customising-single-table-inheritance-mapping-in-active-record</guid><category><![CDATA[Ruby]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[active record]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Thu, 07 Nov 2024 13:00:43 GMT</pubDate><content:encoded><![CDATA[<p>A few weeks ago I was working on modelling set of relationships between very similar concepts so I evaluated the different alternatives that Active Records provides for this; <a target="_blank" href="https://api.rubyonrails.org/classes/ActiveRecord/Inheritance/ClassMethods.html#method-i-abstract_class-3F">Abstract classes</a>, <a target="_blank" href="https://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html">Single Table Inheritance</a> (STI) and <a target="_blank" href="https://api.rubyonrails.org/classes/ActiveRecord/DelegatedType.html">Delegated Types</a>. I ended up going with STI (I might post about this thought process later) and in doing so, I learned that there’s a way to customise how Rails maps the relationships between parent and child classes.</p>
<h1 id="heading-how-sti-works-by-default">How STI works by default</h1>
<p>For the purpose of this article, let’s assume we’re modelling an app where there are bicycles of different types (e.g. Road, Mountain, Gravel) and that we’ve already decided that using STI is the right approach.</p>
<p>To make STI work in Rails you first need to create the parent model and its associated table with a column named <code>type</code>.</p>
<pre><code class="lang-plaintext">rails generate model bicycle type sku
</code></pre>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bicycle</span> &lt; ApplicationRecord</span>
<span class="hljs-keyword">end</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The <code>type</code> column in ActiveRecord is reserved to use it exclusively for STI. You can disable this by using <code>self.inheritance_column = nil</code> in the model.</div>
</div>

<p>Now you can create <em>subtypes</em> of Bicycle type by creating new classes that inherit from Bicycle</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MountainBicycle</span> &lt; Bicycle</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RoadBicycle</span> &lt; Bicycle</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GravelBicycle</span> &lt; Bicycle</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>Now you can create Bicycles by using the Bicycle model and providing <strong>the subclass class name</strong> as the <code>type</code> :</p>
<pre><code class="lang-ruby">mountain_bicycle = Bicycle.create!(
    <span class="hljs-symbol">type:</span> <span class="hljs-string">"MountainBicycle"</span>, <span class="hljs-comment"># the subclass class name</span>
    <span class="hljs-symbol">sku:</span> <span class="hljs-number">123456</span>
)

mountain_bicycle <span class="hljs-comment">#=&gt; Returns an instance of MountainBicycle</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">👀</div>
<div data-node-type="callout-text">Note how the instance returned is not of type <code>Bicycle</code>, it’s of type <code>MountainBicycle</code>! Rails casts the type automatically for you</div>
</div>

<p>Or you can also use the subtype directly:</p>
<pre><code class="lang-ruby">road_bicycle = RoadBicycle.create!(<span class="hljs-symbol">sku:</span> <span class="hljs-number">987654</span>)

road_bicycle <span class="hljs-comment">#=&gt; Returns an instance of RoadBicycle</span>
</code></pre>
<p>Now if you were to query for all bicycles, Active Record will return a <strong>collection of subtypes</strong>, not a collection of bicycles.</p>
<pre><code class="lang-ruby">Bicycle.all <span class="hljs-comment">#=&gt; ActiveRecord Collection</span>
<span class="hljs-comment"># [</span>
<span class="hljs-comment">#   MountainBicycle:0x000333222 id: 1,</span>
<span class="hljs-comment">#   RoadBicycle:0x0004448883203 id: 2</span>
<span class="hljs-comment"># ]</span>
</code></pre>
<p>This is very cool and very useful! Rails does this by querying the database for all Bicycles and then initialising a new instance of the class that’s stored in the database. Something like:</p>
<ol>
<li><p>Get all records</p>
</li>
<li><p>Map through records</p>
<ol>
<li><p>Get record’s <code>type</code> (which is returned as a string)</p>
</li>
<li><p>initialise an instance based on the type using something like <code>type. contantize.new(attributes)</code></p>
</li>
</ol>
</li>
</ol>
<p>In our case:</p>
<ol>
<li><p>Get all Records</p>
</li>
<li><p>Map through records</p>
<ol>
<li><p>Record 1</p>
<ol>
<li><code>“MountineBicycle”.constantize.new(attributes)</code></li>
</ol>
</li>
<li><p>Record 2</p>
<ol>
<li><code>”RoadBicycle”.constantize.new(attributes)</code></li>
</ol>
</li>
</ol>
</li>
<li><p>return <code>[MountainBicycle, RoadBicycle]</code></p>
</li>
</ol>
<p>Essentially we are <strong>mapping the type stored in the database to the class (subtype/child) it corresponds to.</strong> But what if you need to change how that mapping behaves?</p>
<h1 id="heading-customising-the-mapping">Customising the mapping</h1>
<p>The default way Active Record works is very much in line with Rails’ core values: <strong>convention</strong> over <strong>configuration</strong>. In this case, the <strong>convention</strong> is that the subtype’s class name is stored as the <code>type</code> in the parent class’ table.</p>
<p>There are some scenarios though in which you need to tweak the <strong>configuration</strong> to fit your use case; you might need to migrate from one model to another or you might not want to tie up your domain modelling with your data (which I learned is quite a healthy thing to do, specially when you’re still figuring things out).</p>
<p>To be more concise, you might want to use just the word “mountain” or “road” as the types stored in the <code>type</code> column in the <code>bicycles</code> table but let Active Record still return instances of <code>MountainBicycle</code> and <code>RoadBicycle</code>.</p>
<p>To do so, <code>ActiveRecord::Inheritance</code> provides a couple of methods you can override to teach your classes to use a different mapping between the value stored in the database and the class used to initialise records.</p>
<h1 id="heading-how-to-customise-the-mapping-of-types-when-using-single-table-inheritance">How to customise the mapping of types when using Single Table Inheritance</h1>
<p>On the parent class, you’ll need to override the <code>sti_class_for</code> (<a target="_blank" href="https://api.rubyonrails.org/classes/ActiveRecord/Inheritance/ClassMethods.html#method-i-sti_class_for">docs</a>, <a target="_blank" href="https://github.com/rails/rails/blob/d0dcb8fa6073a0c4d42600c15e82e3bb386b27d3/activerecord/lib/active_record/inheritance.rb#L194">code</a>) method to teach it how interpret the <code>type_name</code> stored in the database:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bicycle</span> &lt; ApplicationRecord</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">self</span>.<span class="hljs-title">sti_class_for</span><span class="hljs-params">(type_name)</span></span>
    <span class="hljs-keyword">case</span> type_name
    <span class="hljs-keyword">when</span> <span class="hljs-string">"road"</span> <span class="hljs-keyword">then</span> RoadBicycle
    <span class="hljs-keyword">when</span> <span class="hljs-string">"mountain"</span> <span class="hljs-keyword">then</span> MountainBicycle
    <span class="hljs-keyword">else</span> 
      raise SubclassNotFound
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>Now when you query for all bicycles using <code>Bicycle.all</code> Active Record will now know that if the <code>type</code> returns the string “road”, it should use <code>RoadBicycle</code> to initialise a new instance of the record.</p>
<p>On the subtype/child class, you’ll need to teach it which “type name” it responds to:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MountainBicycle</span> &lt; Bicycle</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">self</span>.<span class="hljs-title">sti_name</span> = "<span class="hljs-title">mountain</span>"</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RoadBicycle</span> &lt; Bicycle</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">self</span>.<span class="hljs-title">sti_name</span> = "<span class="hljs-title">road</span>"</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>This is so when you initialise and create a new instance of the subtype it know which value to store in the database.</p>
<pre><code class="lang-ruby">mountain_bicycle = MountainBicycle.new
mountain_bicycle.type <span class="hljs-comment">#=&gt; "mountain"</span>
</code></pre>
<p>Support for this was added fairly recently in a PR from 2019 <a target="_blank" href="https://github.com/rails/rails/pull/37500">https://github.com/rails/rails/pull/37500</a> by Rafael França.</p>
<hr />
<p>Recently I’ve started interacting and sharing more stuff over on Bluesky and it’s been great. Old-school Twitter vibes, no ads, very genuine interactions and a promise of a future of more control over your data in social media. I hope it stays that way for long. Here’s my profile if you wanna connect and a Starter Pack with Ruby, Rails and Web-related people to get you up and running!</p>
<ul>
<li><p><a target="_blank" href="https://bsky.app/profile/julianpinzon.com">https://bsky.app/profile/julianpinzon.com</a></p>
</li>
<li><p><a target="_blank" href="https://go.bsky.app/B3o3zhq">https://go.bsky.app/B3o3zhq</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Discovering Turbo 8 refreshes in Ruby on Rails]]></title><description><![CDATA[I'm working on a personal project in which I'm trying to squeeze every ounce of features from Turbo and in doing so I found something that I thought was a…]]></description><link>https://dev.julianpinzon.com/discovering-turbo-8-refreshes-in-ruby-on-rails</link><guid isPermaLink="true">https://dev.julianpinzon.com/discovering-turbo-8-refreshes-in-ruby-on-rails</guid><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[Turbo]]></category><category><![CDATA[morph]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Sun, 14 Jul 2024 12:17:32 GMT</pubDate><content:encoded><![CDATA[<p>I'm working on a personal project in which I'm trying to squeeze every ounce of features from Turbo and in doing so I found something that I thought was a bug.</p>
<p>When going from a simple page that uses the <code>scroll: preserve</code> attribute (<a target="_blank" href="https://turbo.hotwired.dev/reference/attributes#meta-tags">docs</a>) and the default <code>method: :replace</code> (<a target="_blank" href="https://turbo.hotwired.dev/reference/attributes#meta-tags">docs</a>) to one that uses lazy-loading turbo frames, sometimes the scroll preservation seems to fail. After digging a lot, it turns out the preservation was actually working but my assumptions of how it worked in tandem with lazy-loaded frames was wrong.</p>
<p>I made a video explaining the whole journey using a very simple test case in Rails:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=5-LwKbHkLGg">https://www.youtube.com/watch?v=5-LwKbHkLGg</a></div>
<p> </p>
<p>TL;DW (Too long, didn't watch) -- spoiler alert!</p>
<p>Scroll <strong>is preserved</strong> with lazy-loading frames. The problem comes from the height of elements while the content is lazy loaded. It's a "problem" that you can actually fix <strong>very easily</strong> using Turbo 8 <a target="_blank" href="https://turbo.hotwired.dev/reference/events#page-refreshes">page refreshes and morphing</a>!</p>
<p>Let me know what you think of this format! Is the first time I publish a screencast so any feedback is more than welcome (other than "buy a pop filter" 😅 I KNOW NOW lol)</p>
]]></content:encoded></item><item><title><![CDATA[So long, YouTube shorts!]]></title><description><![CDATA[Is that time of the year where I commit to being better, to be more present, to do more, to procrastinate less... you know... the whole New Year deal. One…]]></description><link>https://dev.julianpinzon.com/so-long-youtube-shorts</link><guid isPermaLink="true">https://dev.julianpinzon.com/so-long-youtube-shorts</guid><category><![CDATA[Browser Extension]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Thu, 28 Dec 2023 10:40:20 GMT</pubDate><content:encoded><![CDATA[<p>Is that time of the year where I commit to being better, to be more present, to do more, to procrastinate less... you know... the whole New Year deal.</p>
<p>One thing I want more of is more control over my time and social media doesn't help me do that. Specially short format videos like TikTok, Instagram Reels or my ultimate nemesis: YouTube shorts. I manage to avoid the other two because I don't use TikTok and I download Instagram about once a month, check what's been going on with my friends and delete it again. But Shorts... damn Shorts. They pull me in and, even though I try very hard not to fall into their trap, I fall more often than I like to accept.</p>
<p>So to help me tackle this, I created a ridiculously simple browser extension for myself that simply removes Shorts from YouTube so I have the old school YouTube browsing experience. I won't go into too much detail into how extensions work –I learnt the very very basics to get this going <a target="_blank" href="https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts">here</a>– but for anyone else wanting to stick it to the man, here's the code.</p>
<p>Stick all of these into a folder:</p>
<p>A manifest:</p>
<pre><code class="lang-json"> {
    <span class="hljs-attr">"manifest_version"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Shorts Blocker"</span>
    <span class="hljs-string">"description"</span>: <span class="hljs-string">"An extensio to block YouTube Shorts"</span>,
    <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0"</span>,
    <span class="hljs-attr">"action"</span>: {
      <span class="hljs-attr">"default_popup"</span>: <span class="hljs-string">"ui.html"</span>,
      <span class="hljs-attr">"default_icon"</span>: <span class="hljs-string">"default_icon.png"</span>
    },
    <span class="hljs-attr">"content_scripts"</span>: [
      {
        <span class="hljs-attr">"matches"</span>: [<span class="hljs-string">"https://*.youtube.com/*"</span>],
        <span class="hljs-attr">"css"</span>: [<span class="hljs-string">"styles.css"</span>],
        <span class="hljs-attr">"run_at"</span>: <span class="hljs-string">"document_end"</span>
      }
    ]
  }
</code></pre>
<p>A CSS file:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* styles.css */</span>

<span class="hljs-selector-tag">a</span><span class="hljs-selector-attr">[title=<span class="hljs-string">"Shorts"</span>]</span>, <span class="hljs-selector-attr">[is-shorts]</span>, <span class="hljs-selector-id">#shorts-container</span> {
    <span class="hljs-attribute">display</span>: none <span class="hljs-meta">!important</span>;
}
</code></pre>
<p>An HTLM file for the UI:</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- ui.html --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Shorts blocked!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>And an icon. You can get one in the link above to the Chrome docs.</p>
<p>That's it. Now there's no visual queue to pull me into Shorts and if I navigate to <code>/shorts</code> it autoplays the first one but doesn't display anything and doesn't let me navigate. Hacky? Sure. Effective? 100%.</p>
<p>You can install this in any browser. I added it to Safari (docs <a target="_blank" href="https://developer.apple.com/documentation/safariservices/safari_web_extensions/developing_a_safari_web_extension">here</a>) and to Chrome (docs <a target="_blank" href="https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts">here</a>).</p>
]]></content:encoded></item><item><title><![CDATA[The Attribute Builders gem and playground]]></title><description><![CDATA[In my last article, I published about the birth of AttributeBuidlers and since then I've worked some more on the project and decided that it was time to…]]></description><link>https://dev.julianpinzon.com/the-attribute-builders-gem-and-playground</link><guid isPermaLink="true">https://dev.julianpinzon.com/the-attribute-builders-gem-and-playground</guid><category><![CDATA[Rails]]></category><category><![CDATA[FormBuilder]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Sun, 29 Oct 2023 01:12:42 GMT</pubDate><content:encoded><![CDATA[<p>In my last article, I published about the birth of <code>AttributeBuidlers</code> and since then I've worked some more on the project and decided that it was time to get it out there – even in its unfinished and incomplete form– in hopes that someone will try it out and get as excited as I am about it.</p>
<p>Head on over to <a target="_blank" href="https://github.com/pinzonjulian/actionview_attribute_builders">https://github.com/pinzonjulian/actionview_attribute_builders</a> and give it a go. I have put up a few examples on how to get started with it using both Material Design Web Components and Shoelace Web Components.</p>
<p>But, who has time these days to go and write a whole new app and install the gem and write a FormBuilder for some web component library only to realise (even though I've said so above) that it's not a complete implementation yet? Well, I've got you covered.</p>
<p>I've built a playground where you can see it in action without having to write any code yourself!</p>
<p><a target="_blank" href="https://attributebuilders.julianpinzon.com">https://attributebuilders.julianpinzon.com</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698540151474/8b53339f-df65-4cf7-b701-7492c640bb6a.png" alt class="image--center mx-auto" /></p>
<p>Here you'll be able to see an implementation of the gem and interact with an actual app! It's still missing a bunch of stuff and has a few bugs here and there but as a proof of concept, it should be enough to convey the intention of the project.</p>
<p>I do recommend going through the gem's readme, and maybe some of the code, to understand what's going on.</p>
<p>I also feel like this idea is ready to be pitched to the Rails team so I'll be posting soon at <a target="_blank" href="https://discuss.rubyonrails.org">https://discuss.rubyonrails.org</a> so be on the lookout for that if you're interested.</p>
<p>Let me know what you think!</p>
]]></content:encoded></item><item><title><![CDATA[The Potential birth of AttributeBuilders]]></title><description><![CDATA[In the previous article, I said I believe splitting up the responsibility of building attributes from the actual rendering of HTML can open up many…]]></description><link>https://dev.julianpinzon.com/the-potential-birth-of-attributebuilders</link><guid isPermaLink="true">https://dev.julianpinzon.com/the-potential-birth-of-attributebuilders</guid><category><![CDATA[Ruby]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[Action view]]></category><category><![CDATA[FormBuilder]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Sat, 17 Jun 2023 11:00:39 GMT</pubDate><content:encoded><![CDATA[<p>In the previous article, I said I believe splitting up the responsibility of building attributes from the actual rendering of HTML can open up many interesting possibilities. But the work to do so might not be that simple. I've been working on this on and off for the past few months but doing so on my own started feeling like a bad idea; it may not be as good an idea as I think it is and I'm sure I'm losing the potential of getting other people to help and make the idea better.</p>
<p>This article is the way for me to share the actual code I've been writing, share the lessons I've learned along the way and hopefully get some feedback. It's also a way to showcase the process of what it would take to turn a historically private Rails API into a public one.</p>
<h1 id="heading-why-do-this">Why do this?</h1>
<h2 id="heading-the-purpose">The purpose</h2>
<p>One of the things that I like the most about the JavaScript ecosystem is the amount of detail they've put into building components for forms and how easy it is to plug them into a React app and have a beautiful, interactive experience out of the box.</p>
<p>In Rails (or in Ruby) we don't have that. Not in a way that feels native to us.</p>
<p>My purpose with this project –in this shape or another– is to unlock that potential. <strong>To provide developers with a better, carefully thought experience to create amazing form elements that integrate perfectly with Rails.</strong> Because that's Rails' superpower; the magic that comes from advanced abstractions that enable us to create great software.</p>
<h2 id="heading-the-goal">The Goal</h2>
<p>The goal is to provide an abstraction that knows about the ins and outs of the attributes that form elements need to interface seamlessly with Rails. In other words, let Rails provide the smarts for values, ids, names etc. and let developers leverage that to create their own components.</p>
<h1 id="heading-the-structure-of-helpers">The structure of helpers</h1>
<p>There are several moving pieces when it comes to rendering and testing helpers. The folder structure gives us the first clues. What we care about the most is the <code>form_helper.rb</code> module and the classes inside the <code>tags</code> folder which handle all of the creation of HTML tags and their attributes.</p>
<pre><code class="lang-plaintext">actionview/
  helpers/
    tags/
      base.rb
      text_field.rb ⚡️
      [...]
    form_helper.rb ⚡️
</code></pre>
<p>The <code>form_helper.rb</code> module defines all the methods we use when building forms like <code>text_field</code> (<code>form.text_field :title</code>) or <code>number_field</code> (<code>form.number_field :age</code>). And in turn, they use <code>tag</code> classes to render the HTML. Here's a reminder:</p>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(object_name, method, options = {})</span></span>
  Tags::TextField.new(object_name, method, <span class="hljs-keyword">self</span>, options).render
<span class="hljs-keyword">end</span>
</code></pre>
<p>As we saw in the previous article, a lot of the heavy lifting is defined in the <a target="_blank" href="https://github.com/rails/rails/blob/main/actionview/lib/action_view/helpers/tags/base.rb"><code>helpers/base.rb</code></a> class and all of its associated modules:</p>
<pre><code class="lang-ruby">Helpers::ActiveModelInstanceTag
Helpers::TagHelper
Helpers::FormTagHelper
FormOptionsHelper
</code></pre>
<h2 id="heading-testing">Testing</h2>
<p><strong>All</strong> of the classes inside the <code>tags</code> folder are tagged with a special comment:</p>
<p><code># :nodoc:</code></p>
<p>In Rails, this means that this class is <strong>private</strong> and meant only to be used internally by the framework and that it can change without giving notice to anyone. Classes tagged with this have <strong>no documentation</strong>, which further signals to developers this shouldn't be used. Just like private methods, these "private classes" in this case are not tested directly. Instead, they're tested through whoever implements them, which in our case is the <code>form_helper</code>.</p>
<p>Let's take the <a target="_blank" href="https://github.com/rails/rails/blob/main/actionview/lib/action_view/helpers/tags/text_field.rb"><code>Tags::TextField</code></a> class as an example. There is no test for this class, but its behaviour is tested through several tests for the <a target="_blank" href="https://github.com/rails/rails/blob/main/actionview/lib/action_view/helpers/form_helper.rb"><code>form_helper.rb</code></a> module: <a target="_blank" href="https://github.com/rails/rails/blob/main/actiontext/test/template/form_helper_test.rb"><code>form_helper_test.rb</code></a> (check some of these tests <a target="_blank" href="https://github.com/rails/rails/blob/main/actionview/test/template/form_helper_test.rb#L393">here</a>). It has 19 tests to be more exact. Here's an example test for reference:</p>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_text_field_placeholder_with_string_value</span></span>
  I18n.with_locale <span class="hljs-symbol">:placeholder</span> <span class="hljs-keyword">do</span>
    assert_dom_equal(
      <span class="hljs-string">'&lt;input id="post_cost" name="post[cost]" placeholder="HOW MUCH?" type="text" /&gt;'</span>, 
      text_field(<span class="hljs-symbol">:post</span>, <span class="hljs-symbol">:cost</span>, <span class="hljs-symbol">placeholder:</span> <span class="hljs-string">"HOW MUCH?"</span>))
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<h1 id="heading-phase-1-splitting-helpers-ongoing">Phase 1: Splitting helpers (ongoing)</h1>
<blockquote>
<p>This is by no means a finalised proposal. Everything can be changed and challenged. This idea is still in flux!</p>
</blockquote>
<p>So, what are the actual steps needed to take, for example, a <code>Tags::TextField</code> helper and turning it into <strong>two classes with distinct responsibilities</strong>? Well, I've done quite a bit of that already. Visit this fork of Rails over at my GitHub account (the branch is names: <code>separate_tag_helpers_responsability</code>:</p>
<p><a target="_blank" href="https://github.com/pinzonjulian/rails/tree/separate_tag_helpers_responsability">https://github.com/pinzonjulian/rails/tree/separate_tag_helpers_responsability</a></p>
<p><em>(If you want to follow in more detail what I've done, check each commit</em> <a target="_blank" href="https://github.com/rails/rails/compare/main...pinzonjulian:rails:separate_tag_helpers_responsability"><em>here</em></a><em>)</em></p>
<p>The process is more or less simple; I'm not creating something entirely new for the framework. I'm just refactoring private internals in the hopes of making them public at some point.</p>
<h2 id="heading-the-birth-of-attributebuilders">The birth of AttributeBuilders</h2>
<blockquote>
<p>The links in the following section point to the fork I'm working on so be sure to click and take a look!</p>
</blockquote>
<p>I went for <code>AttributeBuilders</code> as the name for the classes responsible for all the logic behind the different attributes or options needed to build a tag. The responsibility of these classes is to output a hash with all the options for each tag. So to create an <code>&lt;input type="text" name="article[title]" id="article_title" value="Hello, World!"&gt;</code> the output would be something like this:</p>
<pre><code class="lang-ruby">{
  <span class="hljs-symbol">type:</span> <span class="hljs-string">"text"</span>,
  <span class="hljs-symbol">name:</span> <span class="hljs-string">"article[title]"</span>,
  <span class="hljs-symbol">id:</span> <span class="hljs-string">"article_title"</span>,
  <span class="hljs-symbol">value:</span> <span class="hljs-string">"Hello, World!"</span>
}
</code></pre>
<p>Just as <code>Tags</code> have a <code>Base</code> they inherit most of their behaviour from, <code>AttributeBuilders</code> (<a target="_blank" href="https://github.com/pinzonjulian/rails/tree/separate_tag_helpers_responsability/actionview/lib/action_view/helpers/attribute_builders">folder</a>) have a <a target="_blank" href="https://github.com/pinzonjulian/rails/blob/separate_tag_helpers_responsability/actionview/lib/action_view/helpers/attribute_builders/base.rb"><code>Base</code></a> class too to handle all the heavy lifting.</p>
<h2 id="heading-the-first-attributebuilder-text-field">The first AttributeBuilder: Text Field</h2>
<blockquote>
<p>A reminder the code you see is a work in progress and has a few rough edges and inconsistencies still.</p>
</blockquote>
<p>I started with the <code>TextField</code> Attribute Builder for several reasons: first, it's probably one of the easiest tags to work with (compared to something like <code>collection_check_boxes</code>). Second, it turns out that TextField is the basis for a bunch of other helpers like <code>number</code>, <code>email</code>, <code>password</code> etc.</p>
<p>Doing this meant copying the <code>Tags::TextField</code> class and stripping it off its rendering responsibility, leaving only the options-building one. Here's a <strong>simplified</strong> preview (Click here to see the complete one <a target="_blank" href="https://github.com/pinzonjulian/rails/blob/separate_tag_helpers_responsability/actionview/lib/action_view/helpers/attribute_builders/text_field.rb"><code>AttributeBuilders::TextField</code></a>):</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ActionView::Helpers::AttributeBuilders::TextField</span> &lt; Base <span class="hljs-comment"># :nodoc:</span></span>
  <span class="hljs-keyword">include</span> Tags::Placeholderable

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">html_attributes</span></span>
    options = @options.stringify_keys
    options[<span class="hljs-string">"size"</span>] = options[<span class="hljs-string">"maxlength"</span>] <span class="hljs-keyword">unless</span> options.key?(<span class="hljs-string">"size"</span>)
    options[<span class="hljs-string">"type"</span>] <span class="hljs-params">||</span>= field_type
    options[<span class="hljs-string">"value"</span>] = options.fetch(<span class="hljs-string">"value"</span>) { value_before_type_cast } <span class="hljs-keyword">unless</span> field_type == <span class="hljs-string">"file"</span>
    add_default_name_and_id(options)

    <span class="hljs-keyword">return</span> options
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>Moving all of this code meant that the <code>Tags::TextField</code> class also needed to change to only have an HTML rendering responsibility. <a target="_blank" href="https://github.com/pinzonjulian/rails/blob/separate_tag_helpers_responsability/actionview/lib/action_view/helpers/tags/text_field.rb">This is how it ended up looking</a>:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">module</span> <span class="hljs-title">ActionView</span></span>
  <span class="hljs-class"><span class="hljs-keyword">module</span> <span class="hljs-title">Helpers</span></span>
    <span class="hljs-class"><span class="hljs-keyword">module</span> <span class="hljs-title">Tags</span></span>
      <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TextField</span> &lt; RendererBase</span>
        <span class="hljs-keyword">include</span> Helpers::ActiveModelInstanceTag, Helpers::TagHelper

        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">render</span></span>
          tag(<span class="hljs-string">"input"</span>, @attributes)
        <span class="hljs-keyword">end</span>
      <span class="hljs-keyword">end</span>
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>(Note that the parent is called <code>RendererBase</code> class. This is a temporary <code>Base</code> class I created to support the migration. This class needs some work and should eventually be renamed back to <code>Tags::Base</code>)</p>
<p>Finally, let's put this to use in the <code>FormHelper</code> module in the <a target="_blank" href="https://github.com/pinzonjulian/rails/blob/separate_tag_helpers_responsability/actionview/lib/action_view/helpers/form_helper.rb#L1172">text_field method</a>:</p>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(object_name, method, options = {})</span></span>
  attribute_builder = AttributeBuilders::TextField.new(object_name, method, <span class="hljs-keyword">self</span>, options)
  html_attributes = attribute_builder.html_attributes

  text_field_element = Tags::TextField.new(
    <span class="hljs-symbol">attributes:</span> html_attributes, 
    <span class="hljs-symbol">object:</span> attribute_builder.object, 
    <span class="hljs-symbol">method_name:</span> method, 
    <span class="hljs-symbol">template_object:</span> <span class="hljs-keyword">self</span>
  )

  text_field_element.render
<span class="hljs-keyword">end</span>
</code></pre>
<p>In plain English, this is:</p>
<ul>
<li><p>Initializing the <code>AttributeBuilders::TextField</code> class</p>
</li>
<li><p>building the attributes calling the <code>html_attributes</code> method on <code>attribute_builder</code></p>
</li>
<li><p>Initializing the <code>Tags::TextField</code> class</p>
</li>
<li><p>rendering the HTML calling the <code>render</code> method on the <code>text_field_element</code></p>
</li>
</ul>
<p>Since the behaviour didn't change at all, all the tests pass!</p>
<p>(Isn't that more code than before? Yes. Is that worse? I don't think so. Maybe there's an extra missing abstraction there but the possibilities this opens up are huge).</p>
<h2 id="heading-what-ive-done-so-far">What I've done so far</h2>
<p>TextField was the first one but I've already tackled a bunch of these:</p>
<ul>
<li><p>check_box</p>
</li>
<li><p>color_field</p>
</li>
<li><p>date_field</p>
</li>
<li><p>datetime_field</p>
</li>
<li><p>datetime_local_field</p>
</li>
<li><p>email_field</p>
</li>
<li><p>file_field</p>
</li>
<li><p>hidden_field</p>
</li>
<li><p>number_field</p>
</li>
<li><p>password_field</p>
</li>
<li><p>radio_button</p>
</li>
<li><p>range_field</p>
</li>
<li><p>search_field</p>
</li>
<li><p>text_area</p>
</li>
<li><p>text_field</p>
</li>
<li><p>time_field</p>
</li>
<li><p>url_field</p>
</li>
<li><p>week_field</p>
</li>
</ul>
<p>It looks like an impressive, long list but most of these are children of <code>TextField</code> which made it super easy once I figured out the basics. There are about 9 or so to go (like <code>CollectionSelect</code>, <code>GroupedCollectionSelect</code> and others) which might present some challenges.</p>
<h1 id="heading-phase-2-creating-a-public-interface">Phase 2: Creating a public interface</h1>
<p>If this is a good idea and the Rails Core team accepts it and merges it, then we can move on to the next Phase.</p>
<p>When Phase 1 finishes nothing will have changed for developers yet. The interfaces would be the same and no new public APIs would have been created. The next step would be to turn these private, <code>#:nodoc</code> classes into public ones which means two things: testing them directly and documenting them thoroughly.</p>
<h2 id="heading-on-testing">On testing</h2>
<p>There are two things to do here. The first is to create tests for the new classes; this means turning the current tests from ones that check for HTML to ones that check the proper hashes are built. Once those tests are converted, we will need to figure out what a test for the rendering class looks like (I don't yet have an answer for this one).</p>
<h1 id="heading-calling-all-developers">Calling all developers!</h1>
<p>Here's where you come in.</p>
<p>I believe in this idea –or some form of it– but I need opinions and challenges. I need other perspectives to make this even better. What do you think? How would you tackle this problem? How would you tackle the process of contributing this to Rails?</p>
<p>For example, I've thought of making this a gem, independent of Rails that patches the <code>Tag</code> classes and the <code>FormHelper</code>. Doing so would allow us to play with it safely in other code bases, maybe create an example design system with it or something like that. I started it in the Rails codebase because I needed the tests to make sure I wasn't breaking anything but maybe once it's done, it could be extracted into a Gem.</p>
<hr />
<p>That's all for this series. I <strong>really</strong> hope something comes out of this because I think this is one of the most interesting areas in Rails right now. With the newly found love for simpler applications, small-but-mighty teams, the innovation brought by component libraries like ViewComponent and Phlex, and the energy brought by HTML over the wire and the return to glorious server-side rendered HTML, I believe there's no better time to keep pushing forward. To keep making Ruby and Rails better to enable a future with better, simpler and more elegant applications that solve real-world problems.</p>
]]></content:encoded></item><item><title><![CDATA[Diving Deep: Action View Form Helpers]]></title><description><![CDATA[In the previous article, I mentioned that Action View has some component-like classes that render form elements. Let's deep dive into a simple one…]]></description><link>https://dev.julianpinzon.com/diving-deep-action-view-form-helpers</link><guid isPermaLink="true">https://dev.julianpinzon.com/diving-deep-action-view-form-helpers</guid><category><![CDATA[Ruby]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[Action view]]></category><category><![CDATA[FormBuilder]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Thu, 15 Jun 2023 02:00:18 GMT</pubDate><content:encoded><![CDATA[<p>In the previous article, I mentioned that Action View has some component-like classes that render form elements. Let's deep dive into a simple one: <code>Tags::TextField</code>.</p>
<p>This class is used in the <code>FormBuilder</code> like so (<a target="_blank" href="https://github.com/rails/rails/blob/e88857bbb9d4e1dd64555c34541301870de4a45b/actionview/lib/action_view/helpers/form_helper.rb#L1661">source</a>):</p>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(object_name, method, options = {})</span></span>
  Tags::TextField.new(object_name, method, <span class="hljs-keyword">self</span>, options).render
<span class="hljs-keyword">end</span>
</code></pre>
<p>Note that two things are happening here. First, an instance of <code>Tags::TextField</code> is initialized with the necessary <code>arguments</code>. Then <code>render</code> is called which is what outputs HTML.</p>
<p>Let's take a peek into the class: (<a target="_blank" href="https://github.com/rails/rails/blob/e88857bbb9d4e1dd64555c34541301870de4a45b/actionview/lib/action_view/helpers/tags/text_field.rb">source</a>) (I've compressed it and removed some irrelevant stuff for the article)</p>
<pre><code class="lang-ruby">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ActionView::Helpers::Tags::TextField</span> &lt; Base</span>
  <span class="hljs-keyword">include</span> Placeholderable

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">render</span></span>
    options = @options.stringify_keys
    options[<span class="hljs-string">"size"</span>] = options[<span class="hljs-string">"maxlength"</span>] <span class="hljs-keyword">unless</span> options.key?(<span class="hljs-string">"size"</span>)
    options[<span class="hljs-string">"type"</span>] <span class="hljs-params">||</span>= field_type
    options[<span class="hljs-string">"value"</span>] = options.fetch(<span class="hljs-string">"value"</span>) { value_before_type_cast } <span class="hljs-keyword">unless</span> field_type == <span class="hljs-string">"file"</span>
    add_default_name_and_id(options)
    tag(<span class="hljs-string">"input"</span>, options)
  <span class="hljs-keyword">end</span>

  <span class="hljs-comment"># ...</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>The <code>render</code> method has some logic in it. It:</p>
<ul>
<li><p>adds a few parameters to options like <code>size</code> and <code>type</code></p>
</li>
<li><p>calculates the <code>value</code> the input field should have using <code>value_before_type_cast</code></p>
</li>
<li><p>uses <code>add_default_name_and_id</code> to mutate the options hash to add conventional names and id values</p>
</li>
</ul>
<p>Finally, after doing all of that, it renders the HTML tag using <code>tag("input", options)</code>.</p>
<p>A lot of the heavy lifting is done by the parent <code>Tags::Base</code> class and all of its included modules (<a target="_blank" href="https://github.com/rails/rails/blob/e88857bbb9d4e1dd64555c34541301870de4a45b/actionview/lib/action_view/helpers/tags/base.rb">source</a>: again edited and slimmed down). Here's a sneak peek (don't stress about reading and understanding all of it. The details are not too relevant)</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ActionView::Helpers::Tags::Base</span></span>
  <span class="hljs-keyword">include</span> Helpers::ActiveModelInstanceTag, Helpers::TagHelper, Helpers::FormTagHelper
  <span class="hljs-keyword">include</span> FormOptionsHelper

  <span class="hljs-keyword">attr_reader</span> <span class="hljs-symbol">:object</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">initialize</span><span class="hljs-params">(object_name, method_name, template_object, options = {})</span></span>
    @object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup
    @template_object = template_object

    @object_name.sub!(<span class="hljs-regexp">/\[\]$/</span>, <span class="hljs-string">""</span>) <span class="hljs-params">||</span> @object_name.sub!(<span class="hljs-regexp">/\[\]\]$/</span>, <span class="hljs-string">"]"</span>)
    @object = retrieve_object(options.delete(<span class="hljs-symbol">:object</span>))
    @skip_default_ids = options.delete(<span class="hljs-symbol">:skip_default_ids</span>)
    @allow_method_names_outside_object = options.delete(<span class="hljs-symbol">:allow_method_names_outside_object</span>)
    @options = options

    <span class="hljs-keyword">if</span> Regexp.last_match
      @generate_indexed_names = <span class="hljs-literal">true</span>
      @auto_index = retrieve_autoindex(Regexp.last_match.pre_match)
    <span class="hljs-keyword">else</span>
      @generate_indexed_names = <span class="hljs-literal">false</span>
      @auto_index = <span class="hljs-literal">nil</span>
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>By heavy lifting, I mostly mean taking all of the necessary measures for the text field to conform to the HTML spec and Rails’ conventions for Action View, Active Record Active Model and Action Pack.</p>
<p>I've dug deep into this for several reasons:</p>
<ol>
<li><p>I'm a long-time user and supporter of component libraries. ViewComponent and Phlex provide very interesting solutions for common problems when building views. They were born in the modern era, inspired by libraries like React or Vue which have created very interesting and useful patterns. There's nothing like cross-pollination for new ideas to emerge. And actually, Web Components fit in this bucket as well.</p>
</li>
<li><p>Using these libraries with Rails forms is very hard and up until a few months ago, there were a bunch of unsolved challenges when trying to do so. As an example, the ViewComponent authors had to <a target="_blank" href="https://github.com/ViewComponent/view_component/pull/1650">build a Compatibility module to patch</a> the <code>capture</code> method for this and other use cases.</p>
</li>
<li><p>As we saw in the previous articles, even with Rails' core constructs (FormBuilder, partials etc) it's hard to build flexible form builder methods with nice interfaces.</p>
</li>
</ol>
<h1 id="heading-describing-the-problem">Describing the problem</h1>
<p>Here's my take. Rails form helper classes like <code>Tags::TextField</code> have two different responsibilities.</p>
<ol>
<li><p>Build the attributes for an Active Record/Active Model/Action Pack compliant form input and</p>
</li>
<li><p>render that input (i.e. Output the HTML)</p>
</li>
</ol>
<p>The second one is pretty simple in most cases. Just use a <code>tag</code> method and pass the tag name, and what are the arguments: <code>tag("input", options)</code>. For some other cases, it's not that simple.</p>
<p>It's the first responsibility that's super difficult to do and it's written to work extremely closely with Rails conventions.</p>
<p>I believe it's this mix of responsibilities that makes it hard for other libraries and even Rails itself to provide a better developer experience when building new, custom form builder methods and helpers.</p>
<h1 id="heading-the-solution">The solution</h1>
<p>Split it. ✂️</p>
<p>I believe that if we <strong>split</strong> the <em>attribute-building</em> responsibility from the <em>HTML rendering</em> of tag helpers <strong>and make the <em>attribute-building</em> a public API</strong>, we can provide developers with the power of the current form builder methods without constraining the APIs exposed to the view.</p>
<h2 id="heading-a-pseudo-code-example">A pseudo-code example</h2>
<blockquote>
<p>It's really pseudo-code so look past the errors and the poor naming of things 🙏🏽</p>
</blockquote>
<p>Let's work with the <code>Tags::TextField</code> class to imagine what that future could look like. As a reminder, this is how it currently looks inside of the <code>FormBuilder</code> class</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FormBuilder</span></span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(object_name, method, options = {})</span></span>
    Tags::TextField.new(object_name, method, <span class="hljs-keyword">self</span>, options).render
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>What if instead of a single <code>text_field</code> method delegating to a single class, we had three different methods: one for rendering HTML, one for attribute building (both delegating to specialized classes) and one uses them both that’s exposed as the interface to build input fields:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FormBuilder</span></span>
  <span class="hljs-comment"># the method used when building a form in a template</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(object_name, method, options = {})</span></span>
    attributes = text_field_attributes(object_name, method, options = {})
    text_field_element(attributes)        
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field_element</span><span class="hljs-params">(attributes)</span></span>
    <span class="hljs-comment"># A new helper method and class responsible for text field renderring</span>
    Tags::TextFieldHTML.render(attributes)
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field_attributes</span><span class="hljs-params">(object_name, method, options = {})</span></span>
    <span class="hljs-comment"># A new helper method and class responsible for attribute building</span>
    AttributeBuilder::TextField.build(object_name, method, options)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>In this example, a developer using <code>form.text_field :title</code> would see no difference. But this opens up a whole world of possibilities. Let's explore some.</p>
<h2 id="heading-using-component-frameworks">Using component frameworks</h2>
<p>With something like this, component frameworks like ViewComponent or Phlex wouldn't need to reimplement all of the smarts that Rails has put in place to work with Active Record, Active Model and Action Pack. They can simply focus on the specific logic and markup the developer needs to enhance form elements for their specific use case. Here's some pseudo-code.</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FormBuilder</span></span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(object_name, method, options = {})</span></span>
    <span class="hljs-comment"># leverage the attribute-building part provided by rails</span>
    attributes = text_field_attributes(object_name, method, options = {})
    <span class="hljs-comment"># but replace the default text field renderer with a component</span>
    component = Components::SuperComplexTextField.new(
      <span class="hljs-symbol">attributes:</span> attributes,
      <span class="hljs-symbol">object:</span> <span class="hljs-keyword">self</span>.object
    )
    @template.render component
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field_attributes</span><span class="hljs-params">(object_name, method, options = {})</span></span>
    AttributeBuilder::TextField.build(object_name, method, options)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>In this example, we replace the HTML renderer from Rails' default one with a Component. How does the Component how to render an input field of type text? It can either:</p>
<ul>
<li><p>inspire itself on the default one and then extend it with any specific details or</p>
</li>
<li><p>use the class provided by Rails and add any other markup or logic needed (if the Tag class is also became a public API)</p>
</li>
</ul>
<h2 id="heading-using-partials">Using partials</h2>
<p>Remember the case we talked about in part 1 of this series where you had to come up with weird names for the builder's methods to prevent clashes? Well this approach can solve that</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FormBuilder</span> &lt; ActionView::Helpers::<span class="hljs-title">FormBuilder</span></span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(object_name, method, options = {})</span></span>
    <span class="hljs-comment"># build attributes with new builder</span>
    attributes = text_field_attributes(object_name, method, options)
    @template.render(
      <span class="hljs-string">"form_builder/text_field"</span>, 
      <span class="hljs-symbol">locals:</span> { <span class="hljs-symbol">form:</span> <span class="hljs-keyword">self</span>, 
                <span class="hljs-symbol">method:</span> method, 
                <span class="hljs-symbol">options:</span> options,
                <span class="hljs-symbol">attributes:</span> attributes,
              }
    )
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Some icon<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
  <span class="hljs-comment">&lt;!-- Render eleemtn with html helper --&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">self</span>.text_field_element(attributes) </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">self</span>.object.error_messages[method] </span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre>
<p>Now there's no issue with names and the form builder method can still be named just <code>text_field</code>.</p>
<p>If this has piqued your interest, I'll be publishing one last article that shows what it takes to make this happen. I've already forked Rails and started to understand how to tackle this work; from understanding the many different tags Rails already has, figuring out tests, to envisioning how many phases a project like this one might have.</p>
<p>Stay tuned!</p>
]]></content:encoded></item><item><title><![CDATA[Unlocking the power of forms in Rails]]></title><description><![CDATA[I've had this idea in the back of my head for a while that can potentially unlock a bunch of possibilities with Rails' Form Helpers. But to present it, I…]]></description><link>https://dev.julianpinzon.com/unlocking-the-power-of-forms-in-rails</link><guid isPermaLink="true">https://dev.julianpinzon.com/unlocking-the-power-of-forms-in-rails</guid><category><![CDATA[Ruby]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[Action view]]></category><category><![CDATA[OSS]]></category><category><![CDATA[FormBuilder]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Wed, 14 Jun 2023 01:48:48 GMT</pubDate><content:encoded><![CDATA[<p>I've had this idea in the back of my head for a while that can potentially unlock a bunch of possibilities with Rails' Form Helpers. But to present it, I want to write about what you can do with them today, the limitations and what I want as a developer.</p>
<p>I'll be releasing 3 articles in quick succession over the next few days.</p>
<ol>
<li><p>Part 1: An intro/refresher on <code>FormBuilder</code></p>
</li>
<li><p>Part 2: A deep dive into how <code>FormBuilder</code> and Tag Helper Classes build tags like <code>&lt;input&gt;</code> or <code>&lt;select&gt;</code>. Here we'll uncover what I believe is the opportunity to unlock new stuff.</p>
</li>
<li><p>Part 3: A proposal for a solution with a link to a Rails Fork that's in progress.</p>
</li>
</ol>
<h1 id="heading-youre-using-a-formbuilder-even-if-you-dont-know-what-it-is">You're using a FormBuilder even if you don't know what it is</h1>
<blockquote>
<p>Most of what I'll mention in this series and some of the examples come from the awesome Rails Guide: <a target="_blank" href="https://guides.rubyonrails.org/form_helpers.html">Action View Form Helpers</a></p>
</blockquote>
<p>I have to be honest; I haven't written a plain HTML form in many years and I don't really know how to do it from memory any more. Rails form helpers provide a beautiful developer experience while keeping us true to the fundamentals of the web. What a combo!</p>
<p>When I learnt Rails for the first time I wrote forms that looked something like this one.</p>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form_with <span class="hljs-symbol">url:</span> <span class="hljs-string">"/search"</span>, <span class="hljs-symbol">method:</span> <span class="hljs-symbol">:get</span> <span class="hljs-keyword">do</span> <span class="hljs-params">|form|</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.label <span class="hljs-symbol">:query</span>, <span class="hljs-string">"Search for:"</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:query</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.submit <span class="hljs-string">"Search"</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">%</span></span></span><span class="ruby"> <span class="hljs-keyword">end</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span></span>
</code></pre>
<p>I typed the stuff and a form popped up. However, I never really understood what <code>form</code> was, especially when working with Stack Overflow examples and older code that used just <code>f</code>. What the hell is <code>f</code>? (please, don't use <code>f</code>).</p>
<p>Well, that <code>form</code> is an instance of a class called <a target="_blank" href="https://github.com/rails/rails/blob/main/actionview/lib/action_view/helpers/form_helper.rb#L1674"><code>FormBuilder</code></a>. The documentation has a great description of this class:</p>
<blockquote>
<p>The +FormBuilder+ object can be thought of as serving as a proxy for the # methods in the +FormHelper+ module.</p>
</blockquote>
<p>In other words, an instance of <code>FormBuilder</code>, which is initialized when you call <code>form_with</code>, wraps all the different form elements you can use to build a form in nice methods like <code>label</code>, <code>text_field</code>, <code>button</code> that return plain HTML.</p>
<p>Usually, though, we don't have a plain URL to point our form to. More often than not, <code>form_with</code> is called with a model. Like an instance of a <code>@user</code> or <code>@article</code> and this is where the benefits start multiplying.</p>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form_with <span class="hljs-symbol">model:</span> @article <span class="hljs-keyword">do</span> <span class="hljs-params">|form|</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:title</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_area <span class="hljs-symbol">:body</span>, <span class="hljs-symbol">size:</span> <span class="hljs-string">"60x10"</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.submit </span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">%</span></span></span><span class="ruby"> <span class="hljs-keyword">end</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span></span>
</code></pre>
<p>The docs continue with the following:</p>
<blockquote>
<p>This class, however, allows you to # call methods with the model object you are building the form for.</p>
</blockquote>
<p>To understand this, let's zoom in on the <code>text_field</code> method in the example above. Assuming there is an <code>Article</code> model with a <code>title</code> attribute the output of <code>form.text_field :title</code> will be:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> 
       <span class="hljs-attr">name</span>=<span class="hljs-string">"article[title]"</span> 
       <span class="hljs-attr">id</span>=<span class="hljs-string">"article_title"</span> 
       <span class="hljs-attr">value</span>=<span class="hljs-string">"My Title"</span> /&gt;</span>
</code></pre>
<p>Without you having to think about it, Rails added the following attributes to the resulting HTML tag:</p>
<ul>
<li><p>name: with a convention of the model's class and then the attribute in squared brackets</p>
</li>
<li><p>id: with the model name first then the attribut ename</p>
</li>
<li><p>value</p>
</li>
</ul>
<p>These are crucial for this element's interactions with things like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#defining_an_explicit_label_with_the_for_attribute">an associated <code>label</code> tag</a>, JavaScript interactions that require a unique ID or generating a conventional and predictable <code>params</code> hash in your controller to manipulate and persist data.</p>
<p>This is <strong>the most important part of forms in Ruby on Rails.</strong> The framework has already put in place everything you need to build a form specifically catered to a model and to receive the information back from that form in a predictable way.</p>
<p>(Keep this in mind because this is going to be crucial for this whole series.)</p>
<h1 id="heading-styling-form-helpers">Styling form helpers</h1>
<h2 id="heading-directly-in-a-view-template">Directly in a view template</h2>
<p>To style form helpers you can use the <code>class</code> parameter and give it some value of a CSS class. In this case, we'll use the class <code>"input"</code></p>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field 
      <span class="hljs-symbol">:title</span>, 
      <span class="hljs-class"><span class="hljs-keyword">class</span>: "<span class="hljs-title">input</span>" </span></span><span class="xml"><span class="hljs-tag">%&gt;</span></span>
</code></pre>
<p>But what if all of your forms look the same and you always use the same class?</p>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:title</span>, <span class="hljs-class"><span class="hljs-keyword">class</span>: "<span class="hljs-title">input</span>" </span></span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:subtitle</span>, <span class="hljs-class"><span class="hljs-keyword">class</span>: "<span class="hljs-title">input</span>" </span></span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:body</span>, <span class="hljs-class"><span class="hljs-keyword">class</span>: "<span class="hljs-title">input</span>" </span></span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:footer</span>, <span class="hljs-class"><span class="hljs-keyword">class</span>: "<span class="hljs-title">input</span>" </span></span><span class="xml"><span class="hljs-tag">%&gt;</span></span>
</code></pre>
<h2 id="heading-by-using-a-form-builder">By using a Form Builder</h2>
<p>You can also go one level deeper and customize a <code>FormBuilder</code> with the styles you want. To do it though, you need to understand how a <code>FormBuilder</code> method works. Let’s take text_field as an example (<a target="_blank" href="https://github.dev/rails/rails/blob/4f70750c076715fe4a474f0295bc0d8a849ba0a7/actionview/lib/action_view/helpers/form_helper.rb#L1171">Source</a>):</p>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(object_name, method, options = {})</span></span>
  Tags::TextField.new(object_name, method, <span class="hljs-keyword">self</span>, options).render
<span class="hljs-keyword">end</span>
</code></pre>
<p>The method receives a few arguments and immediately delegates them to a new instance of a <code>Tags::TextField</code> class and then calls <code>render</code> on it. These <code>Tag</code> classes (which are nested under the <a target="_blank" href="https://github.com/rails/rails/tree/main/actionview/lib/action_view/helpers"><strong>helpers</strong> folder</a> in the Action View codebase) are kind of equivalent to what we now call a <strong>component</strong>: a class whose purpose is to render a bit of HTML.</p>
<p>Without going any deeper, we can just use our own <code>FormBuilder</code>, modify the arguments to add our <code>input</code> CSS class and call <code>super</code> so Rails keeps doing its job.</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeCustomFormBuilder</span> &lt; ActionView::Helpers::<span class="hljs-title">FormBuilder</span></span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(object_name, method, options = {})</span></span>
    options.merge!(<span class="hljs-class"><span class="hljs-keyword">class</span>: "<span class="hljs-title">input</span>")</span>
    <span class="hljs-keyword">super</span>(object_name, method, options)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>This method is fine for simple interventions like adding a few classes and it cleans up your code quite a bit. It also makes it easy to change your code in a single place and affect every form.</p>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:title</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:subtitle</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:body</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:footer</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span></span>
</code></pre>
<h1 id="heading-more-complex-form-elements">More complex form elements</h1>
<p>But form elements can become very complex. You may want to add a trailing and/or leading icon, a hint, an error message, or complex markup to create a checkbox that looks like a switch. Here are a few ways to solve that</p>
<h2 id="heading-complex-form-builder-methods">Complex form builder methods</h2>
<p><em>\</em>There's going to be a bit of pseudo-code in this section to make my point so it may contain some errors.*</p>
<p>You can create markup directly in the form builder like so:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeCustomFormBuilder</span> &lt; ActionView::Helpers::<span class="hljs-title">FormBuilder</span></span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(method, **args)</span></span>
    @template.capture <span class="hljs-keyword">do</span>
      @template.concat <span class="hljs-keyword">super</span>(attribute, args.merge(<span class="hljs-class"><span class="hljs-keyword">class</span>: '<span class="hljs-title">a</span> <span class="hljs-title">long</span> <span class="hljs-title">string</span> <span class="hljs-title">of</span> <span class="hljs-title">classes</span> <span class="hljs-title">if</span> <span class="hljs-title">you</span> <span class="hljs-title">use</span> <span class="hljs-title">tailwind</span>'))</span>
        <span class="hljs-keyword">if</span> some_var = args.fetch(<span class="hljs-symbol">:some_argument</span>, <span class="hljs-literal">nil</span>)
          @template.concat @template.content_tag(<span class="hljs-symbol">:p</span>, some_var., <span class="hljs-class"><span class="hljs-keyword">class</span>: '<span class="hljs-title">another</span> <span class="hljs-title">long</span> <span class="hljs-title">string</span> <span class="hljs-title">of</span> <span class="hljs-title">classes</span>')</span>
        <span class="hljs-keyword">end</span>
      <span class="hljs-keyword">end</span>  
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>Even though this option works, it's super complex and hard to read. First, you need to be aware that you're writing stuff to a <code>@template</code> instance variable to which you send the method <code>capture</code> to encapsulate more HTML that you then have to <code>concat</code>. This is not a nice way to write markup at all.</p>
<h2 id="heading-delegating-to-a-partial">Delegating to a partial</h2>
<p>To solve the above, you can just render a partial and create your markup there:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeCustomFormBuilder</span> &lt; ActionView::Helpers::<span class="hljs-title">FormBuilder</span></span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">text_field</span><span class="hljs-params">(method, **args)</span></span>
    @template.render(
      <span class="hljs-string">"some_custom_form_builder/text_field"</span>, 
      <span class="hljs-symbol">locals:</span> { <span class="hljs-symbol">form:</span> <span class="hljs-keyword">self</span>, <span class="hljs-symbol">method:</span> method, <span class="hljs-symbol">args:</span> args)
    )
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Some icon<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">self</span>.text_field </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">self</span>.object.error_messages[method] </span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre>
<p>But there's a problem here. I'm calling <code>self.text_field</code> in the template and that will reference the <code>text_field</code> method in the form builder which will create an infinite loop and a stack overflow error.</p>
<p>To solve it you have two options. You either create an <code>&lt;input&gt;</code> field manually and lose all of the work Rails has done to add an <code>id</code>, <code>name</code> and <code>value</code> or rename the <code>text_field</code> method in <code>SomeCustomeFormBuilder</code> by prefixing it with something else like... <code>some_custom_&lt;method_name&gt;</code> so that we can freely call <code>text_field</code>. Let's take that second option:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeCustomFormBuilder</span> &lt; ActionView::Helpers::<span class="hljs-title">FormBuilder</span></span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">some_custom_text_field</span><span class="hljs-params">(method, **args)</span></span> <span class="hljs-comment"># 👎</span>
    @template.render(
      <span class="hljs-string">"some_custom_form_builder/some_custom_text_field"</span>, 
      <span class="hljs-symbol">locals:</span> { <span class="hljs-symbol">form:</span> <span class="hljs-keyword">self</span>, <span class="hljs-symbol">method:</span> method, <span class="hljs-symbol">args:</span> args)
    )
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>It's not bad. But it isn't great either. For a framework and a language that excels at ergonomics and naming, this is not very nice. This is how you would use this in a form:</p>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form_with <span class="hljs-symbol">model:</span> @articel <span class="hljs-keyword">do</span> <span class="hljs-params">|form|</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.some_custom_text_field <span class="hljs-symbol">:article</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">%</span></span></span><span class="ruby"> <span class="hljs-keyword">end</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span></span>
</code></pre>
<h1 id="heading-what-i-want">What I want</h1>
<p>I just want to be able to call <code>form.text_field :article</code> and have it return whatever markup I want. For some people that might be just an <code>&lt;input type="text"&gt;</code> but for others that might be a full-on component with labels icons, hints, errors etc.</p>
<h1 id="heading-finding-the-problem">Finding the problem</h1>
<p>I've done some digging and I think I know what's forcing developers to do this. Now that you know all about Form Builders, in the next article we'll dive even deeper into how something as simple as a <code>TextField</code> is rendered and we'll uncover some coupling that I believe is holding form builders up.</p>
]]></content:encoded></item><item><title><![CDATA[Advanced Layout Rendering in Rails]]></title><description><![CDATA[Part 3: Making shared, data-rich layouts for subsections of your apps]]></description><link>https://dev.julianpinzon.com/advanced-layout-rendering-in-rails</link><guid isPermaLink="true">https://dev.julianpinzon.com/advanced-layout-rendering-in-rails</guid><category><![CDATA[Ruby]]></category><category><![CDATA[Rails]]></category><category><![CDATA[rubyonrails]]></category><category><![CDATA[Action view]]></category><category><![CDATA[layout]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Thu, 27 Apr 2023 05:52:57 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682314089450/36cefeaf-595d-4dec-8a35-531b0887a388.png" alt="A wireframe showing the &quot;profile&quot; page of the car. It consists of four different screens which the user navigates to using tabs. There is a common element at the top of all 4 screens: The name of the car (Mazda 5: The all rounder!), how far away it is (200 meters, 5 minute walk), its purchase date (2021) and how many kilometres it has been driven (8,500). Below this information there is a horizontal navigation with links to: information, location, features and pictures. The four wireframes show rough drawings of each of these" class="image--center mx-auto" /></p>
<p>To finish this series we'll finally tackle this part of the car-sharing app we've been creating in this Action View Layouts series.</p>
<p>To recap, in part 2 I described my process to uncover what the resources these screens show are and how these all fall under the namespace of a <code>Vehicle</code> (check out the article <a target="_blank" href="https://dev.julianpinzon.com/layout-rendering-in-rails-implicit-per-controller-layouts">here if you need a refresher</a>). This makes it easy to name and create the controllers that will handle these views:</p>
<ul>
<li><p><code>Vehicle::DetailsController</code></p>
</li>
<li><p><code>Vehicle::FeaturesController</code></p>
</li>
<li><p><code>Vehicle::PicturesController</code></p>
</li>
<li><p><code>Vehicle::LocationsController</code></p>
</li>
</ul>
<p>In this article, we'll explore how to design routes and leverage inheritance and implicit layout rendering to make this design a breeze.</p>
<h2 id="heading-designing-expressive-routes">Designing expressive routes</h2>
<p>To access these controllers we will need to add our resources to the router. I find it helpful to visualise the actual URLs first before jumping in. Here's what I imagine:</p>
<ul>
<li><p><code>vehicles/:vehicle_id/details</code></p>
</li>
<li><p><code>vehicles/:vehicle_id/features</code></p>
</li>
<li><p><code>vehicles/:vehicle_id/pictures</code></p>
</li>
<li><p><code>vehicles/:vehicle_id/location</code> 👀</p>
</li>
</ul>
<p>See anything special? All of these URLs describe plural resources except for one.</p>
<p>Even if these aren't Active Record models with backing database tables, you can still think of them as entities having relationships between them.</p>
<ul>
<li><p><em>"A vehicle has</em> <strong><em>many</em></strong> <em>details".</em> Can be translated as an <code>index</code> action for details</p>
</li>
<li><p><em>"A vehicle is enhanced with</em> <strong><em>many</em></strong> <em>features.</em> Can be translated as an <code>index</code> action for features.</p>
</li>
<li><p><em>"A vehicle is presented visually using</em> <strong><em>many</em></strong> <em>pictures".</em> Can be translated as an <code>index</code> action for pictures</p>
</li>
<li><p><em>"A vehicle is parked at</em> <strong><em>a</em></strong> <em>location".</em> Can be translated as a <code>show</code> action for its location</p>
</li>
</ul>
<h3 id="heading-resources-plural-vs-resource-singular">Resources (plural) vs Resource (singular)</h3>
<p>Rails' router allows you to declare singular or plural versions of a resource and this will take on a different meaning and create different URLs for your application. Let's take the <code>Vehicles::Location</code> controller as an example. If we were to use the plural version:</p>
<pre><code class="lang-ruby">Rails.routes.draw <span class="hljs-keyword">do</span> 
  <span class="hljs-comment"># ...</span>
  resources <span class="hljs-symbol">:vehicles</span>, <span class="hljs-symbol">only:</span> <span class="hljs-string">%w(index)</span> <span class="hljs-keyword">do</span>
    resources <span class="hljs-symbol">:locations</span>, <span class="hljs-symbol">only:</span> <span class="hljs-string">%w(show)</span> <span class="hljs-comment"># 👀 resourceS: plural</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>The output of this will be:</p>
<pre><code class="lang-plaintext">...
vehicle_location_path    
GET    /vehicles/:vehicle_id/location/:id
location#show
...
</code></pre>
<p>But what if your vehicle's location doesn't live in another model and table? What if it's just an attribute of the vehicle itself? You won't have an ID to go look for it.</p>
<p>This is what the singular <code>resource</code> method is for:</p>
<pre><code class="lang-ruby">Rails.routes.draw <span class="hljs-keyword">do</span> 
  <span class="hljs-comment"># ...</span>
  resources <span class="hljs-symbol">:vehicles</span>, <span class="hljs-symbol">only:</span> <span class="hljs-symbol">:index</span> <span class="hljs-keyword">do</span>
    resource <span class="hljs-symbol">:locations</span>, <span class="hljs-symbol">only:</span> <span class="hljs-symbol">:show</span> <span class="hljs-comment"># 👀 resource: singular!</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>Now the output is just as we described above</p>
<pre><code class="lang-plaintext">vehicle_location_path    
GET    /vehicles/:vehicle_id/location ✨ singular, with not id param
locations#show
</code></pre>
<p><a target="_blank" href="https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resource">The documentation for the <code>resource</code> method</a> explains it very well:</p>
<blockquote>
<p>Sometimes, you have a resource that clients always look up without referencing an ID. A common example, /profile always shows the profile of the currently logged in user. In this case, you can use a singular resource to map /profile (rather than /profile/:id) to the show action [...]</p>
</blockquote>
<h3 id="heading-scoping-controllers-to-modules">Scoping controllers to modules</h3>
<p>We've solved one piece but we still have a problem. Did you notice the controller names in code snippets?</p>
<pre><code class="lang-plaintext">vehicle_location_path    
GET    /vehicles/:vehicle_id/location
locations#show ⬅️ this are the controller#action names
</code></pre>
<p>The controller is just <code>locations</code> instead of <code>vehicles::locations</code>. This can be an issue if there are other "locations" in your app. Imagine the user can have multiple stored locations where they usually search cars from. Like, from home and work. Both a "vehicle's location" and "a user's usual locations" need a controller with the word "locations" in them. This is why the router provides <a target="_blank" href="https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-namespace">namespacing</a> and <a target="_blank" href="https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-namespace">scoping</a> methods.</p>
<p>The most immediate benefit of using these methods is to allow your controllers to be nested within a module and to live in a different folder:</p>
<pre><code class="lang-plaintext">app/
  controllers/
    vehicles_controller.rb
    vehicles
      locations_controller.rb
      ...
</code></pre>
<pre><code class="lang-ruby"><span class="hljs-comment"># app/controllers/vehicles/locations_controller.rb</span>
<span class="hljs-class"><span class="hljs-keyword">module</span> <span class="hljs-title">Vehicles</span></span>
  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LocationsController</span> &lt; ApplicationController</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p><code>namespace</code> and <code>scope</code> are similar but have some slight nuances that make them better for different scenarios. If we were to use <code>namespace</code> :</p>
<pre><code class="lang-ruby">Rails.application.routes.draw <span class="hljs-keyword">do</span> 
  resources <span class="hljs-symbol">:vehicles</span>, <span class="hljs-symbol">only:</span> <span class="hljs-symbol">:index</span> <span class="hljs-keyword">do</span> 
    namespace <span class="hljs-symbol">:vehicles</span> <span class="hljs-keyword">do</span> 
      resource <span class="hljs-symbol">:location</span>, <span class="hljs-symbol">only:</span> <span class="hljs-symbol">:show</span>
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>And look at the outcome:</p>
<pre><code class="lang-plaintext">vehicle_vehicles_location_path    GET    /vehicles/:vehicle_id/vehicles/location(.:format)    
vehicles/locations#show
</code></pre>
<p>You can see that we got (spoiler, it's sad):</p>
<ul>
<li><p>A URL that has the word <code>vehicles</code> two times</p>
</li>
<li><p>A path helper that also has the word <code>vehicle</code> twice.</p>
</li>
</ul>
<p>If we want to design beautiful and expressive routes, this is not the way. So let's try <code>scope</code>. This method receives several arguments but we care only about <code>module</code> today which will scope or nest our controllers under a different Ruby module:</p>
<pre><code class="lang-ruby">Rails.application.routes.draw <span class="hljs-keyword">do</span>
  resources <span class="hljs-symbol">:vehicles</span>, <span class="hljs-symbol">only:</span> <span class="hljs-symbol">:index</span> <span class="hljs-keyword">do</span>
    scope <span class="hljs-class"><span class="hljs-keyword">module</span>: :<span class="hljs-title">vehicles</span> <span class="hljs-title">do</span></span>
      resource <span class="hljs-symbol">:location</span>, <span class="hljs-symbol">only:</span> <span class="hljs-symbol">:show</span>
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<pre><code class="lang-plaintext">vehicle_location_path
GET    /vehicles/:vehicle_id/location(.:format)    
vehicles/locations#show
</code></pre>
<p>Now we got (spoiler: it's good!):</p>
<ul>
<li><p>A simple and succinct URL 🎉</p>
</li>
<li><p>A very expressive path helper 🎉</p>
</li>
<li><p>A locations controller nested under the <code>vehicles</code> namespace 🎉</p>
</li>
</ul>
<h3 id="heading-why-care-so-much">Why care so much?</h3>
<p>We've gone on and on about routes and diving deep into this. Who cares if paths are simple or if things are nested? Why is this important? Because taking the time to design these properly has unlocked all of the pieces to create the interface we set out to create.</p>
<h2 id="heading-putting-it-all-together">Putting it all together</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682318153044/6045356f-dc76-45bd-bf19-d42bfa0b2e61.png" alt="A wireframe of the details page of a vehicle. Two rectangles highlight important parts of the image. A red one at the tops highlight information that is the same across all other pages for the vehicle. The green one encompasses the area where data will change based on the page visited" class="image--center mx-auto" /></p>
<p>So how do we make it so all of the pages for the vehicle share the same information at the top (red square), but render different content at the bottom (green square)? Does this ring a bell?</p>
<p>A <code>vehicle</code> is composed of many resources such as <code>location</code> or <code>pictures</code>, it's <strong>the parent</strong> of all of these resources...</p>
<p>Its children share the same <strong>layout</strong>.</p>
<p>... see where I'm getting at here? If you've followed the series you'll probably start to see that we have seen this problem before. If there is a <strong>parent controller</strong> that can dictate how its children behave, we should create one:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">module</span> <span class="hljs-title">Vehicles</span></span>
  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainController</span> &lt; ApplicationContrller</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>Saying it out loud helps bring it home:</p>
<p><em>We've created</em> <strong><em>the main controller</em></strong> <em>for the vehicle section of our app.</em></p>
<p>Because all of its children will use the same layout, we should create one for this main controller:</p>
<pre><code class="lang-plaintext">app/
  views/
    layouts/
      application.html.erb 
      vehicles
        main.html.erb ✅
</code></pre>
<p>We now make it so all child controllers inherit from this <code>Main</code> controller:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicles::DetailsController</span> &lt; Vehicles::MainController</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span></span>
    @vehicle = Vehicle.find(params[<span class="hljs-symbol">:vehicle_id</span>])
    @details = @vehicle.details
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicles::FeaturesController</span> &lt; Vehicles::MainController</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span></span>
    @vehicle = Vehicle.find(params[<span class="hljs-symbol">:vehicle_id</span>])
    @features = @vehicle.features
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicles::ImagesController</span> &lt; Vehicles::MainController</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span></span>
    @vehicle = Vehicle.find(params[<span class="hljs-symbol">:vehicle_id</span>])
    @images = @vehicle.images
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>All of these controllers need a <code>@vehicle</code> to render the top section of our layout. And because our routes are beautifully designed and conventional, all of them share the same param <code>vehicle_id</code> which means we can pull this out to the parent controller as a callback.</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">module</span> <span class="hljs-title">Vehicles</span></span>
  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainController</span> &lt; ApplicationContrller</span>
    before_action <span class="hljs-symbol">:set_vehicle</span>

    private
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">set_vehicle</span></span>
      @vehicle = Vehicle.find(params[<span class="hljs-symbol">:vehicle_id</span>])
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<h2 id="heading-enabling-change">Enabling change</h2>
<p>But what if this design didn't work well with your users and they are getting confused about tabs? Maybe you design an experience where there aren't tabs anymore and all information is stacked in one single view.</p>
<p>Does this mean you have to go back to a single controller with a bunch of instance variables?</p>
<p>No (if you use Turbo)</p>
<p>Since we have built a strong foundation that separates every resource the vehicle has, it's a matter of removing the tabs and making a template that leverages turbo frames. Let's give it a quick go.</p>
<p>For a <code>Vehicle::Details#index</code> page that will stack all of the info in our tabs into a single, scrollable view you could do something like this:</p>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-comment">&lt;!-- app/views/vehicles/details --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Details<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> render <span class="hljs-string">"details"</span>, <span class="hljs-symbol">locals:</span> @details<span class="hljs-string">" </span></span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"><span class="hljs-string"> turbo_frame_tag "</span>location<span class="hljs-string">", 
                       src: vehicle_location_path(@vehicle),
                       loading: :lazy </span></span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"><span class="hljs-string"> turbo_frame_tag "</span>features<span class="hljs-string">", 
                      src: vehicle_features_path(@vehicle), 
                      loading: :lazy </span></span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"><span class="hljs-string"> turbo_frame_tag "</span>pictures<span class="hljs-string">", 
                      src: vehicle_pictures_path(@vehicle), 
                      loading: :lazy </span></span><span class="xml"><span class="hljs-tag">%&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span></span>
</code></pre>
<p>Notice how the frame tags now point to the controllers we had created and how we can even leverage the lazy loading feature of Turbo Frames to optimise the rendering of this view.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>To recap, we have learnt:</p>
<ul>
<li><p>How implicit rendering works in Action View in Rails</p>
</li>
<li><p>How to create layouts for specific controllers</p>
</li>
<li><p>How to create layouts that multiple controllers will share through the default lookup chain Action View goes through</p>
</li>
<li><p>How to design expressive routes that...</p>
</li>
<li><p>Allow you to use all the concepts above to create complex views</p>
</li>
</ul>
<p>Can you think of a place in your app where you could apply this? Let me know!</p>
<p>See you in the next one.</p>
<h2 id="heading-off-the-rails">Off the Rails</h2>
<p>I've been loving writing these articles and seeing the reception from you all. Thanks for liking, reposting, retweeting and sharing this.</p>
<p>If you're a subscriber to the newsletter, I'd love for you to reply to this article and let me know if you liked it and maybe tell me what you'd like to hear about next.<br />If you haven't subscribed though, click <a target="_blank" href="https://dev.julianpinzon.com/newsletter">here</a> and subscribe!</p>
]]></content:encoded></item><item><title><![CDATA[Layout rendering in Rails Part 2: Implicit, per controller layouts]]></title><description><![CDATA[Leverage Rails' conventions to clean up layouts on a per controller basis]]></description><link>https://dev.julianpinzon.com/layout-rendering-in-rails-implicit-per-controller-layouts</link><guid isPermaLink="true">https://dev.julianpinzon.com/layout-rendering-in-rails-implicit-per-controller-layouts</guid><category><![CDATA[Ruby]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[Action view]]></category><category><![CDATA[layout]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Fri, 21 Apr 2023 13:00:09 GMT</pubDate><content:encoded><![CDATA[<p>In the first part of this series, we learnt how implicit rendering works to separate authenticated vs unauthenticated sections of an app. In this second part, we will learn how to use this technique to build interfaces for specific controllers.</p>
<h2 id="heading-the-applications-default-layout">The application's default layout</h2>
<p>In the previous article, we designed a structure such that the unauthenticated pages of our app always inherited by a <code>Public::MainController</code> and we created a <code>public/main.html.erb</code> layout so that all public pages used it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681997421285/44e6ab5e-9024-458b-bcf7-b4f216a45cf6.png" alt="A wireframe of the application's layout. It has a top bar navigation with link to home, about, pricing, sign up and log in. The rest of the layout is empty and a message reads: &quot;The empty public/main.html.erb layout. Public views are rendered in here&quot;" class="image--center mx-auto" /></p>
<p>After users log in, a different layout will be selected as the default. For our case, this will be the <code>application.html.erb</code> layout that comes by default on a Rails app. This also means that at this stage all of our authenticated controllers will inherit from the <code>ApplicationController</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681997725353/5a932fe5-9ac5-4cab-b722-95a8482562de.png" alt="An image of a wireframe for the default layout of the app. It has a sidebar navigation to the left with links to dashboard, search, bookings and my account. The main content area to the right has a message that reads: &quot;The empty application.html.erb layout. Authenticated views are rendered here&quot;" class="image--center mx-auto" /></p>
<h2 id="heading-searching-cars">Searching cars</h2>
<p>The most important feature of our hypothetical car-sharing app is searching for a car and choosing it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681997842659/c94020d8-da83-4e34-becb-7b1df7c5e366.png" alt="A wireframe of the search page of the car-sharing app. It has no navigation links at the top or side of the layout. Instead it has a back button to the top left, a title to the right of the back button that reads Search, a few boxes underneath that represent filters and a content section that has a list of cars to the left and a map with pins to the right representing the search results." class="image--center mx-auto" /></p>
<p>You can notice in this wireframe that the UI for searching for a car does not have a side navigation like the main section of the app. This is intentional. Through this design, we are helping the user focus on a complex task that requires filtering, looking at a map for the closest car, sifting through different options, etc.</p>
<p>This search page can be thought of as the index of vehicles available for hire.</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">VehiclesController</span> &lt; ApplicationController</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span></span>
    <span class="hljs-comment"># ...</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>However, if we don't do anything else, the search page will be rendered inside of the application.html.erb layout.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681998084083/bd98aa4d-0989-42e8-993a-32c91c777281.png" alt="A wireframe that uses the application.html.erb layout with a left-hand side navigation but that in the content area, contains the whole complex search page with filters results the map etc." class="image--center mx-auto" /></p>
<p>This is starting to look very busy. Imagine that at some point one of the filters becomes very complex and requires a drawer or slide-over. How will you fit all of that in this layout?</p>
<h2 id="heading-using-specific-layouts-per-controller">Using specific layouts per controller</h2>
<p>In the previous article, we learnt that Action View has a conventional lookup chain that searches for the layout to render a view and that it starts by looking for a template named after the controller before falling back to the one named after the controller's parent.</p>
<p>If the inheritance chain looks like this:</p>
<p><code>VehiclesController</code> -&gt; <code>ApplicationController</code></p>
<p>This means that Action View will look first for a layout called <code>vehicles.html.erb</code>.</p>
<p>So let's create one!</p>
<pre><code class="lang-plaintext">app/
  controllers/
    application_controller.rb
✨  vehicles_controller.rb ⬅ Our new Controller
      public/
        main_controller.rb
        registrations_controller.rb
  views/
    layouts/
      application.html.erb
✨     vehicles.html.erb ⬅ 👀 A layout with matching name ✨
      public/
        main.html.erb
</code></pre>
<p>This layout won't have the left-hand side navigation. Instead, it will just have a title and a back button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681998740032/a1e34771-0e67-4d3e-ae5a-2d2c625b16d4.png" alt="A wireframe of a new layout that has a top navigation bar with just a back button and a title that reads &quot;Search&quot;. The content area is empty and has a message by the author that reads &quot;The empty vehicles.html.erb layout. Views rendered by the Vehicles Controller are rendered here&quot;" class="image--center mx-auto" /></p>
<p>So when a user visits the index action for vehicles (which serves as the search page), Action View will perform the following lookup:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td>Controller</td><td>Layout</td><td>Found?</td></tr>
</thead>
<tbody>
<tr>
<td>A specific layout for the controller</td><td><code>VehiclesController</code></td><td><code>vehicles.html.erb</code></td><td>✅</td></tr>
<tr>
<td>A layout for its parent controller</td><td><code>ApplicationController</code></td><td><code>application.html.erb</code></td><td>(it's there but it doesn't look for it because it already found one)</td></tr>
</tbody>
</table>
</div><p>The resulting view will then look like our initial wireframe:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681998911775/adab9618-5151-4a08-a509-a07ecd62c36d.png" alt="A wireframe of the search page using the specific layout for the vehicles controller. It has a top navigation with a back button and a search title and a content area with filters at the top, search results to the left and a map to the right with pins representing the location of the filtered vehicles" class="image--center mx-auto" /></p>
<p>This looks much cleaner and allows for the interface to grow and add a drawer, slide-over or any other UI element for more complex filtering in the future. But it's not just about looks though.</p>
<p>Our code is also very simple. We now have a couple of layouts dedicated to the specific needs of our app and we didn't have to write any conditional logic to do this.</p>
<p>Looking at the wireframes though, there's something even harder to do that can be solved in the same, simple way.</p>
<h2 id="heading-choosing-the-right-vehicle">Choosing the right vehicle</h2>
<p>After using our amazing search page, the user sees a good selection of vehicles nearby and wants to choose the best one for their next trip. Doing so requires evaluating the car's specific features, pictures, location, etc. So when the user clicks on one of the search results, we will present them with these screens:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1682003636668/7cc8c849-bcb2-4c58-823a-ace78289f936.png" alt="A wireframe showing the &quot;profile&quot; page of the car. It consists of four different screens which the user navigates to using tabs. There is a common element at the top of all 4 screens: The name of the car (Mazda 5: The all rounder!), how far away it is (200 meters, 5 minute walk), its purchase date (2021) and how many kilometres it has been driven (8,500). Below this information there is a horizontal navigation with links to: information, location, features and pictures. The four wireframes show rough drawings of each of these" class="image--center mx-auto" /></p>
<h3 id="heading-a-single-controller-and-view-might-not-be-enough">A single controller and view might not be enough</h3>
<p>Designs like these can be implemented in multiple ways. One way could be getting all of this information in a single controller action:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">VehicleCompleteDetailsController</span> &lt; ApplicationController</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">show</span></span>
    @vehicle = Vehicle.find(params[<span class="hljs-symbol">:id</span>])
    @general_information = @vehicle.general_information
    @coordinates = @vehicle.coordinates <span class="hljs-comment"># to render a map</span>
    @directions = @vehicle.directions <span class="hljs-comment"># writen notes on how to get there</span>
    @pictures = @vehicle.pictures
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>Presenting all of this in tabs requires us to create a tabbed interface on the front end using Javascript. Even though it's fine to do it this way, a different approach allows for simpler, atomic controller actions that have a single, concrete responsibility and are ready for extension in the future if need be.</p>
<blockquote>
<p>The data in this example doesn't seem that complex but extrapolate this example to other situations where you have had controllers with many collections of different resources that sit behind tabs. These controllers and views definitely reach a breaking point.</p>
</blockquote>
<h3 id="heading-a-better-controller-architecture">A better controller architecture</h3>
<p>When I see that wireframe, I immediately start thinking about the name of the underlying resources they represent. Those resources can be Active Record models but, most often than not, they are just made-up resources that map to a few columns of a model, an entire model or a combination of several model's data. To do this, I usually try to describe it out loud in sentence form. For this design, I came up with the following:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>For the tab...</td><td>A sentence describing its content is ...</td><td>Which becomes a new resource's name</td></tr>
</thead>
<tbody>
<tr>
<td>Info</td><td>A vehicle's information or details</td><td><code>Vehicle::Details</code></td></tr>
<tr>
<td>Location</td><td>A vehicle's location</td><td><code>Vehicle::Location</code></td></tr>
<tr>
<td>Features</td><td>A vehicle's features</td><td><code>Vehicle::Features</code></td></tr>
<tr>
<td>Pictures</td><td>A vehicle's pictures</td><td><code>Vehicle::Pictures</code></td></tr>
</tbody>
</table>
</div><p>Notice how by saying it in sentence form you can immediately tell that there are 4 different resources all belonging to the same namespace: The <code>Vehicle</code>.</p>
<h2 id="heading-on-the-next-episode">On the next episode...</h2>
<p>I know this is a bit of a cliffhanger! Sorry about that, but I want to stop here and allow the next article to be fully focused on a route design technique that is not very common but that will allow us to:</p>
<ul>
<li><p>create <strong>very expressive</strong> path helpers</p>
</li>
<li><p>design very <strong>intuitive and scalable controller structures</strong></p>
</li>
<li><p>learn a way to <strong>continue leveraging implicit layouts</strong> for views that share common information.</p>
</li>
</ul>
<p>The next article is almost ready so it'll come pretty soon. Stay tuned!</p>
<h2 id="heading-sidenote">Sidenote</h2>
<p>I haven't written the layout files here because I don't think writing a complete side navigation HTML layout document or a top nav one adds too much value to the article.<br />However, I invite you to imagine if we had a single layout, how many conditionals we would have to have written so far to achieve what we have so far?</p>
]]></content:encoded></item><item><title><![CDATA[Implicit Layout rendering in Rails]]></title><description><![CDATA[Learn how to use Rails' Action View Layouts by implicitly choosing them based on your controller's inheritance chain.]]></description><link>https://dev.julianpinzon.com/implicit-layout-rendering-in-rails</link><guid isPermaLink="true">https://dev.julianpinzon.com/implicit-layout-rendering-in-rails</guid><category><![CDATA[Ruby]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[layout]]></category><category><![CDATA[Action view]]></category><dc:creator><![CDATA[Julián Pinzón Eslava]]></dc:creator><pubDate>Sun, 16 Apr 2023 13:50:32 GMT</pubDate><content:encoded><![CDATA[<p>I love car-sharing services. It has allowed me to live car-free for the past three and a half years cutting down on maintenance, taxes, stress ... you name it. I can also book small cars for short rides, vans for moving stuff and larger, more comfortable cars for trips. It's amazing!</p>
<p>Today, we'll use a hypothetical car-share app to learn how to use Action View layouts to their fullest.</p>
<h2 id="heading-designing-a-car-sharing-service">Designing a car-sharing service</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681613148058/81ef593b-a1ce-49d7-9c62-a8c8fb5c102d.png" alt="A wireframe of a care-share app with 4 pages: a sign up page with a menu at the top with links to home, about, pricing sign up and log in, a logged in section with a menu to the right with links to a dashboard, search, bookings and my account and a content area to the right. A search page with no navigation and a lot of filters, search results and a map and finally a page for the car with several tabs for information, location, features and pictures." class="image--center mx-auto" /></p>
<p>This wireframe shows four basic screens our app will have that show different <strong>areas</strong> of our application that we will want to treat a bit differently.</p>
<h2 id="heading-conditional-spaghetti">Conditional spaghetti 🍝</h2>
<p>One way to achieve all of these different layouts is to squeeze everything into the default <code>application.html.erb</code> layout:</p>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span><span class="hljs-comment">&lt;!-- ... --&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">if</span> current_user.signed_in? </span><span class="xml"><span class="hljs-tag">%&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">if</span> current_page?(booking_rides_path) </span><span class="xml"><span class="hljs-tag">%&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">yield</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">%</span></span></span><span class="ruby"> <span class="hljs-keyword">end</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">if</span> current_page?(dashboard_path) </span><span class="xml"><span class="hljs-tag">%&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">yield</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">%</span></span></span><span class="ruby"> <span class="hljs-keyword">else</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">yield</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">%</span></span></span><span class="ruby"> <span class="hljs-keyword">end</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%</span></span></span><span class="ruby"> <span class="hljs-keyword">else</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
      <span class="hljs-comment">&lt;!-- Public nav--&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> <span class="hljs-keyword">yield</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%</span></span></span><span class="ruby"> <span class="hljs-keyword">end</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre>
<p>Some pages require the user to log in, some don't. Some require their own specific set of rules and others share some visual aspects with others.</p>
<p>As you can probably tell, this will be hard to understand, extend and maintain. The issue with using a single layout is not just a matter of the ease of readability though. You could fix readability by turning most of this logic into several partials and call it a day. However this is a signal, and one you can train yourself to identify.</p>
<h2 id="heading-identifying-the-problem">Identifying the problem</h2>
<p>All of those conditionals are telling you something: There are several concepts here that are claiming their own space. It's an architectural problem! To allow our app to grow and have the flexibility to use different layouts we need to give it proper foundations for it to scale.</p>
<p>As I see this wireframe I'm thinking:</p>
<ul>
<li><p>The app has public-facing, non-authenticated pages and other private, authenticated ones</p>
</li>
<li><p>Within the authenticated pages:</p>
<ul>
<li><p>There's a design that houses links to most sections of the app like the dashboard, bookings and my account</p>
</li>
<li><p>There is a special case when searching where all navigation disappears and the user is fully focused on the search and car-choosing experience.</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-how-does-rails-find-a-layout">How does Rails find a layout</h2>
<blockquote>
<p>Before diving into this, remember that Rails Guides are probably the best and probably most underutilised resource to learn about the framework. Most of what I'll tell you about here you can find in the <a target="_blank" href="https://guides.rubyonrails.org/layouts_and_rendering.html#finding-layouts">Layouts and Rendering in Rails</a> guide.</p>
</blockquote>
<p>As with most things Rails, the act of finding a <strong>layout</strong> that will wrap a <strong>template/view</strong> rendered by a <strong>controller action</strong> is based on conventions. In a fresh Rails app there is a single layout: <code>app/views/layouts/application.html.erb</code>. This is <strong>the last fallback</strong> the framework will use to display a template. Because in a new app there aren't other layouts Rails uses this one.</p>
<p>You can make your controllers render a different layout by doing so <strong>explicitly or implicitly.</strong></p>
<p>If you haven't thought much about it and just use the <code>application.html.erb</code> layout then you are already using <strong>implicit rendering</strong> which relies on inheritance (more on this later).</p>
<p>On the other hand, you can tell Rails when to use a specific layout by:</p>
<ul>
<li><p><a target="_blank" href="https://guides.rubyonrails.org/layouts_and_rendering.html#specifying-layouts-for-controllers">specifying it in a controller</a></p>
</li>
<li><p><a target="_blank" href="https://guides.rubyonrails.org/layouts_and_rendering.html#choosing-layouts-at-runtime">Choosing it at runtime</a></p>
</li>
<li><p>Giving it as an argument to the <code>render</code> method</p>
</li>
</ul>
<p>I use all of these in different situations but today we will focus on <strong>implicit layout rendering leveraging</strong> <strong>inheritance</strong> because this will help you not only organise your views but also give you the tools to build a better architectural foundation for your app.</p>
<h3 id="heading-authenticated-or-not-authenticated">Authenticated or not authenticated</h3>
<p>Let's focus on the first thing we identified. The app's needs are strikingly different for the authenticated and non-authenticated sections of it. It's almost as if they were two different apps and it is usually very obvious when looking at the design.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681615508998/8895773b-acfb-446c-85a1-4047aef7952a.png" alt="Left: wireframe of the sign up page with a top navigation and a sign up form. The top links read home, about, pricing, sign up and log in. Right: wireframe of the app after the user has logged in with a left-hand side navigation with links to a dashboard, search, bookings and my account and a right-hand content area." class="image--center mx-auto" /></p>
<h3 id="heading-beyond-the-applicationcontroller">Beyond the <code>ApplicationController</code></h3>
<p>The typical <code>ApplicationController</code> looks something like this:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># app/controllers/application_controller.rb</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApplicationController</span> &lt; ActionController::Base</span>
  before_action <span class="hljs-symbol">:authenticate_user!</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>Before every controller action, you perform some type of user authentication. But, there is a portion of your app that is not authenticated and there are multiple pages that fit in that space like sign up, sign in, password recovery etc. For all of these pages, you would need to call <code>skip_before_action :authenticate_user!</code>. That's very cumbersome and also error-prone. So instead of skipping this action on every controller, why not create a specific controller that all public pages will use?</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># app/controllers/public/application_controller.rb</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Public::MainController</span> &lt; ApplicationController</span>
  skip_before_action <span class="hljs-symbol">:authenticate_user!</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>I chose the name <code>Main</code> in this article to make it obvious that it's different from <code>Application</code> but you can name it whatever you want like:</p>
<ul>
<li><p><code>Public::MainController</code></p>
</li>
<li><p><code>Public::ApplicationController</code></p>
</li>
<li><p><code>Public::BaseController</code></p>
</li>
</ul>
<p>Now every controller that is part of the <strong>public</strong> portion of your application and needs to skip authentication will be able to use this as its parent controller:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Public::RegistrationsController</span> &lt; Public::MainController</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">new</span></span>
        <span class="hljs-comment"># renders the sign up page</span>
    <span class="hljs-keyword">end</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create</span></span>
        <span class="hljs-comment"># ...</span>
    <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>At this stage, we still have a single <code>application.html.erb</code> layout. Whenever we visit our new registrations controller it will use that one because remember that this is the ultimate fallback that Rails uses if no other options are provided.</p>
<h3 id="heading-implicit-layouts">Implicit Layouts</h3>
<p>The benefit of this technique is that now we can rely on Rails' conventions to have a new, specific layout for your public controllers. We can create a <code>main.html.erb</code> layout under <code>app/views/layouts/public</code>. Notice the name: <code>main.html.erb</code>. It takes after the name of the controller which explains why in a fresh Rails app the default layout is named <code>application.html.erb.</code></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Controller</td><td>Layout</td></tr>
</thead>
<tbody>
<tr>
<td><code>ApplicationController</code></td><td><code>application.html.erb</code></td></tr>
<tr>
<td><code>Public::MainController</code></td><td><code>public/main.html.erb</code></td></tr>
</tbody>
</table>
</div><pre><code class="lang-plaintext">app/
  controllers/
    application_controller.rb
      public/
✨      main_controller.rb ⬅ Our new Controller
        registrations_controller.rb
  views/
    layouts/
      application.html.erb
      public/
✨      main.html.erb ⬅ 👀 A layout with matching name ✨
</code></pre>
<p>Rails chooses the layout to render a view in a cascading way based on the controller's inheritance chain. For the <code>Public::RegistrationsController</code> its chain looks like:</p>
<ul>
<li><p><code>Public::RegistrationsController</code> that inherits from</p>
</li>
<li><p><code>Public::MainController</code> that inherits from</p>
</li>
<li><p><code>ApplicationController</code></p>
</li>
</ul>
<p>So when rendering the <code>Public::RegistrationsController#new</code> action, Rails will perform the following lookup:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td>Controller</td><td>Layout</td><td>Found?</td></tr>
</thead>
<tbody>
<tr>
<td>A specific layout for the controller</td><td><code>Public::RegistrationsController</code></td><td><code>public/registrations.html.erb</code></td><td>❌</td></tr>
<tr>
<td>A layout for its parent controller</td><td><code>Public::MainController</code></td><td><code>public/main.html.erb</code></td><td>✅</td></tr>
<tr>
<td>A layout for its grandparent controller</td><td><code>ApplicationController</code></td><td><code>application.html.erb</code></td><td>(it's there but it doesn't look for it because it already found one)</td></tr>
</tbody>
</table>
</div><h2 id="heading-git-commit">Git commit</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681615508998/8895773b-acfb-446c-85a1-4047aef7952a.png" alt="Left: wireframe of the sign up page with a top navigation and a sign up form. The top links read home, about, pricing, sign up and log in. Right: wireframe of the app after the user has logged in with a left-hand side navigation with links to a dashboard, search, bookings and my account and a right-hand content area." class="image--center mx-auto" /></p>
<p>This feels like a good place to commit. Through the wireframes and the spaghetti <code>application.html.erb</code> we saw earlier, we uncovered an important architectural pillar of our app: authenticated and non-authenticated pages have different needs and through different controllers and layouts we can convey those needs and give each an organised place to grow.</p>
<h2 id="heading-on-the-next-episode">On the next episode...</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681620169798/5bf461ca-4723-40fa-9ce0-aac055b6a04c.png" alt="A wireframe showing 3 screens of the authenticated portion of the app. The main navigation layout with links to the dashboard, search and booking pages, one of the search experience with search filters, results and a map and a third one, showing a specific car a user chose to view." class="image--center mx-auto" /></p>
<p>In the next article, we'll tackle the next piece of our puzzle: organising the authenticated portion of our app.</p>
<p>Stay tuned and let me know what you think!</p>
<hr />
<h2 id="heading-off-the-rails">Off the Rails</h2>
<p>This is the first article I posted after <a target="_blank" href="https://twitter.com/pinzonjulian/status/1645767023182643205?s=20">announcing on Twitter</a> that I would start creating content to give back to the community and the response was amazing! Over one hundred people subscribed to my newsletter in the first couple of days. Thanks to everyone who subscribed, liked and retweeted!</p>
<p>Also, the car-sharing theme is part of this whole idea of designing beautiful cities and it's a topic a really enjoy. If you do too, take a look at this video from Not Just Bikes on car-sharing. This channel is AMAZING!</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=OObwqreAJ48&amp;t=605s">https://www.youtube.com/watch?v=OObwqreAJ48&amp;t=605s</a></div>
]]></content:encoded></item></channel></rss>