<?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 Agustín Serena on Medium]]></title>
        <description><![CDATA[Stories by Agustín Serena on Medium]]></description>
        <link>https://medium.com/@agustin.serena?source=rss-af33738452d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2puoOJPN4tlTcfISUPjZcw.jpeg</url>
            <title>Stories by Agustín Serena on Medium</title>
            <link>https://medium.com/@agustin.serena?source=rss-af33738452d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:38:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@agustin.serena/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[Coordinating Rails and JavaScript with Custom Turbo Actions]]></title>
            <link>https://medium.com/unagi/coordinating-rails-and-javascript-with-custom-turbo-actions-17865779ab92?source=rss-af33738452d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/17865779ab92</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tubo]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Agustín Serena]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 15:45:13 GMT</pubDate>
            <atom:updated>2025-08-06T16:00:13.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l-2cAVVyq28HeCyCqPL1gw.jpeg" /></figure><p>We recently built a quiz feature that needed to celebrate correct answers with confetti animations. The challenge wasn’t the confetti itself but coordinating between our Rails controller and the frontend JavaScript without mixing concerns or adding complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yID0fF-UTGAATYcSDlVyqg.gif" /></figure><p>The solution led us to discover how Turbo Stream’s extensibility can solve coordination problems in surprisingly elegant ways.</p><h3>Starting Simple: A Custom Confetti Action</h3><p>For our quiz, we started with something specific: a custom action that triggers confetti directly. Our Rails controller becomes remarkably clean:</p><pre>class QuizController &lt; ApplicationController<br>  def create<br>    if correct_answer? <br>      render turbo_stream: turbo_stream.action(:confetti)<br>    else<br>      # Handle incorrect answer<br>    end<br>  end<br>end</pre><p>The controller focuses purely on business logic, validating answers and deciding outcomes. When the answer is correct, it tells Turbo to trigger confetti, and that’s it.</p><p>To make this work, we extend <a href="https://turbo.hotwired.dev/handbook/streams#custom-actions">Turbo.StreamActions</a> with custom behavior:</p><pre>Turbo.StreamActions.confetti = function () {<br>  launchConfetti();<br>};</pre><h3>Making It Generic: The Trigger Action</h3><p>The real insight came when we needed similar coordination for other features. Instead of creating specific actions like confetti, hideSpinner, closeDialog or playSound, we could create one generic action that triggers JavaScript events.</p><p>Now our quiz controller can trigger any event by specifying it in the target:</p><pre>class QuizController &lt; ApplicationController<br>  def create<br>    if correct_answer? <br>      render turbo_stream: turbo_stream.action(:trigger, &quot;launch-confetti&quot;)<br>    else<br>      ...<br>    end<br>  end<br>end</pre><p>This works with one simple JavaScript function that transforms any Turbo Stream response into a custom DOM event:</p><pre>Turbo.StreamActions.trigger = function () {<br>  document.dispatchEvent(new Event(this.target));<br>};</pre><h3>Frontend Components as Event Listeners</h3><p>With events, our frontend components become listeners that can react independently:</p><pre>export default class extends Controller {<br>  connect() {<br>    document.addEventListener(&quot;launch-confetti&quot;, this.launchConfetti);<br>  }<br>  <br>  launchConfetti() {<br>    🎉🎉🎉<br>  }<br>}</pre><p>When a correct answer triggers the “launch-confetti” event, our Stimulus controller responds with the celebration animation.</p><p>This pattern opens up many possibilities. Your Rails controllers can trigger events like:</p><ul><li>hide-loading-spinner after data loads successfully</li><li>play-notification-sound for important alerts</li><li>update-progress-bar during long-running processes</li><li>trigger-analytics-event for user behavior tracking</li></ul><p>Each event can have multiple listeners, and listeners can be added or removed without affecting server code.</p><h3>Why This Approach Wins</h3><p>This pattern keeps Rails controllers focused on data and business logic while enabling rich frontend interactions. Testing becomes easier because you verify events fire without testing implementation details. Multiple components can coordinate without coupling to each other.</p><p>Custom Turbo Stream actions remind us that extending existing tools often beats adding new dependencies. Starting with something specific like confetti and then generalizing to events shows how the best abstractions often emerge from real use cases.</p><p><em>Unagi is a software boutique that offers software development services in Ruby on Rails, a stack we still choose after +12 years. Check out more on our social media.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17865779ab92" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unagi/coordinating-rails-and-javascript-with-custom-turbo-actions-17865779ab92">Coordinating Rails and JavaScript with Custom Turbo Actions</a> was originally published in <a href="https://medium.com/unagi">Unagi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infinite Scrolling with Hotwire Turbo Frames in Ruby on Rails]]></title>
            <link>https://medium.com/unagi/infinite-scrolling-with-hotwire-turbo-frames-in-ruby-on-rails-0f1404c3f113?source=rss-af33738452d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f1404c3f113</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[turbo]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[infinite-scroll]]></category>
            <category><![CDATA[hotwire-rails]]></category>
            <dc:creator><![CDATA[Agustín Serena]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 14:23:32 GMT</pubDate>
            <atom:updated>2024-08-27T14:23:32.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U91QIXYXYh-KjO3LjdbEMA.jpeg" /></figure><p>In modern web applications, providing a smooth and responsive user experience is paramount. Infinite scrolling is a popular technique that loads content dynamically as the user scrolls, eliminating the need for traditional pagination controls. In this article, we’ll explore how to implement infinite scrolling in a Rails application using Turbo Frames, along with the <a href="https://github.com/ddnexus/pagy">pagy</a> gem for efficient pagination.</p><h4><strong>Why Turbo Frames?</strong></h4><p>Turbo Frames, part of the Hotwire stack, allow you to update only a portion of the page without a full reload. This is particularly useful for infinite scrolling, where you want to append new content to an existing list without disrupting the user’s interaction with the page.</p><h4>Setting Up Infinite Scrolling with Pagy</h4><p>To get started, we’ll use the pagy gem, which offers a simple and performant way to handle pagination in Rails. For infinite scrolling, we’ll use the pagy_countless method, ideal when you don’t need to know the total count of items up front.</p><p>Here’s how to set up the ProductsController to handle infinite scrolling:</p><pre># app/controllers/products_controller.rb<br><br>class ProductsController &lt; ApplicationController<br>  include Pagy::Backend<br><br>  def index<br>    @pagy, @products = pagy_countless(Product.all, items: 25)<br><br>    respond_to do |format|<br>      format.html<br>      format.turbo_stream<br>    end<br>  end<br>end</pre><p>In this code, @pagy manages the pagination logic, while @products holds the items to display. The controller is configured to respond to both HTML and Turbo Stream requests, making it easy to incorporate Turbo Frames.</p><h4>Building the HTML View</h4><p>Next, let’s create the HTML view that will display the products and set up Turbo Frames for infinite scrolling:</p><pre># app/views/products/index.html.erb<br><br>&lt;table&gt;<br>  &lt;thead&gt;<br>    &lt;tr&gt;<br>      &lt;th&gt; Name &lt;/th&gt;<br>    &lt;/tr&gt;<br>  &lt;/thead&gt;<br>  &lt;tbody id=&quot;products&quot;&gt;<br>    &lt;%= render @products %&gt;<br>  &lt;/tbody&gt;<br>&lt;/table&gt;<br><br>&lt;% if @pagy.next.present? %&gt;<br>  &lt;%= turbo_frame_tag :next_page, src: products_path(page: @pagy.next, format: :turbo_stream), loading: :lazy %&gt;<br>&lt;% end %&gt;</pre><p>Here, the initial set of products is rendered inside a table. If more pages exist, a turbo_frame_tag is added to lazily load the next set of products when the user scrolls near the bottom.</p><h4>Handling Turbo Stream Updates</h4><p>When the user reaches the bottom of the page, a new request is made to load additional products. This request is handled by the Turbo Stream view, which appends the new items to the existing list and updates the Turbo Frame for the next page.</p><pre># app/views/products/index.turbo_stream.erb<br><br>&lt;%= turbo_stream.append :products do %&gt;<br>  &lt;%= render @products %&gt;<br>&lt;% end %&gt;<br><br>&lt;% if @pagy.next.present? %&gt;<br>  &lt;%= turbo_stream.replace :next_page do %&gt;<br>    &lt;%= turbo_frame_tag :next_page, src: products_path(page: @pagy.next, format: :turbo_stream), loading: :lazy %&gt;<br>  &lt;% end %&gt;<br>&lt;% end %&gt;</pre><h4>Bringing It All Together</h4><p>With this setup, your Rails application now supports infinite scrolling powered by Turbo Frames. This approach not only improves the user experience by reducing page reloads but also keeps your codebase clean and manageable.</p><p>By leveraging the power of Turbo Frames and Pagy, you can implement infinite scrolling in a way that is both performant and easy to maintain. Whether you’re working on a small project or a large-scale application, this technique will help you create a more seamless and modern user interface.</p><p><a href="https://unagisoftware./"><em>Unagi</em></a><em> is a software boutique that offers software development services in Ruby on Rails, a stack we still choose after +12 years. Check out more on our </em><a href="https://linktr.ee/unagisoftware"><em>social media</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f1404c3f113" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unagi/infinite-scrolling-with-hotwire-turbo-frames-in-ruby-on-rails-0f1404c3f113">Infinite Scrolling with Hotwire Turbo Frames in Ruby on Rails</a> was originally published in <a href="https://medium.com/unagi">Unagi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizando las validaciones uniqueness en Rails]]></title>
            <link>https://medium.com/unagi/optimizando-las-validaciones-uniqueness-en-rails-e9601d683703?source=rss-af33738452d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9601d683703</guid>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[uniqueness]]></category>
            <category><![CDATA[case-sensitive]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Agustín Serena]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 14:11:02 GMT</pubDate>
            <atom:updated>2023-10-11T19:45:13.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizando las validaciones en Ruby on Rails: uniqueness y case_sensitive</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rMHE1py1npbktW-qH8FlLw.jpeg" /><figcaption><a href="https://www.freepik.es/vector-gratis/ilustracion-concepto-abstracto-aplicacion-sola-pagina_12291170.htm#page=4&amp;query=actualizacion&amp;position=36&amp;from_view=search&amp;track=sph">Freepik</a> Illustration</figcaption></figure><p>Cuando trabajamos en un modelo en Rails y necesitamos agregar una validación uniqueness con case insensitive, por lo general seguimos estos pasos:</p><ol><li>Creamos el índice unique en la base de datos:</li></ol><pre># db/schema.rb<br>...<br>t.index [&quot;email_address&quot;], name: &quot;index_users_on_email_address&quot;, unique: true</pre><p>2. Agregamos la validación uniqueness al modelo con la opción case_sensitive en false :</p><pre># app/models/user.rb<br><br>class User &lt; ApplicationRecord<br>  ...<br>  validates :email_address, uniqueness: { case_sensitive: false }<br>end</pre><p>Eso parece ser la solución más adecuada, ¿verdad?. Bueno, no del todo 😬. Hay algunas cosas que hacen que esta solución <strong>esté incompleta y sea ineficiente</strong>.</p><p>En primer lugar, el índice unique en la base de datos “no es case-sensitive”. Esto significa que si quitamos la validación uniqueness del modelo o no usamos ActiveRecord para crear el usuario, podríamos terminar con dos registros con la misma dirección de correo electrónico, como “dummy@mydomain.com” y “duMMy@mydomain.com”.</p><p>Pero, incluso si siempre utilizamos ActiveRecord y confiamos en la validación uniqueness del modelo, todavía no estamos aprovechando al máximo el índice, <strong>lo que podría impactar en el rendimiento</strong>.</p><p>Veamos qué sucede al validar un usuario con ActiveRecord con y sin la opción case_sensitive :</p><pre># Sin la opción `case_sensitive: false`<br><br>&gt; User.new(email_address: &#39;duMMy@mydomain.com&#39;).valid?<br>(0.322ms) ActiveRecord -- User Exists? -- { :sql =&gt; &quot;SELECT 1 AS one FROM \&quot;users\&quot; WHERE \&quot;users\&quot;.\&quot;email_address\&quot; = $1 LIMIT $2&quot;, :binds =&gt; { :email_address =&gt; &quot;duMMy@mydomain.com&quot;, :limit =&gt; 1 }, :allocations =&gt; 6, :cached =&gt; nil }<br><br># Con la opción `case_sensitive: false`<br><br>&gt; User.new(email_address: &#39;duMMy@mydomain.com&#39;).valid?<br>(1.424ms) ActiveRecord -- User Exists? -- { :sql =&gt; &quot;SELECT 1 AS one FROM \&quot;users\&quot; WHERE LOWER(\&quot;users\&quot;.\&quot;email_address\&quot;) = LOWER($1) LIMIT $2&quot;, :binds =&gt; { :email_address =&gt; &quot;duMMy@mydomain.com&quot;, :limit =&gt; 1 }, :allocations =&gt; 6, :cached =&gt; nil }</pre><p>Si observamos las consultas SQL, podemos ver que en el segundo caso ActiveRecord agrega LOWER() para realizar la comparación, y ésta toma mucho más tiempo que la primera consulta. Es decir, <strong>sin el uso de </strong><strong>LOWER(), la consulta toma alrededor de ~0.322ms, mientras que con </strong><strong>LOWER() toma ~1.424ms. </strong>Y<strong> </strong>estos resultados son con una base de datos pequeña. Imaginate la diferencia si tenemos un millón de registros!</p><p>Si profundizamos un poco más, un análisis con la instrucción <a href="https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-explain/#:~:text=The%20EXPLAIN%20statement%20returns%20the,join%20algorithm%20will%20be%20used.">EXPLAIN</a> de ambas consultas revela lo siguiente:</p><ul><li>Consulta sin LOWER() :</li></ul><pre>development=# EXPLAIN SELECT 1 AS one FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;email_address&quot; = &#39;duMMy@mydomain.com&#39; LIMIT 1;<br>                                             QUERY PLAN<br>-----------------------------------------------------------------------------------------------------<br> Limit  (cost=0.27..8.29 rows=1 width=4)<br>   -&gt;  Index Only Scan using index_users_on_email_address on users  (cost=0.27..8.29 rows=1 width=4)<br>         Index Cond: (email_address = &#39;dummy@mydomain.com&#39;::text)<br>(3 rows)</pre><ul><li>Consulta con LOWER() :</li></ul><pre>development=# EXPLAIN SELECT 1 AS one FROM &quot;users&quot; WHERE LOWER(&quot;users&quot;.&quot;email_address&quot;) = LOWER(&#39;duMMy@mydomain.com&#39;) LIMIT 1;<br>                                   QUERY PLAN<br>--------------------------------------------------------------------------------<br> Limit  (cost=0.00..4.79 rows=1 width=4)<br>   -&gt;  Seq Scan on users  (cost=0.00..9.57 rows=2 width=4)<br>         Filter: (lower((email_address)::text) = &#39;dummy@mydomain.com&#39;::text)<br>(3 rows)</pre><p>En el primer caso, la consulta utiliza el índice, mientras que en el segundo, realiza un escaneo secuencial 😖.</p><p>Para resolver este problema y optimizar el rendimiento, necesitamos agregar un índice que incluya LOWER(). Esto se puede lograr mediante una migración similar a esta:</p><pre>add_index(<br> :users,<br> &#39;lower(email_address)&#39;,<br> name: &quot;index_users_on_lower_email_address_unique&quot;,<br> unique: true<br>)</pre><p>Con esta modificación, podemos asegurarnos de que las consultas realizadas por ActiveRecord utilicen este nuevo índice, mejorando significativamente el rendimiento.</p><p>En resumen, aunque la solución inicial puede parecer adecuada, es importante tener en cuenta las limitaciones y optimizaciones posibles al trabajar con validaciones uniqueness y case insensitive en Rails. En este caso, agregar un índice adecuado nos ayudó a mejorar significativamente el rendimiento al realizar este tipo de consultas.</p><p><a href="https://unagisoftware.com/"><em>Unagi</em></a><em> brinda servicios de diseño y desarrollo de software a medida, usando tecnologías como </em><strong><em>Ruby</em></strong><em>, </em><strong><em>React</em></strong><em> y </em><strong><em>Javascript</em></strong><em>. Podés visitar cualquiera de </em><a href="https://linktr.ee/unagisoftware"><em>nuestros canales</em></a><em> para saber más de nosotros o escribirnos.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9601d683703" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unagi/optimizando-las-validaciones-uniqueness-en-rails-e9601d683703">Optimizando las validaciones uniqueness en Rails</a> was originally published in <a href="https://medium.com/unagi">Unagi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s new in Ruby 3.1 and Rails 7]]></title>
            <link>https://medium.com/unagi/whats-new-in-ruby-3-1-and-rails-7-1c01990ad61f?source=rss-af33738452d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c01990ad61f</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[releases]]></category>
            <category><![CDATA[rails-7]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Agustín Serena]]></dc:creator>
            <pubDate>Wed, 02 Mar 2022 12:46:04 GMT</pubDate>
            <atom:updated>2022-03-02T12:46:04.737Z</atom:updated>
            <content:encoded><![CDATA[<p>Every December 25th the Ruby community usually releases a minor/major release and last Christmas was not an exception. Both Ruby 3.1 and Rails 7 were released.<br>In this post, we are going to review the most important changes that these new versions bring to us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*318xIBWOlEqCb52V-myxkw.jpeg" /><figcaption>Illustration by <a href="https://icons8.com/illustrations/author/60896eeb088aa7001087bb4d">Rosina Gavrilash</a> from <a href="https://icons8.com/illustrations/">Ouch!</a></figcaption></figure><h3>Ruby 3.1</h3><h4>YJIT: New JIT compiler (experimental)</h4><p>Ruby 3.1 adds YJIT, a new in-process JIT compiler developed by Shopify, one of the biggest contributors to Ruby development. This new compiler is designed to improve the performance of our apps, especially those that use Rails, although it’s important to clarify that it’s still in an experimental phase and is disabled by default. In case we want to enable it, we can do it with the <em>–yjit</em> flag.</p><h4>New debugger: debug gem</h4><p>Let’s say goodbye to byebug. The new version of Ruby brings a completely new gem to debug our applications: <a href="https://github.com/ruby/debug">debug gem</a>. Among some of the features of this new gem we can find performance improvements, support for remote debugging, improved debugging interface (only with VS Code and Google Chrome at the moment), multi-process/multi-thread support, colors, and more.</p><h4>Fine-grain errors in the backtrace: error_highlight</h4><p>This new gem helps to detect the location of the errors that appear in our console, although at the moment it only supports NameError.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*0hm9s5YbeBLY6jZg_JqKbw.png" /></figure><h4>IRB with Autocomplete and Documentation</h4><p>The IRB console now has a new autocomplete function where a list with suggestions appears, and in addition, the documentation (if exists) of the selected option will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*-Zjl3PIvAaxX4RARTVEcuQ.gif" /><figcaption>IRB autocomplete &amp; documentation example</figcaption></figure><h4>Skipping values in hashes and methods with keyword arguments</h4><p>From now on, it will not be necessary to pass values to a hash or a method with named arguments when variables defined with the same name already exist within the context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*ZK7XIzVgSKHzvXn-oTSWKA.png" /><figcaption>Hash example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQlnoE5OKdLUq0rTROHaxA.png" /></figure><h3>Rails 7</h3><h4>Goodbye to Node and Webpack</h4><p>The new version of Rails no longer requires javascript with NodeJS and Webpack (webpacker gem deprecated). In its replacement, Rails will start using the <a href="https://github.com/rails/importmap-rails/">importmap-rails gem</a> by default.</p><p>This way we will no longer have the package.json file or install our dependencies via npm or yarn. From now on, we will have the file config/importmap.rb which will be a kind of Gemfile with all the dependencies, and we will use the “pin” or “unpin” command to install or remove them.</p><blockquote>./bin/importmap pin dependency_name<br>./bin/importmap unpin dependency_name</blockquote><h4>Turbolinks and UJS are replaced by Turbo and Stimulus</h4><p>Turbo and Stimulus come by default with Rails 7 apps. These two new players are part of <a href="https://hotwired.dev/">Hotwire</a>, Rails’ brand new solution aimed at reducing Javascript usage by sending HTML instead of JSON over the wire. Hotwire can improve the initial load speed of the app by reducing client-side processing since most of the site is rendering is done on the server-side.</p><h4>Debug gem by default</h4><p>As we said above, Ruby 3.1 has a new debugging gem, and Rails 7 will add it by default to replace byebug.</p><h4>Encrypted attributes</h4><p>In Rails 7 we can encrypt our database columns very easily through the new encryption method built into ActiveRecord.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNfd1Gah2SIzJQlPmA3Bxw.png" /></figure><p>Ok, everything looks rosy but this has a small problem, we can’t query using those columns. The solution is to add the “<em>deterministic: true</em>” option to the encrypts method.</p><h4>A new way to send files from the controllers</h4><p>How many times did you try to send a file from the controller and the page doesn’t load until the rendering is done? Although there are some solutions to this problem, Rails 7 introduces the send_stream method, which causes the page to return an immediate response while the file continues to be generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YsO5uHJfSEv8As2I30VOXQ.png" /></figure><h4>Ensuring a single record with “sole”</h4><p><em>sole</em> is a new method that avoids having to do &quot;<em>.where&quot;</em> + &quot;<em>.first</em>&quot; or &quot;<em>.find_by</em>&quot; when we do a query and need to make sure that only one record exists for that query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-_8iqEdSqIEOPDFq2PmOA.png" /></figure><p>In both queries, the following can happen:</p><ul><li>If there is only one $100 product, it returns the product in question.</li><li>If there is no $100 product it throws ActiveRecord::RecordNotFound exception.</li><li>If there is more than one $100 product it throws ActiveRecord::SoleRecordExceeded exception.</li></ul><h4>Verifying the presence of an association</h4><p>With the &quot;<em>associated</em>&quot; method we can check that a record has a certain association. This will save us from having to do &quot;<em>joins</em>&quot; and check for the presence of an ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJURFBQ6vNA9FIQ4R_aFrg.png" /></figure><h4>Asynchronous queries</h4><p>Rails 7 introduces a new method called &quot;<em>load_async</em>&quot; that allows us to run queries in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9SHZMKIZgElXYoM639VVA.png" /></figure><p>This allows us to decrease the response time since &quot;<em>load_async</em>&quot; starts a new thread to execute each query, therefore, they are executed simultaneously and immediately. In case we don’t use &quot;<em>load_async</em>&quot; (as we usually do) the queries are not executed until they are referenced in the view.</p><h4>Unlimited retries in ActiveJob</h4><p>I’m not sure how useful and efficient this new ActiveJob feature can be, but now we can do unlimited retries of a job with the &quot;<em>:unlimited&quot;</em> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1OEkJZkWNzlUj99tVcCqQ.png" /></figure><p>I hope you liked these new features as much as I did, and don’t hesitate to comment on any other new features that I haven’t mentioned in this post.</p><p>If you liked this article, you may be interested in one of these:</p><ul><li><a href="https://medium.com/unagi/better-safe-than-sorry-use-git-hooks-to-avoid-mistakes-4ccfa1f78bb9">Better safe than sorry: use git hooks to avoid mistakes</a></li><li><a href="https://medium.com/unagi/make-your-ruby-on-rails-applications-more-readable-with-enums-c7126fcadd49">Make your Ruby on Rails applications more readable with Enums</a></li><li><a href="https://medium.com/unagi/how-to-build-a-ruby-open-source-application-f869fb4410f4">How to build a Ruby open-source application</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c01990ad61f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unagi/whats-new-in-ruby-3-1-and-rails-7-1c01990ad61f">What’s new in Ruby 3.1 and Rails 7</a> was originally published in <a href="https://medium.com/unagi">Unagi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The magic formula to improve your test suite]]></title>
            <link>https://medium.com/unagi/the-magic-formula-to-improve-your-test-suite-b474a20932d?source=rss-af33738452d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b474a20932d</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Agustín Serena]]></dc:creator>
            <pubDate>Fri, 04 Jun 2021 12:19:27 GMT</pubDate>
            <atom:updated>2021-06-04T12:19:27.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9pUobH16wU2uGBMNHGaV4g.jpeg" /><figcaption>Illustration by <a href="https://dribbble.com/Ivan_Haidutski">Ivan Haidutski</a> from <a href="https://icons8.com/illustrations/">Ouch!</a></figcaption></figure><p>There is no such thing as quality software without automated tests. Our software must be properly tested, so it’s important how we structured them. Therefore, in this article, I will give you some tips to write your tests in a readable and reusable way. After reading it, you will realize that without much effort we can improve them considerably.</p><p><em>Disclaimer: This article is actually not magic at all. My tips are based on the </em><strong><em>BDD</em></strong><em> </em><strong><em>(Behavior Driven Development)</em></strong><em> strategy and the use of the </em><a href="https://cucumber.io/docs/gherkin/reference/"><strong><em>Gherkin language</em></strong></a><em> (Given-When-Then), although we’ll only take certain characteristics of each one. But please, don’t tell anyone 🤫</em></p><p><strong>Let’s go there!</strong></p><p>The idea is to modularize our tests by extracting the different actions into different methods in such a way that we have clear and understandable tests at a glance. This way, they can be read as if they were user stories or acceptance criteria.</p><p>Let’s see a basic example where we’ll test a list of products with and without filters. In one scenario we’ll verify the display of the list and, in a second scenario, we’ll add some tests to filter the products by name.</p><p><em>Note: for the examples, I’m going to use Rspec but feel free to use Minitest or any other framework. It really doesn’t matter.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e5d74c9c7b37acd5330f3b61e3b22cb/href">https://medium.com/media/6e5d74c9c7b37acd5330f3b61e3b22cb/href</a></iframe><p>Although these two scenarios verify relatively simple and concrete functionalities, we see that the tests have a significant length, and are not clear nor readable.</p><p>Now let’s go straight into the magic 😉 and re-implement the same tests using the concepts mentioned above. Here we extract the actions to private methods and define them using the Gherkin language:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88908770260663f5a6879a9b3234139a/href">https://medium.com/media/88908770260663f5a6879a9b3234139a/href</a></iframe><p>Yes, I confess, the final code is longer 🤥 But nobody can deny that it’s more readable and clear. I bet that even someone knowing nothing about Ruby could get a general idea of what’s happening there. But you know what I like the most? We haven’t done anything new. Just by applying basic programming concepts, we really improve our test suite.</p><p>This second example is much clearer and has several advantages:</p><ul><li>we can read the tests in a natural language, instantly understanding what each scenario verifies</li><li>we get rid of duplicated code by using private methods</li><li>no scenario contains data creation</li><li>facilitates test maintenance</li><li>makes code review easier</li></ul><p>Having tests in our developments is as important as implementing them in a good, clear, and elegant way. These issues are often not given due attention, and we end up having tests that are difficult to understand and maintain.</p><p>At <a href="https://unagi.com.ar/">Unagi</a>, we know that the quality of the tests defines the quality of the final product, which is why we have been using this type of technique for a long time. We know there is still more to improve, but this is a simple trick to do it.</p><p>And what about you? Do you use any other trick to improve your tests? We would love to read about it. Please, leave your comments and don’t forget to leave 👏🏻👏🏻👏🏻 if you liked this article.</p><p><a href="https://unagi.com.ar/">Unagi</a> is a software factory that provides design and development services for startups, small and mid-size companies. Read more about us on our <a href="https://unagi.com.ar/">website</a>, <a href="https://medium.com/unagi">blog</a>, <a href="https://twitter.com/unagisoftware">Twitter</a>, or <a href="https://www.linkedin.com/company/unagisoftware">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b474a20932d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/unagi/the-magic-formula-to-improve-your-test-suite-b474a20932d">The magic formula to improve your test suite</a> was originally published in <a href="https://medium.com/unagi">Unagi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>