<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Ruby on MoskitoHero</title><link>/tags/ruby/</link><description>Recent content in Ruby on MoskitoHero</description><generator>Hugo</generator><language>en-us</language><lastBuildDate>Tue, 06 May 2025 00:00:00 +0000</lastBuildDate><atom:link href="/tags/ruby/index.xml" rel="self" type="application/rss+xml"/><item><title>An introduction to Barley, the fast model serializer</title><link>/post/2025-05-06-an-introduction-to-barley-the-fast-model-serializer/</link><pubDate>Tue, 06 May 2025 00:00:00 +0000</pubDate><guid>/post/2025-05-06-an-introduction-to-barley-the-fast-model-serializer/</guid><description>How I built and open-sourced Barley, a fast and simple model serializer gem for Rails, born from real-world performance needs and benchmarked against the best in the Ruby ecosystem.</description><content:encoded><![CDATA[<div class="sect1">
<h2 id="the-story"><a class="anchor" href="#the-story"></a>The story</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The company I used to work for had an ageing API in v1 that was very poorly designed and slow in its implementation. It served 4 frontend platforms (a website, two mobile apps and an administration tool). Being in a startup environment, our team had to move fast, but that was at the expense of performance and maintainability. This was the situation when I arrived there.
Returning JSON objects was very cumbersome. It used a custom method, available in each model that built a nested Hash, based on the attributes you gave it. That turned out to be a mess with poor performance and concerning security implications. It was difficult to maintain, with odd variable naming and behavior, so we set out to get rid of it somehow and moved to a kind of serializer DSL that was gradually introduced to replace the old mess.
Later, we decided to tighten up our API with a new version to get rid of the legacy. A few requirements quickly emerged, among which:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>API V2 should be easy to maintain, with clear naming conventions and namespacing</p>
</li>
<li>
<p>Since it is an internal API, it should be tightly coupled to the intended use and platform</p>
</li>
<li>
<p>API V2 should use some sort of view DSL to generate the JSON payloads</p>
</li>
<li>
<p>API V2 should be as predictable as possible in terms of typing and formatting.</p>
</li>
<li>
<p>API V2 should be super fast by default. It should be the last thing we need to optimize.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>So I looked at the serializer DSL that we had designed for API v1.
The first thing I did was to benchmark it against other solutions. So I stripped it out of legacy / no longer needed features, moved it to a local gem, and started playing with a few benchmarks.
And it was <em>very fast</em> indeed ! This is the result of a <a href="https://github.com/MoskitoHero/active_model_serializers/tree/benchmarks">benchmark</a> I did back then:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="shell">Warming up <span class="nt">--------------------------------------</span>
<span class="c"># Omitted for conciseness</span>
Calculating <span class="nt">-------------------------------------</span>
ams                    67.770  <span class="o">(</span>± 1.9%<span class="o">)</span> i/s -    657.000  <span class="k">in  </span>10.042270s
jsonapi-rb            157.239  <span class="o">(</span>± 2.3%<span class="o">)</span> i/s -      1.521k <span class="k">in  </span>10.010257s
barley                 96.909  <span class="o">(</span>± 2.4%<span class="o">)</span> i/s -    945.000  <span class="k">in  </span>10.036316s
barley-cache            4.589k <span class="o">(</span>± 2.8%<span class="o">)</span> i/s -     44.620k <span class="k">in  </span>10.010004s
ams          eager     68.237  <span class="o">(</span>± 6.2%<span class="o">)</span> i/s -    592.000  <span class="k">in  </span>10.087602s
jsonapi-rb   eager    289.733  <span class="o">(</span>± 3.7%<span class="o">)</span> i/s -      2.805k <span class="k">in  </span>10.033912s
barley       eager    406.732  <span class="o">(</span>± 3.2%<span class="o">)</span> i/s -      3.922k <span class="k">in  </span>10.020076s
barley-cache eager    639.935  <span class="o">(</span>± 2.4%<span class="o">)</span> i/s -      6.300k <span class="k">in  </span>10.053710s
with 95.0% confidence

Comparison:
barley-cache      :     4589.3 i/s
barley-cache eager:      639.9 i/s - 7.17x  <span class="o">(</span>± 0.27<span class="o">)</span> slower
barley       eager:      406.7 i/s - 11.29x  <span class="o">(</span>± 0.49<span class="o">)</span> slower
jsonapi-rb   eager:      289.7 i/s - 15.83x  <span class="o">(</span>± 0.74<span class="o">)</span> slower
jsonapi-rb        :      157.2 i/s - 29.17x  <span class="o">(</span>± 1.08<span class="o">)</span> slower
barley            :       96.9 i/s - 47.37x  <span class="o">(</span>± 1.75<span class="o">)</span> slower
ams          eager:       68.2 i/s - 67.25x  <span class="o">(</span>± 4.69<span class="o">)</span> slower
ams               :       67.8 i/s - 67.72x  <span class="o">(</span>± 2.31<span class="o">)</span> slower
with 95.0% confidence

Calculating <span class="nt">-------------------------------------</span>
<span class="c"># Omitted for conciseness</span>

Comparison:
barley-cache      :      46090 allocated
barley-cache eager:     216790 allocated - 4.70x more
barley       eager:     354326 allocated - 7.69x more
jsonapi-rb   eager:     694430 allocated - 15.07x more
jsonapi-rb        :     926082 allocated - 20.09x more
ams          eager:    1068038 allocated - 23.17x more
barley            :    1102354 allocated - 23.92x more
ams               :    1299674 allocated - 28.20x more</code></pre>
</div>
</div>
<div class="paragraph">
<p>Which is quite nice 😎.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="sharing-is-caring"><a class="anchor" href="#sharing-is-caring"></a>Sharing is caring</h2>
<div class="sectionbody">
<div class="paragraph">
<p>So I made a gem out of our serializer and <a href="https://github.com/MoskitoHero/barley">published it on Github</a>. It is named Barley.
I have recently made the gem even faster (from v0.9.0 on) and benchmarked it against <a href="https://github.com/okuramasafumi/alba">Alba</a>, <a href="https://github.com/procore-oss/blueprinter">Blueprinter</a>, <a href="https://github.com/malomalo/turbostreamer">Turbostreamer</a>, <a href="https://github.com/distil/jserializer">Jserializer</a>, <a href="https://github.com/estepnv/fast_serializer">FastSerializer</a>, <a href="https://github.com/trailblazer/representable">Representable</a>, <a href="https://github.com/vasilakisfil/SimpleAMS">SimpleAMS</a>, <a href="https://github.com/rails-api/active_model_serializers">AMS</a>, <a href="https://github.com/rails/jbuilder">Rails JBuilder</a> and <a href="https://github.com/yosiat/panko_serializer">Panko</a>.
Here are the results of these new benchmarks:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="shell">ruby 3.4.3 <span class="o">(</span>2025-04-14 revision d0b7e5b6a0<span class="o">)</span> +YJIT +PRISM <span class="o">[</span>x86_64-linux]
Warming up <span class="nt">--------------------------------------</span>
<span class="c"># Omitted for conciseness</span>

Calculating <span class="nt">-------------------------------------</span>
                alba    401.119 <span class="o">(</span>± 1.7%<span class="o">)</span> i/s    <span class="o">(</span>2.49 ms/i<span class="o">)</span> -      2.016k <span class="k">in   </span>5.027350s
alba_with_transformation
                        256.123 <span class="o">(</span>± 1.2%<span class="o">)</span> i/s    <span class="o">(</span>3.90 ms/i<span class="o">)</span> -      1.300k <span class="k">in   </span>5.076497s
         alba_inline     22.749 <span class="o">(</span>± 8.8%<span class="o">)</span> i/s   <span class="o">(</span>43.96 ms/i<span class="o">)</span> -    114.000 <span class="k">in   </span>5.049973s
                 ams     16.923 <span class="o">(</span>± 5.9%<span class="o">)</span> i/s   <span class="o">(</span>59.09 ms/i<span class="o">)</span> -     85.000 <span class="k">in   </span>5.029061s
              barley    427.045 <span class="o">(</span>± 2.6%<span class="o">)</span> i/s    <span class="o">(</span>2.34 ms/i<span class="o">)</span> -      2.162k <span class="k">in   </span>5.066130s
        barley_cache    378.285 <span class="o">(</span>± 2.4%<span class="o">)</span> i/s    <span class="o">(</span>2.64 ms/i<span class="o">)</span> -      1.927k <span class="k">in   </span>5.097462s
         blueprinter    120.704 <span class="o">(</span>± 1.7%<span class="o">)</span> i/s    <span class="o">(</span>8.28 ms/i<span class="o">)</span> -    612.000 <span class="k">in   </span>5.071371s
     fast_serializer    142.347 <span class="o">(</span>± 1.4%<span class="o">)</span> i/s    <span class="o">(</span>7.03 ms/i<span class="o">)</span> -    720.000 <span class="k">in   </span>5.058924s
         jserializer    252.455 <span class="o">(</span>± 1.6%<span class="o">)</span> i/s    <span class="o">(</span>3.96 ms/i<span class="o">)</span> -      1.274k <span class="k">in   </span>5.047584s
               panko    510.262 <span class="o">(</span>± 4.7%<span class="o">)</span> i/s    <span class="o">(</span>1.96 ms/i<span class="o">)</span> -      2.585k <span class="k">in   </span>5.077381s
               rails    107.589 <span class="o">(</span>± 7.4%<span class="o">)</span> i/s    <span class="o">(</span>9.29 ms/i<span class="o">)</span> -    546.000 <span class="k">in   </span>5.104715s
       representable     50.264 <span class="o">(</span>± 6.0%<span class="o">)</span> i/s   <span class="o">(</span>19.89 ms/i<span class="o">)</span> -    252.000 <span class="k">in   </span>5.027987s
          simple_ams     36.584 <span class="o">(</span>± 5.5%<span class="o">)</span> i/s   <span class="o">(</span>27.33 ms/i<span class="o">)</span> -    184.000 <span class="k">in   </span>5.054347s
       turbostreamer    351.551 <span class="o">(</span>± 1.7%<span class="o">)</span> i/s    <span class="o">(</span>2.84 ms/i<span class="o">)</span> -      1.776k <span class="k">in   </span>5.053401s

Comparison:
               panko:      510.3 i/s
              barley:      427.0 i/s - 1.19x  slower
                alba:      401.1 i/s - 1.27x  slower
        barley_cache:      378.3 i/s - 1.35x  slower
       turbostreamer:      351.6 i/s - 1.45x  slower
alba_with_transformation:      256.1 i/s - 1.99x  slower
         jserializer:      252.5 i/s - 2.02x  slower
     fast_serializer:      142.3 i/s - 3.58x  slower
         blueprinter:      120.7 i/s - 4.23x  slower
               rails:      107.6 i/s - 4.74x  slower
       representable:       50.3 i/s - 10.15x  slower
          simple_ams:       36.6 i/s - 13.95x  slower
         alba_inline:       22.7 i/s - 22.43x  slower
                 ams:       16.9 i/s - 30.15x  slower

Calculating <span class="nt">-------------------------------------</span>
<span class="c"># Omitted for conciseness</span>

Comparison:
               panko:     259178 allocated
              barley:     633521 allocated - 2.44x more
       turbostreamer:     641760 allocated - 2.48x more
alba_with_transformation:     818181 allocated - 3.16x more
                alba:     818241 allocated - 3.16x more
         jserializer:     822281 allocated - 3.17x more
        barley_cache:     849521 allocated - 3.28x more
     fast_serializer:    1470121 allocated - 5.67x more
         blueprinter:    2297921 allocated - 8.87x more
         alba_inline:    2736041 allocated - 10.56x more
               rails:    2757857 allocated - 10.64x more
                 ams:    4713401 allocated - 18.19x more
       representable:    5151321 allocated - 19.88x more
          simple_ams:    9017033 allocated - 34.79x more</code></pre>
</div>
</div>
<div class="paragraph">
<p>With YJIT enabled, Barley really shines and is the first Hash serializer of the group.
There are <a href="https://github.com/MoskitoHero/barley/tree/main/benchmarks#readme">more benchmarks to be found in the Barley repository</a>.
Barley is very simple in its implementation and allocates very little. I believe that it is what makes it so fast. I’ll write another post on how I optimized it in version 0.9.0.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="the-features"><a class="anchor" href="#the-features"></a>The Features</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Barley provides:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>a clear DSL to define your serializer</p>
</li>
<li>
<p>inline / block sub-serializer definition</p>
</li>
<li>
<p>russian-doll caching</p>
</li>
<li>
<p>type-checking with <a href="https://dry-rb.org/gems/dry-types/main/">dry-types</a></p>
</li>
<li>
<p>context handling</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>This is how Barley works:</p>
</div>
<div class="sect2">
<h3 id="in-the-model-you-want-to-serialize"><a class="anchor" href="#in-the-model-you-want-to-serialize"></a>In the model you want to serialize</h3>
<div class="paragraph">
<p>First, include the Barley::Serializable concern in your model.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="c1"># /app/models/user.rb</span>
<span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="kp">include</span> <span class="no">Barley</span><span class="o">::</span><span class="no">Serializable</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Once you include this module, Barley will look for a UserSerializable class in your codebase, so you need to define one, typically in the app/serializable directory. It should inherit from Barley::Serializer</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="c1"># /app/serializers/user_serializer.rb</span>
<span class="k">class</span> <span class="nc">UserSerializer</span> <span class="o">&lt;</span> <span class="no">Barley</span><span class="o">::</span><span class="no">Serializer</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Once this is set up, the as_json method on your model will return what you have defined in your serializer class.
You can also chose to use a different serializer to render your data. You can use the serializer method in your model. This method also allows you to pass a cache argument.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="c1"># /app/models/user.rb</span>
<span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="kp">include</span> <span class="no">Barley</span><span class="o">::</span><span class="no">Serializable</span>

  <span class="n">serializer</span> <span class="no">MyCustomSerializer</span><span class="p">,</span> <span class="ss">cache: </span><span class="kp">true</span>
  <span class="c1"># or</span>
  <span class="n">serializer</span> <span class="no">MyCustomSerializer</span><span class="p">,</span> <span class="ss">cache: </span><span class="p">{</span><span class="ss">expires_in: </span><span class="mi">1</span><span class="p">.</span><span class="nf">hour</span><span class="p">}</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Another way to achieve this is through the as_json method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="no">User</span><span class="p">.</span><span class="nf">first</span><span class="p">.</span><span class="nf">as_json</span><span class="p">(</span><span class="ss">serializer: </span><span class="no">MyCustomSerializer</span><span class="p">,</span> <span class="ss">cache: </span><span class="p">{</span><span class="ss">expires_in: </span><span class="mi">1</span><span class="p">.</span><span class="nf">hour</span><span class="p">})</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Please note that Barley overrides the as_json method and does not provide it with standard only, include or except arguments. This is because the purpose of this serializer is precisely to do that job. The root argument works, though.</p>
</div>
</div>
<div class="sect2">
<h3 id="defining-the-serializer"><a class="anchor" href="#defining-the-serializer"></a>Defining the serializer</h3>
<div class="paragraph">
<p>Let’s go back to the serializer class. Barley provides a simple DSL that allows you to define your JSON in a readable and maintainable way. Here is an example definition that covers most use cases:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="c1"># /app/serializers/user_serializer.rb</span>
<span class="k">class</span> <span class="nc">UserSerializer</span> <span class="o">&lt;</span> <span class="no">Barley</span><span class="o">::</span><span class="no">Serializer</span>

  <span class="n">attributes</span> <span class="ss">id: </span><span class="no">Types</span><span class="o">::</span><span class="no">Strict</span><span class="o">::</span><span class="no">Integer</span><span class="p">,</span> <span class="ss">:name</span>

  <span class="n">attribute</span> <span class="ss">:email</span>
  <span class="n">attribute</span> <span class="ss">:value</span><span class="p">,</span> <span class="ss">type: </span><span class="no">Types</span><span class="o">::</span><span class="no">Coercible</span><span class="o">::</span><span class="no">Integer</span>

  <span class="n">many</span> <span class="ss">:posts</span>

  <span class="n">one</span> <span class="ss">:group</span><span class="p">,</span> <span class="ss">serializer: </span><span class="no">CustomGroupSerializer</span>

  <span class="n">many</span> <span class="ss">:related_users</span><span class="p">,</span> <span class="ss">key: :friends</span><span class="p">,</span> <span class="ss">cache: </span><span class="kp">true</span>

  <span class="n">one</span> <span class="ss">:profile</span><span class="p">,</span> <span class="ss">cache: </span><span class="p">{</span> <span class="ss">expires_in: </span><span class="mi">1</span><span class="p">.</span><span class="nf">day</span> <span class="p">}</span> <span class="k">do</span>
    <span class="n">attributes</span> <span class="ss">:avatar</span><span class="p">,</span> <span class="ss">:social_url</span>

    <span class="n">attribute</span> <span class="ss">:badges</span> <span class="k">do</span>
      <span class="n">object</span><span class="p">.</span><span class="nf">badges</span><span class="p">.</span><span class="nf">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:display_name</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>

<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>For type-checking to work, you need to define a Types module like this, somewhere in your codebase:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="k">module</span> <span class="nn">Types</span>
  <span class="kp">include</span> <span class="no">Dry</span><span class="o">.</span><span class="no">Types</span><span class="p">()</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="sect3">
<h4 id="1-attributes"><a class="anchor" href="#1-attributes"></a>1. Attributes</h4>
<div class="paragraph">
<p>They can be defined as an array with the plural attributes method. It can be an array of symbols, or an array of hashes in the key: TypeDefinition pattern, or a mix of both.
They can also be defined with a singular attribute method, that accepts a type keyword argument.
If type is included in an attribute’s definition, it will raise an error. You can use types to coerce types and define constraints. Please refer to the <a href="https://dry-rb.org/gems/dry-types/main/">dry-types</a> gem for more options.
If you give a block to the attribute method, you can also return anything you like. You have the object object at hand that refers to the serialized model.</p>
</div>
</div>
<div class="sect3">
<h4 id="2-associations"><a class="anchor" href="#2-associations"></a>2. Associations</h4>
<div class="paragraph">
<p>They are defined with the one or many methods.
It will use the default serializer if no argument is given. You can provide it with a serializer and a cache option.
These methods do not provide a type argument, as it makes no sense to do so.
You can also decide to give it a block, that allows you to define the association’s serializer inline.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="wrapping-it-up"><a class="anchor" href="#wrapping-it-up"></a>Wrapping it up</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The Barley gem’s goal is to provide a simple DSL to define your JSON payloads with a type-proof option, and render it in a very fast and efficient manner. It is probably not as feature-packed as other serializers available to the rails community, but it is a no-brainer, yet powerful option that you should consider if you are looking for performance and simplicity.
I’d be happy to see more projects starting to adopt it and would love the community to provide optimizations to make it even better.</p>
</div>
</div>
</div>
]]></content:encoded></item><item><title>Ruby Best Practices - Method Arguments</title><link>/post/2024-01-12-ruby-best-practices-method-arguments/</link><pubDate>Fri, 12 Jan 2024 00:00:00 +0000</pubDate><guid>/post/2024-01-12-ruby-best-practices-method-arguments/</guid><description>Simple rules for ordering Ruby method arguments — put optional arguments last, and switch to keyword arguments when you have more than one optional parameter.</description><content:encoded><![CDATA[<div class="paragraph">
<p>To write readable and maintainable code, follow a few simple rules about argument ordering.</p>
</div>
<div class="sect1">
<h2 id="tip-1-optional-arguments-go-last"><a class="anchor" href="#tip-1-optional-arguments-go-last"></a>Tip 1: Optional arguments go last</h2>
<div class="sectionbody">
<div class="paragraph">
<p>When a method takes several arguments, and some of them have default values, make sure to put the optional ones at the end.
Take this method definition:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="s2">&#34;val_b&#34;</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span>
  <span class="c1"># some code...</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Looks fine at first glance. But in practice, it’s impossible to call this method with values for a and c without also specifying b. You end up writing:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">foo</span><span class="p">(</span><span class="s2">&#34;val_a&#34;</span><span class="p">,</span> <span class="s2">&#34;val_b&#34;</span><span class="p">,</span> <span class="s2">&#34;val_c&#34;</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>…​which defeats the purpose of setting a default for b if you’re forced to specify it every time. ¯<em>(ツ)</em>/¯</p>
</div>
<div class="sect2">
<h3 id="solution-move-optional-arguments-to-the-end"><a class="anchor" href="#solution-move-optional-arguments-to-the-end"></a>Solution: move optional arguments to the end</h3>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">c</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="s2">&#34;val_b&#34;</span><span class="p">)</span>
  <span class="c1"># some code...</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Now you can call:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">foo</span><span class="p">(</span><span class="s2">&#34;val_a&#34;</span><span class="p">,</span> <span class="s2">&#34;val_c&#34;</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>No problem 😎.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="tip-2-use-keyword-arguments-aka-kwargs"><a class="anchor" href="#tip-2-use-keyword-arguments-aka-kwargs"></a>Tip 2: Use keyword arguments (aka kwargs)</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Tip 1 only gets you so far. What if you have multiple optional arguments and want to override just the last one? You’d still need to specify all the previous ones.
For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span> <span class="o">=</span> <span class="s2">&#34;val_c&#34;</span><span class="p">,</span> <span class="n">d</span> <span class="o">=</span> <span class="s2">&#34;val_d&#34;</span><span class="p">,</span> <span class="n">e</span> <span class="o">=</span> <span class="s2">&#34;val_e&#34;</span><span class="p">)</span>
  <span class="c1"># some code...</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Want to change only e? Too bad — you still have to write:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">foo</span><span class="p">(</span><span class="s2">&#34;val_a&#34;</span><span class="p">,</span> <span class="s2">&#34;val_b&#34;</span><span class="p">,</span> <span class="s2">&#34;val_c&#34;</span><span class="p">,</span> <span class="s2">&#34;val_d&#34;</span><span class="p">,</span> <span class="s2">&#34;my_val_e&#34;</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Now imagine this in a large codebase:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">foo</span><span class="p">(</span><span class="n">user</span><span class="p">.</span><span class="nf">id</span><span class="p">,</span> <span class="s2">&#34;DONE&#34;</span><span class="p">,</span> <span class="kp">true</span><span class="p">,</span> <span class="kp">false</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s2">&#34;always&#34;</span><span class="p">,</span> <span class="kp">true</span><span class="p">,</span> <span class="n">post</span><span class="p">.</span><span class="nf">id</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>And you’re left thinking: <em>&#34;Wait, what’s that <strong>false</strong> again? What does the <strong>1</strong> do? Why <strong>&#39;always&#39;</strong>?&#34;</em>
Not ideal, especially under pressure in a production bug fix.</p>
</div>
<div class="sect2">
<h3 id="solution-switch-to-keyword-arguments-when-you-hit-2-optional-params"><a class="anchor" href="#solution-switch-to-keyword-arguments-when-you-hit-2-optional-params"></a>Solution: switch to keyword arguments when you hit 2+ optional params</h3>
<div class="paragraph">
<p>Benefits:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Argument order doesn’t matter anymore</p>
</li>
<li>
<p>You can ignore defaults entirely</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The method now becomes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="ss">c: </span><span class="s2">&#34;val_c&#34;</span><span class="p">,</span> <span class="ss">d: </span><span class="s2">&#34;val_d&#34;</span><span class="p">,</span> <span class="ss">e: </span><span class="s2">&#34;val_e&#34;</span><span class="p">)</span>
  <span class="c1"># some code...</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>To change only e, you write:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">foo</span><span class="p">(</span><span class="s2">&#34;val_a&#34;</span><span class="p">,</span> <span class="s2">&#34;val_b&#34;</span><span class="p">,</span> <span class="ss">e: </span><span class="s2">&#34;my_val_e&#34;</span><span class="p">)</span></code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="ninja-level-tip-the-clean-coders-take"><a class="anchor" href="#ninja-level-tip-the-clean-coders-take"></a>Ninja-level tip — the clean coder’s take:</h2>
<div class="sectionbody">
<div class="paragraph">
<p><strong>If your method takes more than 1 argument, make everything after the first a keyword argument. Always.</strong></p>
</div>
<div class="sect2">
<h3 id="example"><a class="anchor" href="#example"></a>Example:</h3>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="k">def</span> <span class="nf">send_message_to</span><span class="p">(</span><span class="n">recipient</span><span class="p">,</span> <span class="ss">confirm: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">bcc: </span><span class="s2">&#34;joe@bill.com&#34;</span><span class="p">,</span> <span class="ss">cc: </span><span class="s2">&#34;jane@doe.com&#34;</span><span class="p">)</span>
  <span class="c1"># ruby code</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Here, the first argument is obvious thanks to the method name: you’re sending a message <em>to</em> someone.
Called without options:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">send_message_to</span><span class="p">(</span><span class="s2">&#34;sam@sam.com&#34;</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Clear and concise.
Compare a non-keyword version:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">send_message</span><span class="p">(</span><span class="s2">&#34;recipient@mail.com&#34;</span><span class="p">,</span> <span class="kp">false</span><span class="p">,</span> <span class="s2">&#34;joe@bill.com&#34;</span><span class="p">,</span> <span class="s2">&#34;paul@smith.com&#34;</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>…​with the keyword version:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">send_message_to</span><span class="p">(</span><span class="s2">&#34;sam@sam.com&#34;</span><span class="p">,</span> <span class="ss">bcc: </span><span class="s2">&#34;paul@smith.com&#34;</span><span class="p">,</span> <span class="ss">confirm: </span><span class="kp">false</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>If you adopt these habits, <a href="&lt;em&gt;GHOST_URL&lt;/em&gt;/writing-code-for-your-future-self">future you</a> will thank you when you revisit the code to debug or tack on yet another parameter.</p>
</div>
</div>
</div>
</div>
]]></content:encoded></item><item><title>Love your error messages as thyself</title><link>/post/2022-05-17-learn-your-error-messages-as-thyself/</link><pubDate>Tue, 17 May 2022 07:44:36 +0000</pubDate><guid>/post/2022-05-17-learn-your-error-messages-as-thyself/</guid><description>Stop ignoring error messages and start reading them — it will make you a better developer and help you understand your language from the inside out.</description><content:encoded><![CDATA[<div class="paragraph">
<p>Learn to hate, then love error messages.</p>
</div>
<div class="sect1">
<h2 id="stack-overflowoverflow"><a class="anchor" href="#stack-overflowoverflow"></a>Stack Overflow overflow</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I have lost so much time on Stack Overflow.</p>
</div>
<div class="paragraph">
<p>I mean Stack Overflow is great, and software development knowledge would not be so advanced and so widespread without its great influence. What I mean is that I have often found myself repeating the endless pattern of <em>&#39;Hey, I have an error…​ Wow, so many words…​ Let’s google this. Stack Overflow has it! Let’s see what they say&#39;</em></p>
</div>
<div class="paragraph">
<p>I am not talking about the infamous Stack Overflow copy-paste syndrome, nor am I dismissing the great answers produced by the great developers out ther, but rather about the missing step in the example above: making sense of the error message myself before actually looking for a ready-made answer.</p>
</div>
<div class="paragraph">
<p>Our brain is so quick at taking shortcuts that it often makes us lazy and skip the seemingly unneeded steps our thinking needs to fully develop. Take the example of walking. Although I don’t exactly remember taking my first step in this world, I can imagine it was a movement that required so much concentration - not to say bravery - and coordination that it must have felt quite awkward at the beginning. Today, I don’t even think about it. My brain just orchestrates everything, allowing me to go for a walk and actually think about something else.</p>
</div>
<div class="paragraph">
<p>Think about the first day you typed your first computer program. Think about the way you were thinking at the time. Maybe you are currently learning computer science and many mechanisms experienced developers don’t even think about are steps you consciously take, one by one, in order to reach code quality - or even to write code that actually works.</p>
</div>
<div class="paragraph">
<p>And while learning, we all encountered bugs. The language we were coding in was talking to us with complicated words, and concepts we sometimes did not even know about. We all googled for solutions. And Stack Overflow is so well conceived and maintained that we most certainly found the answer there. And it happened again. Error messages were so hard to understand, so cryptic, sometimes. So we just kept copy-pasting the error messages, and it just kept throwing correct answers at you, which, with a little adaptation, just worked.</p>
</div>
<div class="paragraph">
<p><em>And then, your brain skipped the error-message-reading step.</em></p>
</div>
<div class="paragraph">
<p>But we don’t want to just be very, very, very talented googlers, do we?</p>
</div>
</div>
</div>
<h1 id="rtfem" class="sect0"><a class="anchor" href="#rtfem"></a>RTFEM!</h1>
<div class="paragraph">
<p>Read the f***ing error messages!</p>
</div>
<div class="paragraph">
<p>So I encourage all of you learners to actually take a long look at the error messages that are thrown right in your face just as you were expecting a successful compilation. Take the time to read them. Take the time to look at those weird symbols that show up here and there. And you know what? You may not get to the point quicker at first, but you will gain a deeper knowledge of how your language is actually built, how it works internally. You might look at your fellow programmers increase their skills faster on the surface, but your understanding of error messages will eventually turn you into a Code Jedi Master.</p>
</div>
<div class="paragraph">
<p>What made me really stop overlooking error messages was reading <em>Ruby Under A Microscope</em> by Pat Shaughnessy, a most excellent book about the way Ruby is actually written in C, the way the language parser works and the way it turns the words you write into machine-understandable concepts.</p>
</div>
<div class="paragraph">
<p>Somewhere in the first part of the book that introduces how the parser works, the author talks about language tokenisation, which is - very basically - how the parser takes words and understand how to match them with a feature. And here they were, in a code example, my long-seen-yet-so-little-known error message friends, namely <code>tSTRING</code>, <code>tCONSTANT</code> and <code>tINTEGER</code>.</p>
</div>
<div class="paragraph">
<p>If only I had known what these correspond to before, <a href="https://makandracards.com/makandra/15611-how-to-fix-unexpected-token-error-for-json-parse">error messages such as these</a> would never have had me google for an answer.</p>
</div>
<div class="paragraph">
<p>But how could I know? When you google for ruby tString, you get all sorts of results, mostly skipping the preceding t. In order to get to the real stuff, I should have taken the time to actually read the error messages and wonder:</p>
</div>
<div class="paragraph">
<p>What is the language trying to tell me?</p>
</div>
<div class="paragraph">
<p>And if that sounds awkward, just remember that your programming language is actually a computer program written by other humans, and ask yourself:</p>
</div>
<div class="paragraph">
<p>What is the author of the language telling me to look at?</p>
</div>
<div class="paragraph">
<p>Chances are he is trying to get you to look at features of the language that may not be plain to see, but a little hidden from sight. And if he is trying to have you look at these, you might just as well do it. And learn.</p>
</div>
<div class="sect1">
<h2 id="learn-to-love-your-errormessages"><a class="anchor" href="#learn-to-love-your-errormessages"></a>Learn to love your error messages</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Not only should you read error messages carefully, but you should also take the time to craft yours with love and care. Like I said in an earlier post, <a href="https://moskitohero.com/development/2021/11/21/writing-code-for-your-future-self.html">you should always try to write code with your future self in mind</a>. And I guess the same applies to error messages.</p>
</div>
<div class="paragraph">
<p>Don’t just raise <code>Error</code>, or <code>StandardError</code> in your lib. Actually write your own <code>OddError</code> class. Give it a message. Make it clear. Make it so your user - and that may be the future you - is eager to look at what you coded and understand how it is architectured.</p>
</div>
<div class="paragraph">
<p>An error message must be clear, so it requires your code to be clear, and therefore it requires your programming mind to be clear about what the code is actually doing. Error messages tell something about your self.</p>
</div>
<div class="paragraph">
<p>Error messages are the conversation between the author of a program and his users. As a programmer, you will be either one or the other, in turn, and often both at the same time.</p>
</div>
<div class="paragraph">
<p>Error messages will make you grow while <em>learning</em> software. They will make you grow while <em>using</em> software. They will make you grow while <em>writing</em> software. Do not just dismiss them and skip to the Stack Overflow step.</p>
</div>
</div>
</div>
]]></content:encoded></item><item><title>Writing code for your future self</title><link>/post/2021-11-21-writing-code-for-your-future-self/</link><pubDate>Sun, 21 Nov 2021 07:44:36 +0000</pubDate><guid>/post/2021-11-21-writing-code-for-your-future-self/</guid><description>A set of guidelines to write clean, readable code that you — and your future self — will thank you for.</description><content:encoded><![CDATA[<div class="paragraph">
<p>We all write bad code. Let’s face it. Even if we do our best at writing the most efficient and well-designed code, we all happen to write this dirty method we don’t feel so proud of and dread having to debug next month, or next year.</p>
</div>
<div class="paragraph">
<p>I’m not going to talk about that code, because it’s so easy to spot and there is no need to write blog posts about it. What I’m interested in is code which looks fine when you have finished typing, but will bite you in the back someday. It ends up being hard to maintain, extend or even understand. After years of coding, I have come up with a set of warnings that alert me whenever I am heading for a dead end.</p>
</div>
<div class="sect1">
<h2 id="meaning"><a class="anchor" href="#meaning"></a>Meaning</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Code is language. Even more so when you use a programming language such as Ruby, which is designed to be very expressive. But to me, code begins to smell when it becomes unclear what it really does.</p>
</div>
<div class="sect2">
<h3 id="names"><a class="anchor" href="#names"></a>Names</h3>
<div class="paragraph">
<p>Naming is essential. One of the thing that changes the most in my creation process is probably the name of the classes, methods and variables I design.</p>
</div>
<div class="paragraph">
<p>Humans name things they understand. And the higher the knowledge of an element, the sharper the naming. Renaming my classes in the development process is usually a good sign that I am getting a better idea of what they do or what concept they stand for.</p>
</div>
</div>
<div class="sect2">
<h3 id="method-length"><a class="anchor" href="#method-length"></a>Method length</h3>
<div class="paragraph">
<p>One of the most frequent design patterns we are taught as aspiring OOP developers is to keep methods shorter than a few lines. One caveat, however, is that code ends up scattered all over the place, and you can sometimes lose touch with the lifecycle of your data. This is especially true for classes that are used to build a data structure.</p>
</div>
<div class="paragraph">
<p>For instance, take this class that builds a <code>data</code> hash to be sent to FCM:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="k">module</span> <span class="nn">MobilePush</span>
  <span class="k">class</span> <span class="nc">FcmNotification</span> <span class="o">&lt;</span> <span class="no">BaseNotification</span>

    <span class="k">def</span> <span class="nf">launch</span>
      <span class="c1"># Bootstrap stuff...</span>
      <span class="n">push_service</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">project</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
    <span class="k">end</span>
    <span class="kp">private</span>
      <span class="c1"># Lots of methods...</span>
      <span class="k">def</span> <span class="nf">data</span>
       <span class="p">{</span>
          <span class="ss">notification: </span><span class="n">json_notification</span><span class="p">,</span>
          <span class="ss">recipient: </span><span class="n">recipient_name</span><span class="p">,</span>
          <span class="ss">room: </span><span class="n">room_name</span>
        <span class="p">}</span>
      <span class="k">end</span>
      <span class="c1"># Lots of other methods...</span>
      <span class="k">def</span> <span class="nf">json_notification</span>
        <span class="vi">@notification</span><span class="p">.</span><span class="nf">to_json</span>
      <span class="k">end</span>
      <span class="k">def</span> <span class="nf">recipient_name</span>
        <span class="vi">@recipient</span><span class="p">.</span><span class="nf">name</span>
      <span class="k">end</span>

      <span class="c1"># Maybe a few other methods...</span>
      <span class="k">def</span> <span class="nf">room_name</span>
        <span class="vi">@room</span><span class="p">.</span><span class="nf">name</span>
      <span class="k">end</span>
      <span class="c1"># The rest of the methods...</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><em>Note: This example is a little over-simplified for brevity. But you get the idea.</em></p>
</div>
<div class="paragraph">
<p>I wrote this thinking <em>&#34;Hey that’s smart! Everything is nicely sorted. It really looks like clean code&#34;</em>.</p>
</div>
<div class="paragraph">
<p>Then I took a few day’s break with my family. While I was away, one of my co-workers had to deal with my new code and add a new feature. But he found it unnecessarily abstracted, hard to maintain and extend. And he was right. So I refactored it to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="k">module</span> <span class="nn">MobilePush</span>
  <span class="k">class</span> <span class="nc">FcmNotification</span> <span class="o">&lt;</span> <span class="no">BaseNotification</span>

    <span class="k">def</span> <span class="nf">launch</span>
      <span class="c1"># Bootstrap stuff...</span>
      <span class="n">push_service</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">project</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
    <span class="k">end</span>
    <span class="kp">private</span>
      <span class="c1"># Lots of methods...</span>
      <span class="k">def</span> <span class="nf">data</span>
       <span class="p">{</span>
          <span class="ss">notification: </span><span class="vi">@notification</span><span class="p">.</span><span class="nf">to_json</span><span class="p">,</span>
          <span class="ss">recipient: </span><span class="vi">@recipient</span><span class="p">.</span><span class="nf">name</span><span class="p">,</span>
          <span class="ss">room: </span><span class="vi">@room</span><span class="p">.</span><span class="nf">name</span>
        <span class="p">}</span>
      <span class="k">end</span>
      <span class="c1"># The rest of the methods...</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>So OK, I had to swap out <code>room_name</code> for <code>@room.name</code> in two or three places in the class, because it was also used elsewhere. But I also made my code a little less abstracted. Now, my co-worker knows exactly what data is made of, at a glance.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="stories"><a class="anchor" href="#stories"></a>Stories</h2>
<div class="sectionbody">
<div class="paragraph">
<p>One thing to remember when writing code, is that it is not just meant to be effective and concise. Code is meant to be read by others. Your co-workers, your team leader, and even more crucially, by the person who will be in charge of your once-new, now-legacy codebase.</p>
</div>
<div class="sect2">
<h3 id="one-liners"><a class="anchor" href="#one-liners"></a>One-liners</h3>
<div class="paragraph">
<p>I love one-liners. They are fun, straight to the point, and they showcase the technical skills and the wit of their creators. They are to programming what punchlines, or newspaper headlines are to writing. But who wants to read a whole book written in this way?</p>
</div>
<div class="paragraph">
<p>Even though I sometimes use one-liners in my code, I only do so when I feel confident my successor - or my future self - will be able to make sense out of it easily.</p>
</div>
</div>
<div class="sect2">
<h3 id="be-explicit"><a class="anchor" href="#be-explicit"></a>Be explicit</h3>
<div class="paragraph">
<p>I believe that most code should be explicit and guide the reader with landmarks that will help him or her follow along.</p>
</div>
<div class="paragraph">
<p>For instance, instead of this kind of expression:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="no">Device</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="s1">&#39;last_seen &gt; ?&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">.</span><span class="nf">hour</span><span class="p">.</span><span class="nf">ago</span><span class="p">).</span><span class="nf">where</span><span class="p">(</span><span class="ss">logging: </span><span class="kp">true</span><span class="p">).</span><span class="nf">where</span><span class="p">(</span><span class="ss">notifications: </span><span class="kp">true</span><span class="p">).</span><span class="nf">last</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">topic</span><span class="p">,</span> <span class="n">payload</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>I would rather either use class methods, or scopes in the model, to end up with:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">device</span> <span class="o">=</span> <span class="no">Device</span><span class="p">.</span><span class="nf">active_last</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="nf">hour</span><span class="p">).</span><span class="nf">logging</span><span class="p">.</span><span class="nf">notifying</span><span class="p">.</span><span class="nf">last</span>
<span class="n">device</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">topic</span><span class="p">,</span> <span class="n">payload</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>I’m not stupid. I can understand the first example. But when parsing hundreds of lines of code to find a bug, I can look at this code and instantly tell what it does. No need to make sure I got the &lt; and the &gt; right. This was done once, on the day it was typed, and I can rely on it with confidence because each of these methods is tested and does what it says.</p>
</div>
</div>
<div class="sect2">
<h3 id="be-methodic"><a class="anchor" href="#be-methodic"></a>Be methodic</h3>
<div class="paragraph">
<p>I like to separate intents in what I do with my class. When you tell a story, you first introduce your character with a clear description. Then only you give him an active role in your story. That’s what the code example above is doing. I could also have easily  written:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="no">Device</span><span class="p">.</span><span class="nf">active_last</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="nf">hour</span><span class="p">).</span><span class="nf">logging</span><span class="p">.</span><span class="nf">notifying</span><span class="p">.</span><span class="nf">last</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">topic</span><span class="p">,</span> <span class="n">payload</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>But that’s mixing intents. This line is both querying the model and triggering an action, so you start reading the line thinking: <em>&#34;Oh, he is defining the Device&#34;</em> and finish it thinking <em>&#34;Ah. No, he is sending this device a message&#34;</em>. Your reader should never ever be misguided, even in short, simple assertions like these.</p>
</div>
<div class="paragraph">
<p>I try to separate queries from actions. They are two types of tasks and require two distinct steps in my code.</p>
</div>
<div class="paragraph">
<p>Consider these three sentences:</p>
</div>
<div class="quoteblock">
<blockquote>
<div class="paragraph">
<p>The man in the bar that is old and dirty is talking about yesterday’s soccer results. - messy</p>
</div>
</blockquote>
</div>
<div class="quoteblock">
<blockquote>
<div class="paragraph">
<p>There is a man who is talking in the dirty old bar about yesterday’s soccer results. - clearer</p>
</div>
</blockquote>
</div>
<div class="quoteblock">
<blockquote>
<div class="paragraph">
<p>In the dirty old bar, there is a man. He is talking about yesterday’s soccer results. - crystal clear</p>
</div>
</blockquote>
</div>
<div class="paragraph">
<p>I want my code to be crystal-clear. I want my code reviewer, my successor or my future very-tired-on-a-friday-afternoon self to perfectly get what I am doing with my code.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="tests"><a class="anchor" href="#tests"></a>Tests</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Writing tests helps me identify dependencies. Integration tests often require quite a lot of bootstrapping: a logged in user, a few related entities…​ that’s fine.</p>
</div>
<div class="paragraph">
<p>But I sometimes write tests that rely too much on other models. If you can’t test your <code>Comment</code> model without a <code>Post</code> model, then something may be too tightly coupled in the code, and the relationship between those entities needs to be inquired.</p>
</div>
<div class="paragraph">
<p>Assertions also guide me towards code clarity. I have found that when I have trouble defining an expectation in my test, it usually means that this particular method is not doing something clear enough. It either needs to be split into smaller methods or completely re-thought about.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="a-word-aboutcomments"><a class="anchor" href="#a-word-aboutcomments"></a>A word about comments</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Another sign that code needs to be refactored is comments. Comments mostly indicate that what the program does is unclear. So when I see comments in code, the first thing I do is delete them and figure out what is happening without reading them. And whenever that comes out messy, it’s a good sign that they can all be replaced by a single <code>TODO: refactor</code>.</p>
</div>
<div class="paragraph">
<p>Comments are also often a sign of an external dependency. Typically, you will get this kind of thing:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="c1"># Handle temperature &gt; 21</span>
<span class="c1"># Deal with legacy customer IDs</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The first one might depend on the device you’re dealing with, and that dependency might be addressed by the hardware team.</p>
</div>
<div class="paragraph">
<p>The second one could be deleted by resorting to an inherited class, like <code>LegacyCustomer</code>, which could handle that kind of special user cases and keep the <code>Customer</code> class clean with a predictable and simple interface.</p>
</div>
<div class="paragraph">
<p>The only comments I keep are top comments above class declarations, Yard documentation, a few refactor TODOs and silly, fun meta about the code.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="conclusion"><a class="anchor" href="#conclusion"></a>Conclusion</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I sometimes look at messy code and wonder <em>&#34;who wrote this piece of crap?&#34;</em></p>
</div>
<div class="paragraph">
<p>Let’s see…​ Git blame…​</p>
</div>
<div class="paragraph">
<p><em>Me.</em></p>
</div>
<div class="paragraph">
<p>I don’t like this feeling. I want to feel proud of my code. I want other developers, including my future self, to make sense out of it easily and instantly, and thank me for making the effort of crafting code that makes sense, is easy to debug and maintain.</p>
</div>
<div class="paragraph">
<p>Following this set of guidelines will hopefully help me down that path.</p>
</div>
</div>
</div>
]]></content:encoded></item><item><title>An alternative to the ActiveRecord after_initialize callbacks</title><link>/post/2020-10-08-an-alternative-to-the-activerecord-after-initialize-callbacks/</link><pubDate>Sat, 03 Oct 2020 00:23:33 +0000</pubDate><guid>/post/2020-10-08-an-alternative-to-the-activerecord-after-initialize-callbacks/</guid><description>Avoiding the callback hell in Rails by creating a simple method in the model to initialize associated records.</description><content:encoded><![CDATA[<div class="paragraph">
<p>I was playing with dynamic nested forms with Stimulus today and I stumbled upon a void left by Rails&#39; ActiveRecord callbacks.</p>
</div>
<div class="paragraph">
<p>I have this Caregiver model within a nested form and I need to create it along with a User entity in my form, to be able to populate the fields. The problem is that creating an <code>after_initialize</code> callback (even with <code>:new_record?</code> will break the general behaviour of my app, and I don’t want to run through all the specs and fix FactoryBot issues etc.</p>
</div>
<div class="paragraph">
<p>So I just decided to create a small method in my Caregiver model:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="c1"># caregiver.rb</span>

<span class="k">def</span> <span class="nf">init_with_user</span>
  <span class="nb">self</span><span class="p">.</span><span class="nf">build_user</span>
  <span class="nb">self</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Then I just need to call it in my view like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="erb"><span class="cp">&lt;%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">fields_for</span> <span class="ss">:caregivers</span><span class="p">,</span> <span class="n">caregiver</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">init_with_user</span><span class="p">,</span> <span class="ss">child_index: </span><span class="s1">&#39;TEMPLATE_RECORD&#39;</span> <span class="k">do</span> <span class="o">|</span><span class="n">cf</span><span class="o">|</span> <span class="cp">%&gt;</span>
  <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="s1">&#39;caregiver_fields&#39;</span><span class="p">,</span> <span class="ss">cf: </span><span class="n">cf</span> <span class="cp">%&gt;</span>
<span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>This makes the code in my view simpler, more explicit, while avoiding the dreaded callback hell.</p>
</div>
]]></content:encoded></item><item><title>Chaining conditions in regular expressions</title><link>/post/2020-10-03-chaining-conditions-in-regular-expressions/</link><pubDate>Sat, 03 Oct 2020 00:23:33 +0000</pubDate><guid>/post/2020-10-03-chaining-conditions-in-regular-expressions/</guid><description>Unleash the full power of regular expressions by chaining conditions together.</description><content:encoded><![CDATA[<div class="imageblock">
<div class="content">
<img src="/assets/img/regexp.jpg" alt="Regexp hell"/>
</div>
</div>
<div class="paragraph">
<p>I recently had to make a semi-complex check on a string to validate it.</p>
</div>
<div class="paragraph">
<p>Basically, I have this model method which produces a serial number based on the ID of the object. Valid returned values for this method are <code>L00000002</code>, <code>L00000587</code> or <code>L00014522</code>. In short, they should be constituted of a capital <code>L</code> followed by 8 digits composed of the <code>id</code> of the object padded with zeros.</p>
</div>
<div class="paragraph">
<p>So I had to find a way to simply created a matcher for this to use in my model spec. I could have built two expectations, one for the length, and one for the composition. But I just decided to believe that regular expressions are powerful enough to do both at the same time. So I headed to <a href="https://rubular.com">rubular</a> and started fiddling and googling around.</p>
</div>
<div class="paragraph">
<p>The solution I came up with was the following (with an <code>id</code> of <code>12</code>, for instance):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="regexp">/^L(?=[0-9]{8}$)0*12$/</code></pre>
</div>
</div>
<div class="paragraph">
<p>What this does, is - after the starting <code>^L</code> character - create a condition matching whatever follows the <code>?=</code> inside the parentheses. If this condition is true, then the rest of the expression is read. So I just check for any digit (<code>[0-9]</code> - it could have been <code>\d</code> but readability make the first option a better fit IMHO) exacty 8 times (<code>{8}</code>) and then the end of the string with <code>$</code>. If this is matched, then I check any number of zeros (<code>0*</code>) followed by the id (<code>12</code>) and the end of the string (<code>$</code>).</p>
</div>
<div class="paragraph">
<p>Now I could use this expression in my spec, using the <code>Regexp.escape</code> method on my model’s <code>id</code> within a string interpolation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="c1"># spec/models/my_model_spec.rb</span>
<span class="n">describe</span> <span class="s2">&#34;serial_number&#34;</span> <span class="k">do</span>
  <span class="n">let</span><span class="p">(</span><span class="ss">:my_model</span><span class="p">)</span> <span class="p">{</span> <span class="n">create</span><span class="p">(</span><span class="ss">:my_model</span><span class="p">)</span> <span class="p">}</span> <span class="c1"># I use the FactoryBot gem</span>

  <span class="n">it</span> <span class="s2">&#34;returns a valid serial number&#34;</span> <span class="k">do</span>
    <span class="n">expect</span><span class="p">(</span><span class="n">my_model</span><span class="p">.</span><span class="nf">serial_number</span><span class="p">).</span><span class="nf">to</span> <span class="n">match</span><span class="p">(</span><span class="sr">/^L(?=[0-9]{8}$)0*</span><span class="si">#{</span><span class="no">Regexp</span><span class="p">.</span><span class="nf">escape</span><span class="p">(</span><span class="n">my_model</span><span class="p">.</span><span class="nf">id</span><span class="p">.</span><span class="nf">to_s</span><span class="p">)</span><span class="si">}</span><span class="sr">$/</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="olist lowerroman">
<ol class="lowerroman" type="i">
<li>
<p>and create the corresponding method like so:</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre># app/models/my_model.rb
def serial_number
  &#34;L#{id.to_s.rjust(8, &#34;0&#34;)}&#34;
end</pre>
</div>
</div>
<div class="paragraph">
<p>Don’t you just love regular expressions?</p>
</div>
]]></content:encoded></item><item><title>Prevent Devise from sending confirmation emails</title><link>/post/2020-01-26-prevent-devise-from-sending-confirmation-emails/</link><pubDate>Sun, 26 Jan 2020 00:00:00 +0000</pubDate><guid>/post/2020-01-26-prevent-devise-from-sending-confirmation-emails/</guid><description>When you need to import users into a new Rails app using Devise, you may want to skip sending confirmation emails. Here’s how to do it by overriding an instance method in the User model.</description><content:encoded><![CDATA[<div class="imageblock">
<div class="content">
<img src="/assets/img/message-in-a-bottle.jpg" alt="Image par Antonios Ntoumas de Pixabay"/>
</div>
</div>
<div class="paragraph">
<p>I am about to release a huge rails project I have been working on for quite a
while. This project is meant to replace an old app that manages a database of
customers with emails. The new rails project uses Devise for authentication.</p>
</div>
<div class="paragraph">
<p>Before we push the final update to the production server, we need to find a way to import the users without sending confirmation emails, but still keep them unconfirmed until they actually login to the new system and provide a password. New registrations should also still be confirmable.</p>
</div>
<div class="paragraph">
<p>So I had to find a way to override an instance method. This is easy to do with a
simple module:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="c1"># Module to be included in a User instance whenever we don&#39;t want to send an email</span>
<span class="c1"># Useful when importing users or for testing</span>
<span class="k">module</span> <span class="nn">SkipConfirmationEmail</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">included</span><span class="p">(</span><span class="n">base</span><span class="p">)</span>
    <span class="n">base</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="ss">:include</span><span class="p">,</span> <span class="no">InstanceMethods</span><span class="p">)</span>

    <span class="n">base</span><span class="p">.</span><span class="nf">class_eval</span> <span class="k">do</span>
      <span class="kp">alias_method</span> <span class="ss">:send_confirmation_instructions</span><span class="p">,</span> <span class="ss">:return_false</span>
    <span class="k">end</span>
  <span class="k">end</span>

  <span class="c1"># Instance methods</span>
  <span class="k">module</span> <span class="nn">InstanceMethods</span>
    <span class="k">def</span> <span class="nf">return_false</span>
      <span class="kp">false</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>What this basically does is alias the <code>send_confirmation_instructions</code> method to
a new <code>return_false</code> instance method we can inject into our model like this :</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span>
<span class="n">user</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="ss">:include</span><span class="p">,</span> <span class="no">SkipConfirmationEmail</span><span class="p">)</span>

<span class="n">user</span><span class="p">.</span><span class="nf">send_confirmation_instructions</span>
<span class="c1">#&gt; false</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Therefore, my users will still have to confirm their account at first login on
the new system, but won’t be notified when I import the database a few days
before launch.</p>
</div>
<div class="paragraph">
<p>This can easily be adapted to serveral use cases, whenever you need to override
an instance method in an exisiting Ruby class, as seen <a href="https://gist.github.com/bluefuton/5851093">in this GitHub gist</a>.</p>
</div>
]]></content:encoded></item></channel></rss>