<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jonathan Loos on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Loos on Medium]]></description>
        <link>https://medium.com/@jonathanloos97?source=rss-9ed3333eda24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iTHU9II-8slU6WXHWU_iuA.png</url>
            <title>Stories by Jonathan Loos on Medium</title>
            <link>https://medium.com/@jonathanloos97?source=rss-9ed3333eda24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 04:13:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jonathanloos97/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[@hotwired/turbo: How we upgraded our entire Ruby on Rails monolith in one month]]></title>
            <link>https://jonathanloos97.medium.com/hotwired-turbo-how-we-upgraded-our-entire-ruby-on-rails-monolith-in-one-month-25d110871039?source=rss-9ed3333eda24------2</link>
            <guid isPermaLink="false">https://medium.com/p/25d110871039</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[hotwire-rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Jonathan Loos]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 04:00:22 GMT</pubDate>
            <atom:updated>2023-04-14T12:25:54.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>Over the last 7 months, <a href="https://harled.ca/team">we</a> have completed several large-scale upgrades to our <a href="https://harled.ca/blog/our_majestic_monolith_part_one">Rails Monolith</a> in hopes of keeping our platform modern and ready for the next big move. The most daunting of which is undoubtedly the migration from <a href="https://github.com/turbolinks/turbolinks">Turbolinks</a> and <a href="https://guides.rubyonrails.org/working_with_javascript_in_rails.html#replacements-for-rails-ujs-functionality">@rails/ujs</a> to <a href="https://github.com/hotwired/turbo">@hotwired/turbo</a> after we moved to Rails 7. Over the course of one month we overhauled nearly every corner of the UI &amp; refactored most of our controller responses to accomplish the migration.</p><p>Please make sure to read through what these packages have to offer before continuing in the article as we’ll be focusing primarily on the upgrading process.</p><h3>Strategy</h3><p>We started by grouping work in buckets of difficulty. After reading through the <a href="https://turbo.hotwired.dev/handbook/introduction">turbo documentation</a> we found the following strategy would work well for us:</p><ul><li>Refactor the method: :delete to turbo_method: :delete for link_to tags.</li><li>Order all .js.erb (UJS) files by length to assess difficulty. With more lines came more reactivity and thus more complexity and refactoring needed. Those working on smaller files should be moving quickly through the list, with the higher complexity files taking longer to complete.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*SMvqAekOjQPG78kj" /></figure><ul><li>We then chose to refactor all occurrences of remote: true into turbo frames because we wanted to start working with forms. (P.s we really found the form replacement lifecycle to be a great place to start learning about turbo!)</li><li>Approach the rest of the files from short to long in small teams until the files remaining hits zero. For reference, we had to replace 177 .js.erb files during our upgrade 🙃.</li></ul><h3>Our approach to view components</h3><p>For years we have been loosely adopting Joel Hawksley’s <a href="https://viewcomponent.org/">View Components</a> into our app in hopes to eventually remove most of our partials! Although we still have a long way to go, during our migration to turbo we finally refactored hundreds of our partials into view components. To learn more of the benefits we see with moving to components <a href="https://jonathanloos97.medium.com/githubs-view-components-2ddbc3e532b1">read here</a>.</p><h3>Main fallout after migrating</h3><h4>Same route being hit by multiple unknown sources</h4><p>The simplest endpoint is one that has a single response as outlined in <a href="https://turbo.hotwired.dev/handbook/frames">Turbo’s handbook</a>. For example, consider an app with a users table.</p><p>User form component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*wbgZMbrHP3d46ZiG" /></figure><p>Controller “update” action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*kI4tsdPp6XxLKWD6" /></figure><p>HTML response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*q8Z2menNU1oxkMiu" /></figure><p>This is a very simple lifecycle of a turbo-frame which is rendered inside a view component. But what if there was somewhere else in our app calling the same endpoint but requires a different response? One way we implemented this over the years (pre-turbo) is to do the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HM3u-NLBxbQOs9GT" /></figure><p><strong>Challenge</strong></p><p>One of the main issues which we introduced gradually over the years was complex controller return methods (opposing the recommended <a href="https://rails.rubystyle.guide/#skinny-controllers">skinny controller</a>). Some of our controller methods housed multiple responses conditionally rendered based on large amounts of business logic. This was an obvious growing pain of our platform, and we were excited / terrified at the opportunity to detangle them! We determined there were a couple approaches to the issue:</p><ol><li>Leave the refactoring of the controller to another time and rebuild the response partials with turbo-frames as-is.</li><li>Clean up the controller method to have one response turbo_stream and have the conditional logic in the partial.</li><li>Break up the controller method for each response with a dedicated endpoint for each.</li></ol><p>We chose to pursue the third option. While it introduces a bit more risk to refactor our app that heavily, we determined the benefit of simplifying our controller interface was worth time. The resulting controller from the previous example would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qbtLDtM5kfm9jRUv" /></figure><h4>Error handling</h4><p>We ran into multiple instances where error cases were handled incorrectly as a result of the move which left users confused as to whether their changes were persisted or not. The main items we identified were:</p><ul><li>Forms not properly displaying the error messages. For example, if an endpoint didn’t properly handle a failed update and defaulted to rendering the read-only component instead of responding with the form &amp; errors.</li><li>Toast messages not set on redirects.</li><li>For async queries triggered through stimulus controllers: Uncaught errors leading to console error logs.</li></ul><h4>Missing form fields/attributes lost during move to component</h4><p>As I mentioned a large part of our upgrade was also moving a lot of our views into view components. We had a lot of success with this, but we did have one big issue: human error. We were our own worst enemies and missed some fields/UI components during the move to components. This is mostly a friendly reminder to take your time while you’re refactoring your code, it’s easy to miss something! Also note that we have very little end-to-end tests, so we had to do most of the validation manually.</p><p>This brings up a good point, due to the lack of end-to-end testing we had to make an elaborate manual tracker to ensure we covered the entirety of the application before the final merge. Whatever stage your testing strategy is at, it’s always prudent to consider and establish a testing strategy prior to beginning implementation. In our case it was manual acceptance testing, how are you planning on doing it?</p><h3>Upgrading to 7.3.0</h3><p>This is mostly an announcement for anyone who is running @hotwired/turbo &lt; 7.3.0 and looking to update the minor version. There are a couple intricacies you should be aware of which are outlined in <a href="https://github.com/hotwired/turbo/pull/863#issuecomment-1490066773">this github thread</a>. This upgrade rendered most of our application unusable without the incorporation of a temporary patch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25d110871039" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Use Authorization as a UX Tool]]></title>
            <link>https://jonathanloos97.medium.com/how-we-use-authorization-as-a-ux-tool-4476c2270e7a?source=rss-9ed3333eda24------2</link>
            <guid isPermaLink="false">https://medium.com/p/4476c2270e7a</guid>
            <category><![CDATA[ui-ux-design]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <dc:creator><![CDATA[Jonathan Loos]]></dc:creator>
            <pubDate>Tue, 02 Aug 2022 02:44:04 GMT</pubDate>
            <atom:updated>2022-08-09T03:23:27.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gzf2_YBa2YtZWXfNwQpkRg.jpeg" /></figure><h3>Introduction</h3><p>At some point in every application’s lifecycle you’ll come across the task of implementing an authorization framework. Choosing a framework is a hard enough task on its own, and there are great resources out there to help guide your choice. In this article we are going to focus on reimagining an authorization framework for developers as a UX tool for product teams.</p><p>We at<a href="https://harled.ca/"> Harled</a> have used <a href="https://github.com/varvet/pundit">Pundit</a> and <a href="https://rubyonrails.org/">Ruby on Rails</a> for several initiatives which required complex authorization rules across our varied user base and we’ll base the rest of this article on those technologies. Pundit has enabled us to reach our security goal of authorization with explicit policies and scopes on our data with minimal setup and intuitive layout. However, focusing on the security aspect of the framework exposed some areas where <a href="https://uxdesign.cc/when-great-product-teams-ship-broken-ux-4-steps-to-mind-the-gap-bfdf6f150f8b">user journeys</a> and authorization dead ends collide.</p><h3>Broken User Journeys In Authorization Frameworks</h3><h4>How They Happen</h4><p>As our app scaled, so did our functionality, and by proxy — the number and complexity of our policies. The mismatch typically happens during the introduction of a new authorization rule that lacks consideration of UI elements which rely on it.</p><p>To illustrate, consider the example of the initial introduction of an authorization framework into a new application. You have a page with a list of users and each list element has show, edit and delete links (shoutout to the old reliable <a href="https://guides.rubyonrails.org/v3.2/getting_started.html#listing-all-posts">rails scaffold</a>). You then receive a request to only show users other users of the same organization. You find your framework, then protect the user /show route with a policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gRPtWnjcQfdVHj3I" /></figure><p>Now if a user tries to access the profile of a user outside of their organization via direct link they will be redirected to the homepage. Done right? Well, not quite. This is where the UX piece comes into play. However, bookmarks aren’t a great way for users to access pages in your application. Users need links, lists and redirects for navigation. We’re missing a piece here to let the user know they can’t access the show page.</p><h3>Fixing Broken Journeys</h3><p>Let’s take a look at some strategies to help avoid dead-ends in your user journeys.</p><h4>Using Policies In The UI</h4><p>You most likely identified that we missed the step of wrapping the /show link in the .show? policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R9ze7bEcLE6O0BWz" /></figure><p>This is a very useful method, but it does come with its drawbacks. We’ll talk about strategies and best practices when building the UI elements later in the article. For now, there’s a large question to be asked which leads to our next point:</p><blockquote>What if the policy method contains logic which queries the database or puts load on your application?</blockquote><p>In this scenario, we’ll run those queries on each iteration of the row resulting in increased load on your application. How do we get around it? Either reduce the logic in the policy check or switch to a <strong>policy scope</strong>.</p><h4>Switching To A Policy Scope</h4><p>Policies also expose conditional scoping for queries to keep data relevant to the user accessing it. Typically this is used when listing large amounts of data such as the above example to keep it to one query, instead of <em>n</em> queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*364I-TH5RlR8wq3U" /></figure><h3>Tracking</h3><p>When a user identified a broken flow, we would address it almost immediately given the original size of our application. This was manageable for a while, but became unmaintainable with scale. We realized we needed a more robust way of tracking and prioritizing each flow, along with a confident, clear way to communicate them to our product team.</p><p>We started by hooking into Pundit’s framework and raising exceptions to the database whenever a user encountered a broken flow. To accomplish this, we leveraged a combination of the <a href="https://github.com/smartinez87/exception_notification">exception_notification</a> gem and a custom setup for saving relevant state. We call these records: <strong>Pundit Exceptions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I-cHfScl8GfqpQwj" /></figure><p>The state saved in the exception is primarily comprised of</p><ul><li>Time of day</li><li>Basic user Information</li><li>Request</li><li>Controller &amp; Action</li><li>Query Parameters</li></ul><p>I would like to take a moment to stress the importance of the query parameters. We have found many times that the query parameters play a key role in conducting a proper root cause analysis of why the flow is broken. They help determine the state of the application when the user hits the dead end. For example, the following routes look identical without the parameters included. However, with the parameters present we can identify that the user was conducting a search.</p><h3>Reporting</h3><p>When reporting on pundit exceptions we focus on one key metric: <strong>frequency</strong>.</p><p>A sudden increase in frequency helps to identify when a <a href="https://cloud.google.com/blog/products/devops-sre/using-the-four-keys-to-measure-your-devops-performance#:~:text=median%20lead%20time.-,Change%20Failure%20Rate,-%60The%20percentage%20of">change failure</a> was introduced. It’s a good idea to implement a post-deployment check which ensures there are no spikes in Pundit Exceptions following a change. But what if you’ve built a backlog of broken flows? The frequency of incoming Pundit Exceptions can help serve as an indicator of severity when prioritizing exceptions to tackle first. The more frequently the exception occurs, the more your users are trying to access the functionality, and the more they are getting frustrated!</p><h4>Building A Dashboard</h4><p>There’s an obstacle to overcome surrounding the communication of these exceptions to a non-technical team. We needed to find a way to enable (in our case) our product teams to identify and prioritize exceptions independently. To accomplish it, we built a dashboard to visualize the frequency of the exceptions in components. Below is a graph showing the number of Pundit Exceptions by controller action per day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hxgIROaHM-UHpHGB" /></figure><p>We complement this with a table showing the top 10 exceptions in terms of occurrences and a quick view of the number of users affected in the last 24 hours (see below). The “Users affected in last 24 hours” metric is great for assessing the breadth of an issue. For example, a low number represents a potentially niche area of your application that doesn’t get much traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*3ncteR5V8sUJOjfN" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*Vhy2QNm1XlppTatC" /></figure><h4>Adding Context To The Dashboard With Ahoy</h4><p><a href="https://github.com/ankane/ahoy">Ahoy</a> is an analytics tool for ruby applications. We love it, and would strongly recommend it to anyone looking for an event analytics tool. One way we use ahoy is to augment a Pundit exception with a user journey for debugging. Even just the page before the exception hit will help with reproducibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I565s1d3-rTVlZIT" /></figure><p>The cool thing here is it opens up the possibility for grouping problematic flows. From the above example we can see the user accessed the `users/:id/edit` route from the search. Remember how we talked about keeping query parameters in mind above? This is another great way to debug! In addition to debugging, it helps display the data in a way such that your product team can easily make educated decisions on redesigns or priority.</p><h3>How to Avoid Breaking Flows During Development</h3><p>We can all lean on 100% end-to-end test coverage to make sure there is never a pundit exception pushed again right? Wouldn’t that be nice… Well unfortunately we didn’t have that luxury, and quite frankly not many teams do! To avoid them, we had to follow a few simple rules when making authorization changes and building out our UI:</p><ul><li>Make sure links and buttons are wrapped in their corresponding policy methods.</li><li>Encapsulate all logic in the policy. Combining a policy check with additional logic in the view (which is an anti-pattern in itself) is likely to lead to a broken flow. Think of the following, and how the button may be visible while the navigation will still fail.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dCR0mgpHnUkTey8I" /></figure><ul><li>Align your policy scopes with their corresponding show methods. Instead of calling <em>.show?</em> on each record, use the policy scope to filter results to those the user is permitted to see. The trick here is to make sure your policy scope won’t include a record that will cause the <em>show?</em> method to fail.</li></ul><h3>Conclusion</h3><p>Pundit is a great authorization tool, but if handled incorrectly it can cause headaches down the road. We talked a lot about identifying, tracking and reporting in this article but if there’s one main takeaway it’s that you always want your recurring Pundit Exceptions to be at zero. These dashboards can fit nicely in a post-deployment analysis or a housekeeping exercise if there are a lot of exceptions to fix. Figure out what makes the most sense for your application, and stay tuned for an open source project to help you accomplish everything in this article from <a href="https://github.com/harled">Harled</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4476c2270e7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Bot Basics]]></title>
            <link>https://jonathanloos97.medium.com/factory-bot-basics-7d1a405051e8?source=rss-9ed3333eda24------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d1a405051e8</guid>
            <category><![CDATA[factorybot]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Jonathan Loos]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 16:54:02 GMT</pubDate>
            <atom:updated>2022-03-18T16:54:02.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using traits and nested factories to build more complex models</h3><p>You can use nested factories to provide convenient helper methods to build model states from the factory. For example, the code below combines changes to the type and approval_status columns and can be accessed like:</p><pre>post = build(:post, :published_and_approved)</pre><p>With the factory Below:</p><pre>factory :post do<br>  approval_status :not_started</pre><pre>  trait :published do<br>    state { :published }<br>  end</pre><pre>  trait :approved do<br>    approval_status { :approved }<br>  end</pre><pre>  factory :published_and_approved, traits: [:approved, :published]<br>end</pre><h3>Linking Models Together</h3><p>Creating linked objects in factory bot is pretty easy as well.</p><p><a href="https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#has_many-associations">https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#has_many-associations</a></p><pre>factory :user do<br>  car # Has One</pre><pre>  factory :user_with_posts do<br>    transient do<br>      posts_count { 5 }<br>    end</pre><pre>    posts do<br>      Array.new(posts_count) { association(:post) } # Has Many<br>    end<br>  end<br>end</pre><h3>Transient Values</h3><p>Transient values live only on the factory and can help mock some complex business logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d1a405051e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub’s View Components]]></title>
            <link>https://jonathanloos97.medium.com/githubs-view-components-2ddbc3e532b1?source=rss-9ed3333eda24------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ddbc3e532b1</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[viewcomponents]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Jonathan Loos]]></dc:creator>
            <pubDate>Wed, 16 Dec 2020 17:59:45 GMT</pubDate>
            <atom:updated>2020-12-21T15:58:49.470Z</atom:updated>
            <content:encoded><![CDATA[<h3>What are View Components</h3><p>View components are Github’s stab at a more modern front end framework solution built specifically for rails. It focuses on code encapsulation to build reusable and testable UI components called View Components. They’re based off of the Presenter Pattern, which addresses bloated views and controllers by <em>“creating a class representation of the state of the view”</em>. What’s nice about VC’s is that they allow for logic that would typically live in the controller or view to live within them. Github describes these as ruby objects that output HTML, so when thinking of rendering a VC, think of it as instantiating an instance of that Component Class and accessing its methods. An important note to remember here is that a large portion of what will be covered here can also be accomplished using rails partials. The main benefit is that you can abstract away the large majority of a view’s logic into a class, reducing clutter in your .erb files.</p><h3>Why use View Components?</h3><p><strong>Encapsulation</strong></p><p>View Components provide encapsulated packages for everything your view needs, separating it from your controller and its logic. In other words, parameters are passed into View Components, but will not bleed in automatically from those set in the controller. This provides a clear source for the information, and removes the guesswork that comes with figuring out what is set where. Not to mention testing this way becomes MUCH nicer.</p><p><strong>Explicit Initializer</strong></p><p>View components implement a standard Ruby initializer that gives a more explicit requirement on what is needed to render. In other words, think of if I were to show you a file for a partial requiring 6 different variables. You can imagine how it can take some time to identify them all. View Components (at their base level) feature a .rb class file and a .html.erb template file. The class file defines the Ruby initializer with all parameters required for it to render, making it much easier to identify what parameters need to be passed in.</p><p><strong>Speed</strong></p><p>Github also points out that their View Components are ~10x faster than partials according to their benchmarks. This is particularly the case when in your production environments as Rails caches classes (or in other words VCs) rather than compiling the every use. The trick here is that class caching is disabled by default in development, but enabled in prod →</p><p><a href="https://github.com/github/view_component/issues/345">View component is significantly slower than partials · Issue #345 · github/view_component</a></p><h3>When To Use View Components</h3><p>One of the main reasons why you’d create a view component is to be able to reuse it. An easy example is a card where with libraries such as Bootstrap it’s pretty simple to reuse the same classes to achieve the same look for each one across your site. The complication arises when there’s custom logic, such as permissions and javascript that apply to these cards. VCs help here by encapsulating the logic in the class definition, and packaging asset files along with it. So in this scenario, we would create a card component that would take in a theme and some text. The class file can handle custom rendering, routing and more to alleviate the view. For example, this: view.html.erb</p><pre>&lt;div class=&quot;card&quot;&gt;<br>   &lt;div class=&quot;card-body&quot;&gt; <br>      &lt;% if user_can_do_this %&gt; <br>         &lt;h5 class=&quot;card-title&quot;&gt;Show this text!&lt;/h5&gt; <br>      &lt;% elsif user_can_do_that %&gt; <br>         &lt;h5 class=&quot;card-title&quot;&gt;Show that text!&lt;/h5&gt; <br>      &lt;% end %&gt; <br>   &lt;/div&gt; <br>&lt;/div&gt;</pre><p>And you can imagine that you would still have to put this logic in a card partial or render the partial within each if-block which still keeps too much logic in the view. With VCs, this can be changed to:</p><pre>class CardComponent &lt; ViewComponent::Base <br>   def initialize(:user) <br>      if user.can_do_this <br>         @title = &quot;Show this text!&quot; <br>      elsif user.can_do_that <br>         @title = &quot;Show that text!&quot; <br>      end <br>   end <br>end</pre><p>Now, anytime you need to render that card just pass in the user and forget the rest. You can also imagine how much easier it is to test the CardComponent class and view separately, than it would be to test it all mushed together.</p><h3>Layout</h3><p><strong><em>Collections</em></strong></p><p>View Components have built in functionality to mimic Rails’ built in &lt;%= render @users %&gt; method which would go and render _user.html.erb for each user. So rather than throwing your card into a loop and iterating, you can extend the instantiation with &lt;%= render (CardComponent.with_collection(@users)) %&gt; . The cool thing here is our above code wouldn&#39;t have to change. VCs takes in one user at a time and renders it, so there&#39;s no need to handle the collection directly.</p><p><strong><em>Content Areas</em></strong></p><p>View Components take in parameters which helps with the simple case above, but what if it’s not just text we want to display within the tag? You can pass in parameters of any type to the initialize function, but what about entire HTML blocks? VCs allow for the definition of content areas or slots (experimental → <a href="https://viewcomponent.org/#slots-experimental">https://viewcomponent.org/#slots-experimental</a>) to help you layout components with more content. With our card example, we could define body and footer areas to support custom content.</p><pre>&lt;%= render(CardComponent.new(user: user) do |component| %&gt; <br>   &lt;% component.with(:body) do %&gt; <br>      &lt;p&gt;My custom body.&lt;/p&gt; <br>   &lt;% end %&gt; <br>   &lt;% component.with(:footer) do %&gt; <br>      &lt;p&gt;My custom footer.&lt;/p&gt; <br>   &lt;% end %&gt; <br>&lt;% end %&gt;</pre><pre>class CardComponent &lt; ViewComponent::Base <br>   with_content_areas :body, :footer <br>   def initialize(:user) <br>      if user.can_do_this <br>         @title = &quot;Show this text!&quot; <br>      elsif user.can_do_that <br>         @title = &quot;Show that text!&quot; <br>      end <br>   end <br>end </pre><p><em>Originally published at </em><a href="https://www.notion.so/View-Components-2f57151a2a464bc68431108d60b3a454"><em>https://www.notion.so</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ddbc3e532b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails Action Cable — A Simpler Perspective]]></title>
            <link>https://jonathanloos97.medium.com/rails-action-cable-a-simpler-perspective-9180193927f2?source=rss-9ed3333eda24------2</link>
            <guid isPermaLink="false">https://medium.com/p/9180193927f2</guid>
            <category><![CDATA[actioncable]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Jonathan Loos]]></dc:creator>
            <pubDate>Sat, 28 Nov 2020 17:42:39 GMT</pubDate>
            <atom:updated>2020-12-21T15:50:38.281Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rails Action Cable — A Simpler Perspective</h3><p>I’m an aspiring Software Engineer who, admittedly, joined the game a little late during my university career. As (I’m sure) many can relate, learning what some of these complex systems are and how they work involves lots of documents, time and confusion. I went through this, and to hopefully save some of you some time I consolidated my learnings.</p><p><strong>Disclaimer:</strong> I have to credit Christopher Sexton’s presentation on the topic available here: <a href="https://www.youtube.com/watch?v=XeqLONJsHkY">https://www.youtube.com/watch?v=XeqLONJsHkY</a>. I would strongly recommend giving this video a watch!</p><h3>What is Rails Action Cable?</h3><p>Rails Action Cable is a rails solution to performing background tasks using a Redis Server. For example, think of a typical synchronous application as a restaurant with a single employee acting as both the waiter and the chef. To ensure the food doesn’t burn, the employee must get the order, prepare it, then return it to the customer before he/she can move on to the next table. Customers are left waiting at their table for their food to “load”, but what if after they order they realize they need a glass of water? What should be a simple task now has to wait for the longer task to complete before it can be performed.</p><p>Introducing Action Cable to an application would be similar to adding a new employee to this restaurant who’s job is solely to be the cook in this scenario. The waiter should not be blocked from taking new orders and checking in on customers when the food is being prepared! Now the waiter (main application) can get the order to the cook (Action Cable Server) and forget about it until it’s finished.</p><h3>Why use it?</h3><p>First off, Action Cable has server to client push, which would be similar to the cook having a bell to ring when the food is ready, rather than having the waiter ask every 5 minutes if it’s ready. Now the entirety of the waiter’s attention can be spent on pleasing the customer. Also, with traditional synchronous rest calls 80% of the bandwidth can be attributed to headers for authorization and authentication for what is only a 20% payload. From an efficiency perspective this is far less than ideal if you have to make numerous cascading calls to your server. With Rails Action Cable and WebSockets this overhead can be drastically reduced!</p><h3>Lifecycle</h3><h4><strong>Client Connects To Cable</strong></h4><p>The client will send a normal looking HTTP request to the server with all auth headers attached. This is really no different from a normal call, except that it’s looking to connect to what is called a cable. A cable is a generic abstraction of handling the passing of information back and forth, and is facilitated over a WebSocket. Most of this is done when the server <strong>handles the connection</strong> (see below).</p><h4><strong>Server Handles Connection</strong></h4><p>The server processes the headers, checks the auth credentials and validates the payload. It then creates a handshake connection called a WebSocket from the HTTP request using Rack Hijack. This allows for continuous two-way data transfer without needing to authenticate every time information is passed. Relating back to the restaurant example, imaging that every time the waiter needed to interact with the chef he/she needed to recite a (long) passcode which the chef then has to double check against a handmade list of hundreds of employees, would probably slow things down right? No think of how they actually work, the waiter and chef see each other in the morning, then throughout the rest of the day they do their jobs without needing to re-establish their identity.</p><h4><strong>Clients Subscribes to Channel</strong></h4><p>Action Cable allows for a pub/sub architecture to various channels. Channel streams are abstractions used to specify types of data being passed. Relating this back to the restaurant, the notification channel would be equivalent to the waiter actively listening for the bell the chef rings when the food is ready. When the waiter is on break he stops listening to (unsubscribes from) the bell until he’s done.</p><h4><strong>Client sends messages to the server &amp; Server Responds to Client</strong></h4><p>This is the information transfer between client and server until the connection is terminated.</p><h3>Conclusion</h3><p>Smaller applications can get away with having a single stream of information and multiple HTTP requests. However, upon scale you might need to consider the implementation of other systems to help with things like background jobs. Rails Action Cable bridges that gap by leveraging (if you choose) a speedy Redis server, alleviating some load on your core application. Action Cable is great for things like sending emails in the background, processing your CRON jobs or doing some data cleanup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9180193927f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>