<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://bearandgiraffe.com/feed/ruby-on-rails.xml" rel="self" type="application/atom+xml" /><link href="https://bearandgiraffe.com/" rel="alternate" type="text/html" /><updated>2026-11-21T19:39:02+00:00</updated><id>https://bearandgiraffe.com/feed/ruby-on-rails.xml</id><title type="html">Bear &amp;amp; Giraffe | Ruby-on-rails</title><subtitle>Fractional CTO and senior engineering leadership for startups. We architect scalable systems and take products from MVP to mature infrastructure.</subtitle><entry><title type="html">To ViewComponent or not to ViewComponent</title><link href="https://bearandgiraffe.com/blog/to-viewcomponent-or-not-to-viewcomponent/" rel="alternate" type="text/html" title="To ViewComponent or not to ViewComponent" /><published>2023-03-22T18:38:20+00:00</published><updated>2023-03-22T18:38:20+00:00</updated><id>https://bearandgiraffe.com/blog/to-viewcomponent-or-not-to-viewcomponent</id><content type="html" xml:base="https://bearandgiraffe.com/blog/to-viewcomponent-or-not-to-viewcomponent/"><![CDATA[<figure>
  <img src="/assets/images/blog/to-viewcomponent-or-not-to-viewcomponent/1.png" alt="" width="1200" height="424" loading="lazy" />
</figure>

<p>Github is one of the largest Ruby on Rails applications, with a complex infrastructure, backend, and frontend. The UI that powers Github is rich and handles complex inline interactions, so it’s natural that Github would create its own frontend framework that works with Rails. Enter the <a href="https://viewcomponent.org/">ViewComponent</a> library.</p>

<p>ViewComponent is defined as:</p>

<blockquote>
  <p>A framework for creating reusable, testable &amp; encapsulated view components, built to integrate seamlessly with Ruby on Rails.</p>
</blockquote>

<p>To a seasoned Rails dev, this might trigger some questions, like doesn’t Rails already have a way to write reusable, testable views? Wouldn’t this be achieved using partials and view helpers? What is ViewComponent trying to achieve that Rails doesn’t already have baked in?</p>

<p>Maybe the answer in this part of the docs:</p>

<blockquote>
  <p>Think of ViewComponents as an evolution of the presenter pattern, inspired by <a href="https://reactjs.org/docs/react-component.html">React</a>. A ViewComponent is a Ruby object and template</p>
</blockquote>

<p>Hmmm… do we actually want to bring “React” into Ruby and Ruby on Rails. The great thing about the Ruby community is that we already have plenty of ways to do things the right way, so is this something born out of the hype behind frontend frameworks like React? Or is there really something worth exploring?</p>

<p>If we keep reading the docs, we land on something interesting:</p>

<blockquote>
  <p>Based on several <a href="https://github.com/viewcomponent/view_component/blob/main/performance/partial_benchmark.rb">benchmarks</a>, ViewComponents are ~10x faster than partials in real-world use-cases.</p>
</blockquote>

<blockquote>
  <p>The primary optimization is pre-compiling all ViewComponent templates at application boot, instead of at runtime like traditional Rails views.</p>
</blockquote>

<p>Is this true? That might be a great value if that’s the case. Well, we can run the benchmark tests ourselves and validate that claim.</p>

<p>First, clone the repo:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone https://github.com/ViewComponent/view_component.git
</code></pre></div></div>

<p>then <code class="language-plaintext highlighter-rouge">cd</code> into the directory and install the dependencies:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cd </span>view_component
bundle 
</code></pre></div></div>

<p><strong>Note:</strong> the <code class="language-plaintext highlighter-rouge">main</code> branch might have change that break the benchmark command. So you might want to use a specific branch or tag. At the time of writing this post, the most recent stable branch<code class="language-plaintext highlighter-rouge">v2.82.0</code>.</p>

<p>Then run the rake command provided with the project:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>rake partial_benchmark
</code></pre></div></div>

<p>To find out which <code class="language-plaintext highlighter-rouge">rake</code> commands are available you can run <code class="language-plaintext highlighter-rouge">rake -T</code> from inside the project.</p>

<p>The output we get is the following:</p>

<pre><code class="language-output">Warming up --------------------------------------
           component   476.000  i/100ms
              inline   565.000  i/100ms
             partial    86.000  i/100ms
Calculating -------------------------------------
           component      4.634k (± 2.9%) i/s -     46.648k in  10.074332s
              inline      5.402k (± 3.8%) i/s -     54.240k in  10.055319s
             partial    870.345  (± 2.8%) i/s -      8.772k in  10.087184s

Comparison:
              inline:     5402.4 i/s
           component:     4634.4 i/s - 1.17x  (± 0.00) slower
             partial:      870.3 i/s - 6.21x  (± 0.00) slower
</code></pre>

<p>According to this, partials are 6.2x slower that inline ViewComponents. That is not 10x! But also, you’re more likely to use regular ViewComponents as opposed to inline ones. So how do partials compare to that?</p>

<p>You can try to use the numbers provided and calculate the difference, or more easily, just update the benchmark file to remove inline components from the comparison:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># performance/partial_benchmark.rb</span>

<span class="c1"># ...</span>

<span class="no">Benchmark</span><span class="p">.</span><span class="nf">ips</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">time</span> <span class="o">=</span> <span class="mi">10</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">warmup</span> <span class="o">=</span> <span class="mi">2</span>

  <span class="n">x</span><span class="p">.</span><span class="nf">report</span><span class="p">(</span><span class="s2">"component"</span><span class="p">)</span> <span class="p">{</span> <span class="n">controller_view</span><span class="p">.</span><span class="nf">render</span><span class="p">(</span><span class="no">Performance</span><span class="o">::</span><span class="no">NameComponent</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="ss">name: </span><span class="s2">"Fox Mulder"</span><span class="p">))</span> <span class="p">}</span>
  <span class="c1"># x.report("inline") { controller_view.render(Performance::InlineComponent.new(name: "Fox Mulder")) }</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">report</span><span class="p">(</span><span class="s2">"partial"</span><span class="p">)</span> <span class="p">{</span> <span class="n">controller_view</span><span class="p">.</span><span class="nf">render</span><span class="p">(</span><span class="s2">"partial"</span><span class="p">,</span> <span class="ss">name: </span><span class="s2">"Fox Mulder"</span><span class="p">)</span> <span class="p">}</span>

  <span class="n">x</span><span class="p">.</span><span class="nf">compare!</span>
<span class="k">end</span>
</code></pre></div></div>

<p>and then re-run the <code class="language-plaintext highlighter-rouge">rake</code> task. The numbers I got are:</p>

<pre><code class="language-output">Warming up --------------------------------------
           component   480.000  i/100ms
             partial    83.000  i/100ms
Calculating -------------------------------------
           component      4.665k (± 2.0%) i/s -     47.040k in  10.087090s
             partial    870.022  (± 3.1%) i/s -      8.715k in  10.027468s

Comparison:
           component:     4665.3 i/s
             partial:      870.0 i/s - 5.36x  (± 0.00) slower
</code></pre>

<p>So ViewComponents are actually 5x faster than partials. That’s half of 10x. But that’s still a significant speed improvement.</p>

<p>Is it possible that this improvement in speed comes at a cost? Perhaps in terms of memory, since ViewComponents are extra ruby classes and HTML templates that you wouldn’t have in a typical Rails application? That’s easy to test. We can improve the benchmarks to include memory usage.</p>

<p>Let’s add the <code class="language-plaintext highlighter-rouge">benchmark-memory</code> <a href="https://github.com/michaelherold/benchmark-memory">gem</a> as a new development dependency to the project, run <code class="language-plaintext highlighter-rouge">bundle</code> to install it, and update the performance script, by adding the following:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">require</span> <span class="s2">"benchmark/memory"</span>

<span class="no">Benchmark</span><span class="p">.</span><span class="nf">memory</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">report</span><span class="p">(</span><span class="s2">"component"</span><span class="p">)</span> <span class="p">{</span> <span class="n">controller_view</span><span class="p">.</span><span class="nf">render</span><span class="p">(</span><span class="no">Performance</span><span class="o">::</span><span class="no">NameComponent</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="ss">name: </span><span class="s2">"Fox Mulder"</span><span class="p">))</span> <span class="p">}</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">report</span><span class="p">(</span><span class="s2">"partial"</span><span class="p">)</span> <span class="p">{</span> <span class="n">controller_view</span><span class="p">.</span><span class="nf">render</span><span class="p">(</span><span class="s2">"partial"</span><span class="p">,</span> <span class="ss">name: </span><span class="s2">"Fox Mulder"</span><span class="p">)</span> <span class="p">}</span>

  <span class="n">x</span><span class="p">.</span><span class="nf">compare!</span>
<span class="k">end</span>
</code></pre></div></div>

<p>We get the following results:</p>

<pre><code class="language-output">Calculating -------------------------------------
           component    42.256k memsize (   232.000  retained)
                       510.000  objects (     3.000  retained)
                         2.000  strings (     0.000  retained)
             partial   143.437k memsize (    80.000  retained)
                         1.682k objects (     2.000  retained)
                        18.000  strings (     0.000  retained)

Comparison:
           component:      42256 allocated
             partial:     143437 allocated - 3.39x more
</code></pre>

<p>So partials are 5x slower and use up at least 3x more memory? Wow. That’s definitely a good value proposition to consider.</p>

<p>I do have to say that there are a few things I do not like about ViewComponent, but it’s mostly a superficial thing. I do not like that we have a new directory to add view logic under <code class="language-plaintext highlighter-rouge">app/view_components</code> (in addition to <code class="language-plaintext highlighter-rouge">app/helpers</code> and <code class="language-plaintext highlighter-rouge">app/views</code>). I also don’t like that by default every component is going to have 2 new files, all organized at the same level under the <code class="language-plaintext highlighter-rouge">app/view_components</code> directory, like so:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>app/view_components/
  -- view_component1.html
  -- view_component1.rb
  -- view_component2.html
  -- view_component2.rb
  -- view_component3.html
  -- view_component3.rb
  -- view_component4.html
  -- view_component4.rb
...
  -- view_componentX.html
  -- view_componentX.rb
</code></pre></div></div>

<p>That just becomes tough on the eyes.</p>

<p>I’d like to see the performance and memory improvements somehow introduced to Rails proper. And it would be much nicer if there was consolidation on the view end of things, like perhaps getting rid of view helpers in favor of view components. That said, ViewComponent might be worth checking out if you have a complex UI. I’d recommend waiting to do so until it’s warranted. Your application might not need the performance or memory improvements. So weigh the pros and cons of introducing a new library to the projects with the benefits it provides. It could very well be that with some caching and a bit of optimization in some areas of your app, the performance needs are negated, and thus using ViewComponent not clearly beneficial.</p>

<p>One last thing to add: It’s still early for ViewComponent. I can see extra benefits surfacing as the project progresses. For example, <a href="https://primer.style/view-components/">Primer</a> is a very nascent project that introduces reusable components, similar to how Bootstrap or Flowbit/Tailwind CSS introduce UI components. Once it’s mature enough, it might help developers speed up their development time for complex UI components in Rails.</p>

<p>So be on the lookout for new features, new benefits, and other wonderful things from the Github team and ViewComponent.</p>

<p>Have you used ViewComponent? If so, how do you like it?</p>]]></content><author><name></name></author><category term="ruby-on-rails" /><category term="rails" /><category term="viewcomponent" /><summary type="html"><![CDATA[Github is one of the largest Ruby on Rails applications, with a complex infrastructure, backend, and frontend. The UI that powers Github is rich and…]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://bearandgiraffe.com/assets/images/blog/to-viewcomponent-or-not-to-viewcomponent/1.png" /><media:content medium="image" url="https://bearandgiraffe.com/assets/images/blog/to-viewcomponent-or-not-to-viewcomponent/1.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Rails: Join on polymorphic association</title><link href="https://bearandgiraffe.com/blog/rails-join-on-polymorphic-association/" rel="alternate" type="text/html" title="Rails: Join on polymorphic association" /><published>2022-10-21T19:43:26+00:00</published><updated>2022-10-21T19:43:26+00:00</updated><id>https://bearandgiraffe.com/blog/rails-join-on-polymorphic-association</id><content type="html" xml:base="https://bearandgiraffe.com/blog/rails-join-on-polymorphic-association/"><![CDATA[<figure>
  <img src="/assets/images/blog/rails-join-on-polymorphic-association/1.jpg" alt="" width="560" height="240" loading="lazy" />
</figure>

<p>I recently had to come up with a query that involved joining on a polymorphic association, so naturally I Googled how best to implement such a solution and happened upon the following 2 articles:</p>

<p><a class="link-card" href="https://veelenga.github.io/joining-polymorphic-associations/">
  <span class="link-card__title">Joining polymorphic associations in ActiveRecord</span>
  <span class="link-card__description">Polymorphic associations in ActiveRecord allow to belong to more than one model on a single associations. The mechanism…</span>
</a></p>

<p>and</p>

<p><a class="link-card" href="https://www.ananunesdasilva.com/posts/polymorphic-joins-in-activerecord">
  <span class="link-card__title">Polymorphic joins in Active Record</span>
  <span class="link-card__description">In Active Record, you can use polymorphic associations to allow a model to belong to more than one other model, on a…</span>
</a></p>

<p>and based on those articles, I chose to go with the scoped <code class="language-plaintext highlighter-rouge">belongs_to</code> solution.</p>

<p>Let’s take Ana’s example to illustrate what I mean. Given that we have the following models:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Booking</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="n">belongs_to</span> <span class="ss">:bookable</span><span class="p">,</span> <span class="ss">polymorphic: </span><span class="kp">true</span>
<span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Accommodation</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="n">has_many</span> <span class="ss">:bookings</span><span class="p">,</span> <span class="ss">as: :bookable</span>
<span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Office</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="n">has_many</span> <span class="ss">:bookings</span><span class="p">,</span> <span class="ss">as: :bookable</span>
<span class="k">end</span>
</code></pre></div></div>

<p>we can update the <code class="language-plaintext highlighter-rouge">Booking</code> model to:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Booking</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="n">belongs_to</span> <span class="ss">:bookable</span><span class="p">,</span> <span class="ss">polymorphic: </span><span class="kp">true</span>
  <span class="n">belongs_to</span> <span class="ss">:accommodation</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">where</span><span class="p">(</span><span class="ss">bookings: </span><span class="p">{</span> <span class="ss">bookable_type: </span><span class="s1">'Accommodation'</span> <span class="p">})</span> <span class="p">},</span> <span class="ss">foreign_key: </span><span class="s1">'bookable_id'</span>
  <span class="n">belongs_to</span> <span class="ss">:office</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">where</span><span class="p">(</span><span class="ss">bookings: </span><span class="p">{</span> <span class="ss">bookable_type: </span><span class="s1">'Office'</span> <span class="p">})</span> <span class="p">},</span> <span class="ss">foreign_key: </span><span class="s1">'bookable_id'</span>
<span class="k">end</span>
</code></pre></div></div>

<p>and now we can create a query that includes a nested join based on the association between <code class="language-plaintext highlighter-rouge">Booking</code> and one of the <code class="language-plaintext highlighter-rouge">bookable</code> models.</p>

<p>Example:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="n">has_many</span> <span class="ss">:bookings</span>
<span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="no">User</span><span class="p">.</span><span class="nf">joins</span><span class="p">(</span><span class="ss">bookings: </span><span class="p">[</span> <span class="ss">:office</span> <span class="p">])</span>
  <span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">offices: </span><span class="p">{</span> <span class="ss">zip_code: </span><span class="mi">90210</span> <span class="p">})</span>
</code></pre></div></div>

<p>Cool.</p>

<p>However, when implementing this solution, I ran into an issue that was not mentioned in those articles. My tests started failing with an error that looks like this:</p>

<pre><code class="language-output">ActiveRecord::StatementInvalid:
        PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "bookings"
        LINE 1: ...bookings" WHERE "office"."id" = 4484 AND ...
                                                                     ^
      # [REDACTED]
      # -e:1:in `&lt;main&gt;'
      # ------------------
      # --- Caused by: ---
      # PG::UndefinedTable:
      #   ERROR:  missing FROM-clause entry for table "bookings"
      #   LINE 1: ...bookings" WHERE "office"."id" = 4484 AND  ...
      #
</code></pre>

<p>One weird thing I noticed was that the error contains references to <code class="language-plaintext highlighter-rouge">FactoryBot</code> and wondered what the connection was. It wasn’t obvious at first why my tests were suddenly failing, when they weren’t even referencing this new association or new code.</p>

<p>After staring at the issue for a couple of hours, and trying to track down the cause, I remembered that one thing that tends to cause headaches with <code class="language-plaintext highlighter-rouge">belongs_to</code> association is their <code class="language-plaintext highlighter-rouge">required</code> nature by default since Rails 5. So, I made a simple adjustment, I added the <code class="language-plaintext highlighter-rouge">optional: true</code> option to the association:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Booking</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="n">belongs_to</span> <span class="ss">:bookable</span><span class="p">,</span> <span class="ss">polymorphic: </span><span class="kp">true</span>
  <span class="o">...</span>
  <span class="n">belongs_to</span> <span class="ss">:office</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">where</span><span class="p">(</span><span class="ss">bookings: </span><span class="p">{</span> <span class="ss">bookable_type: </span><span class="s1">'Office'</span> <span class="p">})</span> <span class="p">},</span> <span class="ss">foreign_key: </span><span class="s1">'bookable_id'</span><span class="p">,</span> <span class="ss">optional: </span><span class="kp">true</span>
<span class="k">end</span>
</code></pre></div></div>

<p>and everything went back to working as usual.</p>

<p>What I figured was that the original code was still creating a <code class="language-plaintext highlighter-rouge">Booking</code> record with a <code class="language-plaintext highlighter-rouge">bookable</code> association and will never directly reference the <code class="language-plaintext highlighter-rouge">office</code> association in the creation/updating process. Which means that marking that association as optional was the right approach.</p>

<p>I hope this helps.</p>

<p>Cheers!</p>]]></content><author><name></name></author><category term="ruby-on-rails" /><category term="rails" /><category term="ruby" /><summary type="html"><![CDATA[I recently had to come up with a query that involved joining on a polymorphic association, so naturally I Googled how best to implement such a solution…]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://bearandgiraffe.com/assets/images/blog/rails-join-on-polymorphic-association/1.jpg" /><media:content medium="image" url="https://bearandgiraffe.com/assets/images/blog/rails-join-on-polymorphic-association/1.jpg" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Rails: I18n in mailer layout</title><link href="https://bearandgiraffe.com/blog/rails-i18n-in-mailer-layout/" rel="alternate" type="text/html" title="Rails: I18n in mailer layout" /><published>2019-03-26T16:01:00+00:00</published><updated>2019-03-26T16:01:00+00:00</updated><id>https://bearandgiraffe.com/blog/rails-i18n-in-mailer-layout</id><content type="html" xml:base="https://bearandgiraffe.com/blog/rails-i18n-in-mailer-layout/"><![CDATA[<figure>
  <img src="/assets/images/blog/rails-i18n-in-mailer-layout/1.png" alt="" width="826" height="456" loading="lazy" />
</figure>

<p>Recently I had a simple task to do in a Ruby on Rails application. The style of the emails needed to show the same subject as a heading in the body of the email. Simple task, right? Sure, until you actually try it and realize that there is not a built in way to do it. It is still a quick fix, so let’s go through it.</p>

<p>The first instinct is to add a line like this to <code class="language-plaintext highlighter-rouge">views/layouts/mailer.html.erb</code> :</p>

<div class="language-erb highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;h1&gt;</span><span class="cp">&lt;%=</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span><span class="p">(</span><span class="s1">'.subject'</span><span class="p">)</span> <span class="cp">%&gt;</span><span class="nt">&lt;/h1&gt;</span>
</code></pre></div></div>

<p>What this is supposed to do is to get the <code class="language-plaintext highlighter-rouge">subject</code> at the relative scope to where the code is being executed. Typically that would map to the <strong>file</strong> you’re calling it from and get you the correct scope. So if you had this line in <code class="language-plaintext highlighter-rouge">views/custom_mailer/notification.html.erb</code> it will look for this scope: <code class="language-plaintext highlighter-rouge">customer_mailer.noticiation.subject</code> in your <code class="language-plaintext highlighter-rouge">yml</code> file. The problem in this case is that the call to the translation is done from a layout file, and it will not pick up the scope of the final view it will be used in. So the result of our code above would be something like this: <code class="language-plaintext highlighter-rouge">Missing translation: :subject</code>.</p>

<p>So what do we do? What we will need to supply is a scope based on the mailer class and the action. Can we get those somehow? My quick instinct is to go look at the <code class="language-plaintext highlighter-rouge">ActionMailer</code> guides and see what we can come up with: <a href="https://api.rubyonrails.org/classes/ActionMailer/Base.html">https://api.rubyonrails.org/classes/ActionMailer/Base.html</a></p>

<p>After a quick glance, we see a method called <code class="language-plaintext highlighter-rouge">default_i18n_subject</code> that might be helpful. Luckily it has both things we need <code class="language-plaintext highlighter-rouge">i18n</code> and <code class="language-plaintext highlighter-rouge">subject</code>. How about them apples! This is what the code inside of that method looks like (click on “Show” to see the source):</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">default_i18n_subject</span><span class="p">(</span><span class="n">interpolations</span> <span class="o">=</span> <span class="p">{})</span> <span class="c1"># :doc:</span>
  <span class="n">mailer_scope</span> <span class="o">=</span> <span class="nb">self</span><span class="p">.</span><span class="nf">class</span><span class="p">.</span><span class="nf">mailer_name</span><span class="p">.</span><span class="nf">tr</span><span class="p">(</span><span class="s2">"/"</span><span class="p">,</span> <span class="s2">"."</span><span class="p">)</span>
  <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span><span class="p">(</span><span class="ss">:subject</span><span class="p">,</span> <span class="n">interpolations</span><span class="p">.</span><span class="nf">merge</span><span class="p">(</span><span class="ss">scope: </span><span class="p">[</span><span class="n">mailer_scope</span><span class="p">,</span> <span class="n">action_name</span><span class="p">],</span> <span class="ss">default: </span><span class="n">action_name</span><span class="p">.</span><span class="nf">humanize</span><span class="p">))</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Interesting. So that gives us a lead. The method takes in a param called <code class="language-plaintext highlighter-rouge">interpolations</code> which is probably a way to override some options to the <code class="language-plaintext highlighter-rouge">t</code> method. Let’s ignore that. What we care about is this: <code class="language-plaintext highlighter-rouge">scope: [mailer_scope, action_name]</code>. We can see that <code class="language-plaintext highlighter-rouge">mailer_scope</code> is defined right above. <code class="language-plaintext highlighter-rouge">action_name</code> however looks like a helper method that might or might not be available to us in the view. Let’s try it and see what happens.</p>

<div class="language-erb highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;%</span> <span class="n">mailer_scope</span> <span class="o">=</span> <span class="nb">self</span><span class="p">.</span><span class="nf">class</span><span class="p">.</span><span class="nf">mailer_name</span><span class="p">.</span><span class="nf">tr</span><span class="p">(</span><span class="s2">"/"</span><span class="p">,</span> <span class="s2">"."</span><span class="p">)</span> <span class="cp">%&gt;</span>
<span class="nt">&lt;h1&gt;</span><span class="cp">&lt;%=</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span><span class="p">(</span><span class="ss">:subject</span><span class="p">,</span> <span class="ss">scope: </span><span class="p">[</span><span class="n">mailer_scope</span><span class="p">,</span> <span class="n">action_name</span><span class="p">])</span> <span class="cp">%&gt;</span><span class="nt">&lt;/h1&gt;</span>
</code></pre></div></div>

<p>Well, that doesn’t work. Why is that? hmmmm…<br />
`self.class` in the original code referred to the mailer class that inherits from <code class="language-plaintext highlighter-rouge">ActionMailer::Base</code> whereas in the view it would refer to something else, which means <code class="language-plaintext highlighter-rouge">mailer_name</code> would not be available as a method to call on it. We need another way to get the mailer name while inside of the view.</p>

<p>After a bit of googling I realized that mailers act the same way as controllers, which means that <code class="language-plaintext highlighter-rouge">action_name</code> will be available to us as a view helper BUT for some reason we do not get the <code class="language-plaintext highlighter-rouge">controller_name</code> helper 🤔. No worries, we can extract that using the following code:</p>

<div class="language-erb highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;%</span> <span class="n">mailer_scope</span> <span class="o">=</span> <span class="nb">self</span><span class="p">.</span><span class="nf">controller</span>
  <span class="p">.</span><span class="nf">class</span>
  <span class="p">.</span><span class="nf">name</span>
  <span class="p">.</span><span class="nf">underscore</span>
  <span class="p">.</span><span class="nf">tr</span><span class="p">(</span><span class="s1">'/'</span><span class="p">,</span> <span class="s1">'.'</span><span class="p">)</span>
<span class="cp">%&gt;</span>
</code></pre></div></div>

<div class="language-erb highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;h1&gt;</span>
  <span class="cp">&lt;%=</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span><span class="p">(</span><span class="ss">:subject</span><span class="p">,</span> <span class="ss">scope: </span><span class="p">[</span> <span class="n">mailer_scope</span><span class="p">,</span> <span class="n">action_name</span> <span class="p">])</span> <span class="cp">%&gt;</span>
<span class="nt">&lt;/h1&gt;</span>
</code></pre></div></div>

<p>There you have it, now you’re able to use scoped internationalization from inside of the mailer layout. Was that useful? What similar tricks have you used in the past? Please share in the comments.</p>]]></content><author><name></name></author><category term="ruby-on-rails" /><category term="rails" /><category term="i18n" /><category term="email" /><summary type="html"><![CDATA[Recently I had a simple task to do in a Ruby on Rails application. The style of the emails needed to show the same subject as a heading in the body of the…]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://bearandgiraffe.com/assets/images/blog/rails-i18n-in-mailer-layout/1.png" /><media:content medium="image" url="https://bearandgiraffe.com/assets/images/blog/rails-i18n-in-mailer-layout/1.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Rails: Start multiple processes with one command in development</title><link href="https://bearandgiraffe.com/blog/rails-start-multiple-processes-with-one-command-in-development/" rel="alternate" type="text/html" title="Rails: Start multiple processes with one command in development" /><published>2018-01-22T17:01:01+00:00</published><updated>2018-01-22T17:01:01+00:00</updated><id>https://bearandgiraffe.com/blog/rails-start-multiple-processes-with-one-command-in-development</id><content type="html" xml:base="https://bearandgiraffe.com/blog/rails-start-multiple-processes-with-one-command-in-development/"><![CDATA[<p>Any app that goes beyond the very basics will probably have many components that it depends on. Even the smallest Rails app will probably have some background job handler (like sidekiq) that takes care of things like sending emails asynchronously or calling analytics APIs without blocking the user’s actions. (<strong>NB:</strong> If you don’t do that already in your app, you should definitely look into it, we’ve written a post about how you can easily add it to your app <a href="/blog/rails-non-blocking-analytics/">here</a>.)</p>

<p>So how do you handle making sure that all of the services you need for your app to function are running in development? Do you manually start each one? That must be a pain. Especially in some cases where you figure out that you forgot to spin up a process after the fact, and now you have to go through the same work you just went through again. It’s a minor annoyance, but once it happens the second, third, or fourth time you start thinking about ways to automate that part.</p>

<p>Well, there’s an easy way to do that. If you’ve ever deployed to Heroku, you probably have had to setup a <code class="language-plaintext highlighter-rouge">Procfile</code> that looks something like this:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">web</span><span class="pi">:</span>    <span class="s">bundle exec puma -C config/puma.rb</span>
<span class="na">worker</span><span class="pi">:</span> <span class="s">bundle exec sidekiq -e production -C config/sidekiq.yml</span>
</code></pre></div></div>

<p>What the <code class="language-plaintext highlighter-rouge">Procfile</code> is doing is behaving a like a manifest file and specifying that we need a <code class="language-plaintext highlighter-rouge">web</code> process which is started using the <code class="language-plaintext highlighter-rouge">bundle exec puma -C config/puma.rb</code>and a <code class="language-plaintext highlighter-rouge">worker</code> process that executes the <code class="language-plaintext highlighter-rouge">bundle exec sidekiq -e production -C config/sidekiq.yml</code> command.</p>

<p>We can add as many of these processes as we want, using the sidekiq example, we can have multiple workers that handle different queues:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">web</span><span class="pi">:</span>     <span class="s">bundle exec puma -C config/puma.rb</span>
<span class="na">worker1</span><span class="pi">:</span> <span class="s">bundle exec sidekiq -e production -C config/sidekiq.yml -q mailers -q analytics</span>
<span class="na">worker2</span><span class="pi">:</span> <span class="s">bundle exec sidekiq -e production -C config/sidekiq.yml -q default</span>
</code></pre></div></div>

<p>To make use of the <code class="language-plaintext highlighter-rouge">Procfile</code> setup in development, all you need to do is use the <code class="language-plaintext highlighter-rouge">foreman</code> gem and then run the <code class="language-plaintext highlighter-rouge">foreman s</code> (or <code class="language-plaintext highlighter-rouge">foreman start</code>) command, which will then look for a <code class="language-plaintext highlighter-rouge">Procfile</code> in the directory from which you’re running the command and then start a separate process for each one you’ve defined.</p>

<p>Great, right? Ummmmm… yeah, but there’s one small problem. We have <code class="language-plaintext highlighter-rouge">-e production</code> specified for sidekiq and we want to run it in <code class="language-plaintext highlighter-rouge">development</code> mode instead. So how can we do that?</p>

<p>Easy. <code class="language-plaintext highlighter-rouge">foreman</code> let’s use specify a different <code class="language-plaintext highlighter-rouge">Procfile</code> to use so we can have multiple ones that we reference using the <code class="language-plaintext highlighter-rouge">-f</code> option: <code class="language-plaintext highlighter-rouge">foreman s -f Procfile.dev</code>. What’s happening here is we’re specifying to <code class="language-plaintext highlighter-rouge">foreman</code> to look for a file called <code class="language-plaintext highlighter-rouge">Procfile.dev</code> instead of the default <code class="language-plaintext highlighter-rouge">Procfile</code>. In <code class="language-plaintext highlighter-rouge">Procfile.dev</code> we can tweak the commands to match the development environment.</p>

<h3 id="moar">Moar!</h3>

<p>Now that we have the initial setup figured out, can we make this do more?</p>

<p>The answer is yes! Let’s consider the following scenario: We are working on a Rails app that uses sidekiq for background jobs, mailcatcher for debugging emails in development, and also React with webpacker. What would our <code class="language-plaintext highlighter-rouge">Procfile.dev</code> look like?</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">web</span><span class="pi">:</span>       <span class="s">bundle exec puma -C config/puma.rb</span>
<span class="na">worker1</span><span class="pi">:</span>   <span class="s">bundle exec sidekiq -e development -C config/sidekiq.yml -q mailers -q analytics</span>
<span class="na">worker2</span><span class="pi">:</span>   <span class="s">bundle exec sidekiq -e development -C config/sidekiq.yml -q default</span>
<span class="na">worker3</span><span class="pi">:</span>   <span class="s">mailcatcher --foreground --http-ip=0.0.0.0</span>
<span class="na">webpacker</span><span class="pi">:</span> <span class="s">./bin/webpack-dev-server --listen-host 0.0.0.0 --watch-poll</span>
</code></pre></div></div>

<p>That works. Except for the scenario where we might be working heavily in the React part of the app and need to restart the webpack server a bunch of times. In the current setup we would have to stop foreman and start it back up, which means a long boot time since we have to wait for all of the services mentioned to restart. There’s a case to have two different <code class="language-plaintext highlighter-rouge">Procfile</code>s for each of the situations: run webpacker with everything else, or run it separately.</p>

<p>Let’s say we’ve created a file <code class="language-plaintext highlighter-rouge">Procfile.dev</code> that does NOT include the <code class="language-plaintext highlighter-rouge">webpacker</code> line and another one called <code class="language-plaintext highlighter-rouge">Procfile.dev.w-webpack</code> that does include the last line. Now, all we have to do is run <code class="language-plaintext highlighter-rouge">foreman s -f</code> and point to the right file.</p>

<p>Not a bad situation. But to be honest, that’s a lot to type if I just want to start the server in development. How can we make this better? For this part, I’m going to take a page out of the Rails book. If you look carefully, you’ll notice that a Rails app has a <code class="language-plaintext highlighter-rouge">bin</code> directory which is just a collection of scripts. The one we use mostly is <code class="language-plaintext highlighter-rouge">bin/rails</code> but they all are convenience scripts that are at our disposal to make us type less. The sensible thing is for us to create another one to run the server.</p>

<p>Let’s create a file called <code class="language-plaintext highlighter-rouge">server</code> in the <code class="language-plaintext highlighter-rouge">bin</code> directory, so we’ll be able to use the <code class="language-plaintext highlighter-rouge">bin/server</code> command to start our Rails app in development. The simplest form of the file would look like this:</p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/usr/bin/env sh</span>
foreman start <span class="nt">-f</span> Procfile.dev
</code></pre></div></div>

<p>That’s easy. Now let’s update this script to work with our webpack scenario:</p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/usr/bin/env sh</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">while</span> <span class="n">getopts</span> <span class="s2">":w"</span> <span class="n">opt</span><span class="p">;</span> <span class="k">do</span>
  <span class="k">case</span> <span class="vg">$opt</span> <span class="k">in</span>
    <span class="n">w</span><span class="p">)</span>
      <span class="no">WITH_WEBPACK</span><span class="o">=</span><span class="kp">true</span>
      <span class="p">;;</span>
  <span class="n">esac</span>
<span class="n">done</span>
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="o">[</span> <span class="nv">$WITH_WEBPACK</span> <span class="o">]</span><span class="p">;</span> <span class="k">then
  </span><span class="nb">echo</span> <span class="s1">'Staring server using Procfile.dev.w-webpack'</span>
  foreman start <span class="nt">-f</span> Procfile.dev.w-webpack
<span class="k">else
  </span><span class="nb">echo</span> <span class="s1">'Staring server using Procfile.dev'</span>
  foreman start <span class="nt">-f</span> Procfile.dev
<span class="k">fi</span>
</code></pre></div></div>

<p>This might be a bit more overwhelming, but in reality, all this is doing is looking for a <code class="language-plaintext highlighter-rouge">-w</code> flag that is passed to the script. And depending on the presence of this flag, it will use the appropriate <code class="language-plaintext highlighter-rouge">Procfile</code> to either start webpack along with everything else, or not. So now we can run <code class="language-plaintext highlighter-rouge">bin/server</code> to start the server, mailcatcher, and sidekiq or <code class="language-plaintext highlighter-rouge">bin/server -w</code> to also start webpack along with the rest. Pretty neat, right? And since we can use tabbing to let the command line autocomplete the command for us, we don’t have to type a lot in order to fire up the app (for the first case it’s <code class="language-plaintext highlighter-rouge">bin/ser + tab</code> and <code class="language-plaintext highlighter-rouge">bin/ser + tab + -w</code> for the second case).</p>

<p>I think this is a good solution when working with a team of developers as well, across multiple apps. It reduces confusion and having to think which command do I need to run to get started. If it’s standardized to <code class="language-plaintext highlighter-rouge">bin/server</code> and then the script in each app handles the rest, now you have one common way to run the app in all cases.</p>

<p><strong>TIP:</strong> Make sure your default option in the script handles the most common scenario, and then add options for any other cases. So for example, if your most common case is to run webpack with everything else, make that the default case and add a flag for the case where it is not (<code class="language-plaintext highlighter-rouge">-no-w</code> ) as opposed to how the script in the example code behaves.</p>]]></content><author><name></name></author><category term="ruby-on-rails" /><category term="rails" /><category term="developer-tools" /><summary type="html"><![CDATA[Any app that goes beyond the very basics will probably have many components that it depends on. Even the smallest Rails app will probably have some…]]></summary></entry><entry><title type="html">Rails: Non blocking analytics</title><link href="https://bearandgiraffe.com/blog/rails-non-blocking-analytics/" rel="alternate" type="text/html" title="Rails: Non blocking analytics" /><published>2018-01-15T17:01:01+00:00</published><updated>2018-01-15T17:01:01+00:00</updated><id>https://bearandgiraffe.com/blog/rails-non-blocking-analytics</id><content type="html" xml:base="https://bearandgiraffe.com/blog/rails-non-blocking-analytics/"><![CDATA[<p><strong>Scenario:</strong> You’ve been working on a web based product which started getting some traction. You want to understand your users’ behavior on your app, and whether the user experience is smooth and going the way you’ve assumed, or if it’s got bumps that you can fix. Naturally, you decide to track every action and event that is occurring. You integrate with something like Google Analytics or Keen.io to track user actions as well as sync some meta data about your user base to better understand what’s going on.</p>

<p><strong>Problem:</strong> After deploying the changes that add the tracking, you start receiving complaints that the app is slower, and in some cases, users are experiencing weird behaviors and an increased rate of errors. What happened?</p>

<p><strong>Diagnosis:</strong> You’ve added your analytics code inline in your controllers, so after each action a user takes, they have to wait for the request to your own servers to finish as well as every request to each analytics platform you are using. What has happened is that you’ve introduced bottlenecks into your code that is acting as user blocking logic. Ask yourself this: Does the user need to wait for the analytics calls to finish before they can continue using your app? The answer is no. From the user’s perspective, they don’t care at all about what’s happening in the background and that you are making an extra call to a third party service for analytics. In fact, this is also true even if you’re not using a third party service and tracking the actions yourself. The analytics logic is secondary to the user experience. If something fails along the way in terms of collecting data for analytics, the user should not be blocked from using your app.</p>

<p><strong>Solution:</strong> The fix is easy. Move all analytics related code to background jobs. Let’s add the following job file to the app (in <code class="language-plaintext highlighter-rouge">app/jobs/analytics/keen_event_job.rb</code>):</p>

<p>If you read the Keen ruby gem README, you’ll find instructions on how to do the same thing but using <code class="language-plaintext highlighter-rouge">EventMachine</code> and replacing <code class="language-plaintext highlighter-rouge">publish</code> with <code class="language-plaintext highlighter-rouge">publish_async</code> and that solution is good if Keen is the only analytics platform you’re using. I find that most projects I work on use multiple analytics platforms like Google Analytics and Keen, but also use other platforms that you’d want to send data to for better customer service like Intercom.io.</p>

<p>At this point, if you’re using multiple services that you’d want to send data to, you’ll find yourself repeating a bunch of code everywhere in your app. That’s when it becomes worth while to write a wrapper that handles calling all of the different services for you. Using the adaptor pattern, we can write a class that has a single interface and is responsible for dispatching the requests to each analytics service.</p>

<p>That sounds a bit difficult and a lot of work. Especially if you are working on multiple apps which all need to implement some sort of analytics. That is why we’ve created a gem that does that for you. The gem is still in its early phases, and will probably change a lot in the near future in order to develop a consistent API and make it modular so it can accept new integrations easily. But for now, it does the job. You can find the gem on <a href="https://github.com/bearandgiraffe/bg-common">github</a>, it’s called BG::Common because it includes a bunch of common things that you’d want to implement in any Rails app. It is likely that we will break it up soon and make the analytics portion of it its own separate gem.</p>]]></content><author><name></name></author><category term="ruby-on-rails" /><category term="analytics" /><category term="rails" /><category term="developer-tools" /><category term="open-source" /><summary type="html"><![CDATA[Scenario: You’ve been working on a web based product which started getting some traction. You want to understand your users’ behavior on your app, and…]]></summary></entry><entry><title type="html">Intro to Trailblazer - Part II: Operations</title><link href="https://bearandgiraffe.com/blog/intro-to-trailblazer-part-ii-operations/" rel="alternate" type="text/html" title="Intro to Trailblazer - Part II: Operations" /><published>2017-04-17T15:01:06+00:00</published><updated>2017-04-17T15:01:06+00:00</updated><id>https://bearandgiraffe.com/blog/intro-to-trailblazer-part-ii-operations</id><content type="html" xml:base="https://bearandgiraffe.com/blog/intro-to-trailblazer-part-ii-operations/"><![CDATA[<p>In a previous <a href="/blog/introduction-to-trailblazer-through-decorators/">post</a>, we talked about using <code class="language-plaintext highlighter-rouge">Decorators</code> and introduced Trailblazer’s <code class="language-plaintext highlighter-rouge">Disposable::Twin</code> class that gives us a super easy way to create and use decorators. But <code class="language-plaintext highlighter-rouge">Decorators</code> aren’t the reason why you should look into Trailblazer, as we said in the previous post, <a href="https://github.com/drapergem/draper">draper</a> would be the better option if that’s all you needed. The really interesting part comes in the way you get to organize your Rails application code so that you keep your controllers skinny and your models skinnier.</p>

<p>When I first started working with Rails, around 2008, the common principle that everyone was following was “Skinny Controllers, Fat Models”. What many applications at the time were suffering from was the never ending nesting of <code class="language-plaintext highlighter-rouge">if/else</code> statements inside of controllers. The solution to that was to move business logic to classes that are responsible for handling the business requirements and limit the controller’s responsibility to merely directing traffic. So many devs, myself included, looked at the structure of a Rails app and figured that the place to move the business logic to was the models because those were the classes that represented the domain objects of the app and thus needed to encapsulate the business logic that governed the relationship between them. That was a trick that Rails played on us, and we fell for it. See, a typical Rails model looked like this:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
<span class="k">end</span>
</code></pre></div></div>

<p>or maybe something like this:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
  <span class="n">has_many</span> <span class="ss">:articles</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="n">validates_uniqueness_of</span> <span class="ss">:email</span>
<span class="k">end</span>
</code></pre></div></div>

<p>what you noticed is that there wasn’t much code inside of a Rails model, so why not put a bunch of it in there, right?</p>

<p>In fact, there was a whole lot of functionality hidden inside each of these classes, courtesy of one tiny little character: <code class="language-plaintext highlighter-rouge">&lt;</code>. What we weren’t seeing was all of the logic hidden inside of <code class="language-plaintext highlighter-rouge">ActiveRecord::Base</code> that was added to each model thanks to <code class="language-plaintext highlighter-rouge">inheritance</code>. It turns out that <code class="language-plaintext highlighter-rouge">AR</code> models plenty of responsibilities to uphold in terms of taking care of fetching and saving data from and to the database. And that is ALL an <code class="language-plaintext highlighter-rouge">AR</code> model should be, a <code class="language-plaintext highlighter-rouge">Data Object</code>. Which meant that a model was not the appropriate place to hold any business logic, we were doing it all wrong all this time!</p>

<p>So if not the controller, and not the model, where should I put my business logic inside of a Rails app, all I’ve got left are views?! If you look at the directory structure of a plain Rails app (what <code class="language-plaintext highlighter-rouge">rails new</code> generates), this is how it looks like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>.
├── Gemfile
├── Gemfile.lock
├── README.md
├── Rakefile
├── app
│   ├── assets
│   ├── channels
│   ├── controllers
│   ├── helpers
│   ├── jobs
│   ├── mailers
│   ├── models
│   └── views
├── bin
│   ├── bundle
│   ├── rails
│   ├── rake
│   ├── setup
│   ├── spring
│   └── update
├── config
│   ├── application.rb
│   ├── application.yml
│   ├── boot.rb
│   ├── cable.yml
│   ├── environment.rb
│   ├── environments
│   ├── initializers
│   ├── locales
│   ├── puma.rb
│   ├── routes.rb
│   ├── secrets.yml
│   └── spring.rb
├── config.ru
├── db
│   └── seeds.rb
├── lib
│   ├── assets
│   └── tasks
├── log
│   ├── development.log
│   ├── production.log
│   └── test.log
├── public
│   ├── 404.html
│   ├── 422.html
│   ├── 500.html
│   ├── apple-touch-icon-precomposed.png
│   ├── apple-touch-icon.png
│   ├── favicon.ico
│   └── robots.txt
├── tmp
│   ├── cache
│   ├── pids
│   ├── restart.txt
│   └── sockets
└── vendor
    └── assets
</code></pre></div></div>

<p>it is natural to assume from this structure that any code you introduce as a developer should go under the <code class="language-plaintext highlighter-rouge">app</code> directory. And what you get out of the box is:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>app
├── assets
├── channels
├── controllers
├── helpers
├── jobs
├── mailers
├── models
└── views
</code></pre></div></div>

<p>which means that your options for where to put business logic are pretty much the <code class="language-plaintext highlighter-rouge">controllers</code> directory, the <code class="language-plaintext highlighter-rouge">models</code> directory, and maybe the <code class="language-plaintext highlighter-rouge">jobs</code> directory, but not much else. If you’re supposed to put app logic inside of any other directory, Rails would have generated it for you, wouldn’t it? “Convention over configuration” is the motto after all! The reality is that Rails is just another Ruby application, so you get to create as many directories as you want and organize your code however best it fits your needs. Rails does indeed automatically include any directory and subdirectory under the <code class="language-plaintext highlighter-rouge">app</code> directory in the load path by default. What most Rails devs tend to forget and ignore is the <code class="language-plaintext highlighter-rouge">lib</code> directory:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>lib
├── assets
└── tasks
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">lib</code> directory is not there by coincidence, and the fact that it just comes with two empty directories should be an indicator that it’s included for a purpose, despite how non evident that might be. All code that is not framework related, as in all code that is not tied to <code class="language-plaintext highlighter-rouge">AR</code> (data), <code class="language-plaintext highlighter-rouge">html</code> (views), or routing (controller + routes), is intended to go in the <code class="language-plaintext highlighter-rouge">lib</code> directory. Which includes any business or domain logic.</p>

<p>It is counterintuitive to think of it this way. We mostly think as the entire app as domain logic, and easily fall into the trap of coupling our application logic with the framework, in this case Rails. But that need not be the case. In fact, structuring our code independently of the framework lends itself to cleaner and more maintainable code. Alas, if you are not ready to make the full jump into putting your code in the <code class="language-plaintext highlighter-rouge">lib</code> directory, I feel you, I get it, and Trailblazer is here to help.</p>

<p>Trailblazer can act as the bridge between Rails, the framework, and code that represents our domain logic. This is where <code class="language-plaintext highlighter-rouge">Trailblazer::Operation</code>s come in to play. If we think of a Rails application as a set of interactions a user can perform, then an operation is the set of side effects each interaction has on the application and the data that the application is responsible for.</p>

<p>Let’s take a look at a particular example. Assume we have a Dropbox clone where a user can upload documents and perform a set of actions on them (rename, delete, etc). The interaction of uploading a document is in fact the operation of creating a document record, uploading the file, setting the file path on the document record, setting document uploader to the current user, setting the timestamps, and triggering any notifications (let’s assume that we accept only images and pdfs, and all images are converted to pdfs and then the user is notified once the conversion is complete).</p>

<p>If you add all that logic on the model, that means each time you create a new record in the db, or perform any action on it, everything that was described above will be triggered. But you might not want that to happen. So you add a bunch of conditionals, and more logic. Soon enough just managing those rules becomes cumbersome and a nightmare. On the flip side, using Trailblazer, we can specify a <code class="language-plaintext highlighter-rouge">Doc::Create</code> operation that is responsible for encapsulating the necessary logic for this particular interaction. It will look something like this:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">require</span> <span class="s1">'file/converter'</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Doc::Create</span> <span class="o">&lt;</span> <span class="no">Trailblazer</span><span class="o">::</span><span class="no">Operation</span>
  <span class="kp">include</span> <span class="no">Model</span>
  <span class="kp">include</span> <span class="no">Dispatch</span>
  <span class="n">model</span> <span class="no">Doc</span><span class="p">,</span> <span class="ss">:create</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="n">contract</span> <span class="k">do</span>
    <span class="kp">include</span> <span class="no">Reform</span><span class="o">::</span><span class="no">Form</span><span class="o">::</span><span class="no">ModelReflections</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">property</span> <span class="ss">:uploaded_at</span><span class="p">,</span>
      <span class="ss">validates: </span><span class="p">{</span> <span class="ss">presence: </span><span class="kp">true</span> <span class="p">}</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">property</span> <span class="ss">:file</span><span class="p">,</span>
      <span class="ss">validates: </span><span class="p">{</span> <span class="ss">presence: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">file: </span><span class="kp">true</span> <span class="p">}</span>
  <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="n">callback</span> <span class="ss">:after_save</span><span class="p">,</span> <span class="no">NotifyUserCallback</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">process</span> <span class="n">params</span>
    <span class="n">validate</span> <span class="n">params</span> <span class="k">do</span> <span class="o">|</span><span class="n">op</span><span class="o">|</span>
      <span class="n">file</span> <span class="o">=</span> <span class="n">params</span><span class="p">[</span><span class="ss">:file</span><span class="p">]</span>
      <span class="k">if</span> <span class="o">!</span><span class="n">file</span><span class="p">.</span><span class="nf">is_a?</span><span class="p">(</span><span class="no">String</span><span class="p">)</span>
        <span class="n">converter</span> <span class="o">=</span> <span class="no">File</span><span class="o">::</span><span class="no">Converter</span><span class="p">.</span><span class="nf">new</span> <span class="ss">original_file: </span><span class="n">file</span>
        <span class="n">op</span><span class="p">.</span><span class="nf">file</span>   <span class="o">=</span> <span class="n">converter</span><span class="o">.</span><span class="p">()</span>
      <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>      <span class="n">op</span><span class="p">.</span><span class="nf">save</span>
      <span class="n">callback!</span><span class="p">(</span><span class="ss">:after_save</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kp">private</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">setup_params!</span> <span class="n">params</span>
    <span class="vi">@current_user</span> <span class="o">=</span> <span class="n">params</span><span class="p">[</span><span class="ss">:current_user</span><span class="p">]</span>
  <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">setup_model!</span> <span class="n">params</span>
    <span class="n">model</span><span class="p">.</span><span class="nf">uploader</span>    <span class="o">=</span> <span class="vi">@current_user</span>
    <span class="n">model</span><span class="p">.</span><span class="nf">uploaded_at</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">now</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Let’s run through that line by line. The first line requires a custom class for converting images to pdf. We do not need to get into what that looks like, outside of the scope of this post. The first thing we do is define a class <code class="language-plaintext highlighter-rouge">Doc::Create</code> which inherits from <code class="language-plaintext highlighter-rouge">Trailblazer::Operation</code>. The reason we name the class <code class="language-plaintext highlighter-rouge">Doc::Create</code> is because we want to namespace the action under the <code class="language-plaintext highlighter-rouge">Doc</code> object, and <code class="language-plaintext highlighter-rouge">Create</code> describes the operation we are performing. The next step is we include the <code class="language-plaintext highlighter-rouge">Model</code> module provided by Trailblazer that gives us the ability to sync the object we create with a Rails model, we specify which model and which method to use with this piece of code: <code class="language-plaintext highlighter-rouge">model Doc, :create</code>. This line <code class="language-plaintext highlighter-rouge">include Dispatch</code> gives us access to callbacks, which we’ll use to send the notification. We use callbacks in this case so that we can chain a bunch of them and reuse them in other places, but for this example we could have just inlined the notification bit in this operation if we wanted to. The <code class="language-plaintext highlighter-rouge">contract do ... end</code> part of the code indicates what params we expect to have passed to use from the form and we can add validations on these attributes the same way we would on a Rails model. The <code class="language-plaintext highlighter-rouge">process</code> method is the method that gets called with this operation is run, it’s where we can add our custom logic. Because of what Trailblazer provides to us out of the box, like validations and synching to models, we don’t have to include a lot of logic to get our example working. We just run the validations, then call the converter, and save the object. Once that is done we call the callback to send the notification. What looked like complex logic became super simple when using <code class="language-plaintext highlighter-rouge">Trailblazer::Operation</code>s. The only other piece of the puzzle is setup code that use to set the current user as the <code class="language-plaintext highlighter-rouge">uploader</code> on the doc object. The reason we need that is because the current user is not a form field that we get, instead it’s an object that we pass along to the operation manually from the controller. Speaking of which, we should look at the controller code next:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">DocsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
  <span class="n">respond_to</span> <span class="ss">:json</span><span class="p">,</span> <span class="ss">:js</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">new</span>
    <span class="n">authorize</span> <span class="no">Doc</span><span class="p">,</span> <span class="ss">:create?</span>
    <span class="n">form</span> <span class="no">Doc</span><span class="o">::</span><span class="no">Create</span>
  <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">create</span>
    <span class="n">authorize</span> <span class="no">Doc</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">create_params</span> <span class="o">=</span> <span class="n">doc_params</span><span class="p">.</span><span class="nf">to_h</span><span class="p">.</span><span class="nf">merge!</span><span class="p">(</span><span class="ss">current_user: </span><span class="n">current_user</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">run</span> <span class="no">Doc</span><span class="o">::</span><span class="no">Create</span><span class="p">,</span> <span class="ss">params: </span><span class="n">create_params</span> <span class="k">do</span> <span class="o">|</span><span class="n">op</span><span class="o">|</span>
      <span class="n">flash</span><span class="p">[</span><span class="ss">:notice</span><span class="p">]</span> <span class="o">=</span> <span class="n">t</span><span class="p">(</span><span class="ss">:notice</span><span class="p">,</span> <span class="ss">scope: </span><span class="p">[</span><span class="ss">:flash</span><span class="p">,</span> <span class="ss">:docs</span><span class="p">,</span> <span class="ss">:create</span><span class="p">])</span>
      <span class="k">return</span> <span class="n">redirect_to</span> <span class="n">root_path</span>
    <span class="k">end</span>
    
    <span class="n">flash</span><span class="p">[</span><span class="ss">:error</span><span class="p">]</span> <span class="o">=</span> <span class="n">t</span><span class="p">(</span><span class="ss">:error</span><span class="p">,</span> <span class="ss">scope: </span><span class="p">[</span><span class="ss">:flash</span><span class="p">,</span> <span class="ss">:docs</span><span class="p">,</span> <span class="ss">:create</span><span class="p">])</span>
    <span class="n">render</span> <span class="ss">:new</span>
  <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kp">private</span>
  <span class="k">def</span> <span class="nf">doc_params</span>
    <span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:doc</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:file</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Because Trailblazer is awesome, when we define an operation, what we get for free is the ability to setup a form object that we can use in a <code class="language-plaintext highlighter-rouge">form_for</code> helper just like we would a regular <code class="language-plaintext highlighter-rouge">AR</code> model. So that’s all that the <code class="language-plaintext highlighter-rouge">new</code> action is doing. Then in the <code class="language-plaintext highlighter-rouge">create</code> action, we are fetching the permitted params for a doc, adding the current user object to it, then passing it to the operation we’ve defined and calling <code class="language-plaintext highlighter-rouge">run</code> on it which will execute all the setup and then the <code class="language-plaintext highlighter-rouge">process</code> method we talked about above. If the operation is successful and valid, then the code inside of the block is executed (which just sets the <code class="language-plaintext highlighter-rouge">flash</code> message and redirects to the <code class="language-plaintext highlighter-rouge">root_path</code>, you can obviously execute whatever fits your app. If the operation is not valid, then the code after the block is executed, which is very standard Rails controller code at this point, again, you’ll be able to include you’re own custom behavior there.</p>

<p>I would say that’s code that is organized, clean, and easy to follow. No magic, no hidden logic that will bite us in the ass. In fact, let’s see what we would do for the <code class="language-plaintext highlighter-rouge">update</code> action:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">require</span> <span class="s1">'file/converter'</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Doc::Update</span> <span class="o">&lt;</span> <span class="no">Trailblazer</span><span class="o">::</span><span class="no">Operation</span>
  <span class="kp">include</span> <span class="no">Model</span>
  <span class="kp">include</span> <span class="no">Dispatch</span>
  <span class="n">model</span> <span class="no">Doc</span><span class="p">,</span> <span class="ss">:create</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="n">contract</span> <span class="k">do</span>
    <span class="kp">include</span> <span class="no">Reform</span><span class="o">::</span><span class="no">Form</span><span class="o">::</span><span class="no">ModelReflections</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">property</span> <span class="ss">:uploaded_at</span><span class="p">,</span>
      <span class="ss">validates: </span><span class="p">{</span> <span class="ss">presence: </span><span class="kp">true</span> <span class="p">}</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">property</span> <span class="ss">:file</span><span class="p">,</span>
      <span class="ss">validates: </span><span class="p">{</span> <span class="ss">presence: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">file: </span><span class="kp">true</span> <span class="p">}</span>
  <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="n">callback</span> <span class="ss">:after_save</span><span class="p">,</span> <span class="no">NotifyUserCallback</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">process</span> <span class="n">params</span>
    <span class="n">validate</span> <span class="n">params</span> <span class="k">do</span> <span class="o">|</span><span class="n">op</span><span class="o">|</span>
      <span class="n">file</span> <span class="o">=</span> <span class="n">params</span><span class="p">[</span><span class="ss">:file</span><span class="p">]</span>
      <span class="k">if</span> <span class="o">!</span><span class="n">file</span><span class="p">.</span><span class="nf">is_a?</span><span class="p">(</span><span class="no">String</span><span class="p">)</span>
        <span class="n">converter</span> <span class="o">=</span> <span class="no">File</span><span class="o">::</span><span class="no">Converter</span><span class="p">.</span><span class="nf">new</span> <span class="ss">original_file: </span><span class="n">file</span>
        <span class="n">op</span><span class="p">.</span><span class="nf">file</span>   <span class="o">=</span> <span class="n">converter</span><span class="o">.</span><span class="p">()</span>
      <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>      <span class="n">op</span><span class="p">.</span><span class="nf">status</span> <span class="o">=</span> <span class="ss">:pending</span> <span class="c1"># &lt;-- this is new</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>      <span class="n">op</span><span class="p">.</span><span class="nf">save</span>
      <span class="n">callback!</span><span class="p">(</span><span class="ss">:after_save</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kp">private</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">setup_params!</span> <span class="n">params</span>
    <span class="vi">@current_user</span> <span class="o">=</span> <span class="n">params</span><span class="p">[</span><span class="ss">:current_user</span><span class="p">]</span>
  <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">setup_model!</span> <span class="n">params</span>
    <span class="n">model</span><span class="p">.</span><span class="nf">uploader</span>    <span class="o">=</span> <span class="vi">@current_user</span>
    <span class="n">model</span><span class="p">.</span><span class="nf">uploaded_at</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">now</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>In the operation class, not much is different, we’ve only added a line to reset the status of the doc if a new file has been uploaded. You could, however, imagine scenarios where the logic can be vastly different and this setup lets us handle that kind of scenarios easily. On the controller side, the <code class="language-plaintext highlighter-rouge">update</code> action will look exactly like the <code class="language-plaintext highlighter-rouge">create</code> action, for the exception of where to <code class="language-plaintext highlighter-rouge">redirect_to</code> on success or which action to <code class="language-plaintext highlighter-rouge">render</code> on failure. It’s really that simple.</p>

<p>We’ve covered quite a lot so far, yet there’s still lots more that Trailblazer offers. You can check out the <a href="http://trailblazer.to/gems/operation/1.1/index.html">docs</a> for more info. What I would say though, is that what we covered in this post should be enough to get you started and thinking about making sure your Rails code does not get messy and out of control.</p>

<p>Do you have experience with Trailblazer? Share it with us in the comments below…</p>]]></content><author><name></name></author><category term="ruby-on-rails" /><category term="rails" /><category term="trailblazer" /><category term="architecture" /><category term="ruby" /><summary type="html"><![CDATA[In a previous post, we talked about using Decorators and introduced Trailblazer’s Disposable::Twin class that gives us a super easy way to create and use…]]></summary></entry><entry><title type="html">Introduction to Trailblazer Through Decorators</title><link href="https://bearandgiraffe.com/blog/introduction-to-trailblazer-through-decorators/" rel="alternate" type="text/html" title="Introduction to Trailblazer Through Decorators" /><published>2017-03-24T19:24:20+00:00</published><updated>2017-03-24T19:24:20+00:00</updated><id>https://bearandgiraffe.com/blog/introduction-to-trailblazer-through-decorators</id><content type="html" xml:base="https://bearandgiraffe.com/blog/introduction-to-trailblazer-through-decorators/"><![CDATA[<p>M.V.C., three letters with a lot of baggage. For the uninitiated, M.V.C. stands for Model-View-Controller. It’s design pattern for how to organize code for an application. It was made popular by Rails, but it definitely is not Rails specific. When mobile app development hit the scene, we started hearing of M.M.V.C. which stands for Model-Model View-Controller. At first, the new design pattern sounded like a distinction without difference to me, but that wasn’t because of the pattern itself but because how I approached MVC originally. Let’s dig into that a bit to see why.</p>

<p>In the MVC pattern, the model encapsulates the data (usually saved in a database) that represents a logical entity or a model of a physical entity (eg. user, organization, etc). The view determines how things are displayed to the user and what interactions the user can have with the application. The controller, like an air traffic controller at an airport, routes traffic through our app and determines what data to pull (models) and pass along to the appropriate view. Very simple, and it’s meant to help developers organize their code instead of trying to put everything in one file (I’m talking about you PHP!). Turns out, applications can get very complex, and the data can be relational (user owns a car, car has car insurance, etc) and those relationships can get very complicated really quickly. The view that is responsible for representing all those relationships and data can become riddled with view logic (many layers of <code class="language-plaintext highlighter-rouge">if</code> statements). Mobile applications, on the other hand, need to be very simplistic on the view layer because the screen is small, which forced mobile developers to add another layer in the design pattern called the View Model, which has the responsibility of taking the data we need for our view, encapsulate it and decide what can be shown and interacted with based on the context. It’s a good idea. I support that idea. So why did I think that it’s a distinction without difference? Simply because I thought we were already doing that with MVC. We already have the Decorator pattern that is essentially what model views are.</p>

<p>In theory, that is true. We already have a pattern in our toolbox that we should reach for, but we all know that many of us, including myself, don’t reach for it often enough. I bet you that the application you’re working on right now does not make use of the Decorator pattern, does it?</p>

<p>If don’t know about the Decorator pattern, or about how to implement one in Ruby, I highly recommend this <a href="https://robots.thoughtbot.com/evaluating-alternative-decorator-implementations-in">article</a> by the good folks at <a href="https://thoughtbot.com/">ThoughtBot</a>. If you just want a gem, try <a href="https://github.com/drapergem/draper">draper</a>. Or, if you are obsessed with code clarity and organization like I am, then look into something like <a href="http://trailblazer.to">trailblazer</a>. Why trailblazer? Because I like the idea of grouping parts of an application into components, or concepts in the trailblazer lingo. Each component can be divided up into multiple parts, each of which is responsible for one thing and one thing only in your application. A user profile can have a form object that is responsible for collecting the data from the user and validating it, the contract takes that data and manipulates it then saves it, and a decorator retrieves that data and presents it back to the user ins a specific manner. The concept is the same, the user profile, the parts are independent and work can be done on each separately and without the risk of breaking any other part.</p>

<p>So what does trailblazer have to do with MVC and MVVC? Well the answer is on the trailblazer website, in the description:</p>

<blockquote>
  <p>Trailblazer gives you a high-level architecture for web applications. It extends the basic MVC pattern with new abstractions. Rock-solid conventions that go far beyond database table naming or route paths let you focus on your application code, minimize bugs and improve the maintainability.</p>
</blockquote>

<p>In other words, trailblazer helps build on MVC and MVVC and structure real world apps in a very clean way. And one of the things it offers is decorators through what it calls a <code class="language-plaintext highlighter-rouge">Disposable::Twin</code>. Here’s how you would setup a user twin:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># app/concepts/user/view/user_twin.rb</span>
<span class="k">class</span> <span class="nc">UserTwin</span> <span class="o">&lt;</span> <span class="no">Disposable</span><span class="o">::</span><span class="no">Twin</span>
  <span class="n">property</span> <span class="ss">:first_name</span>
  <span class="n">property</span> <span class="ss">:last_name</span>
  <span class="n">property</span> <span class="ss">:profile_image</span>
<span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">twin</span> <span class="o">=</span> <span class="no">UserTwin</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="n">twin</span><span class="p">.</span><span class="nf">first_name</span> <span class="c1"># =&gt; delegates to user.first_name</span>
</code></pre></div></div>

<p>There are few cool things it can do too:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># supports nesting</span>
<span class="k">class</span> <span class="nc">OrgTwin</span> <span class="o">&lt;</span> <span class="no">Disposable</span><span class="o">::</span><span class="no">Twin</span>
  <span class="n">property</span> <span class="ss">:name</span>
  <span class="n">property</span> <span class="ss">:owner</span> <span class="k">do</span>
    <span class="n">property</span> <span class="ss">:first_name</span>
    <span class="n">property</span> <span class="ss">:last_name</span>
  <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="c1"># allows custom logic</span>
  <span class="k">def</span> <span class="nf">display_name</span>
    <span class="s2">"Org: </span><span class="si">#{</span><span class="nb">self</span><span class="p">.</span><span class="nf">name</span><span class="si">}</span><span class="s2">"</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>and:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># lets you use dynamic/virtual attributes</span>
<span class="k">class</span> <span class="nc">UserTwin</span> <span class="o">&lt;</span> <span class="no">Disposable</span><span class="o">::</span><span class="no">Twin</span>
  <span class="o">...</span>
  <span class="n">property</span> <span class="ss">:can_update_profile?</span><span class="p">,</span> <span class="ss">virtual: </span><span class="kp">true</span>
<span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">twin</span> <span class="o">=</span> <span class="no">UserTwin</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">user</span><span class="p">,</span> <span class="ss">can_update_profile?: </span><span class="n">current_user</span> <span class="o">==</span> <span class="n">user</span><span class="p">)</span>
<span class="n">twin</span><span class="p">.</span><span class="nf">can_update_profile?</span> <span class="c1"># =&gt; true if the logged in user is the same</span>
                         <span class="c1"># =&gt; false otherwise</span>
</code></pre></div></div>

<p>or lets you reference doubly nested objects and expose them to the top:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">OrgTwin</span> <span class="o">&lt;</span> <span class="no">Disposable</span><span class="o">::</span><span class="no">Twin</span>
  <span class="n">feature</span> <span class="no">Expose</span>
  
  <span class="o">...</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="n">unnest</span> <span class="ss">:account</span><span class="p">,</span> <span class="ss">from: :owner</span>
<span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">owner</span>   <span class="o">=</span> <span class="no">Owner</span><span class="p">.</span><span class="nf">create</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<span class="n">account</span> <span class="o">=</span> <span class="no">Account</span><span class="p">.</span><span class="nf">create</span><span class="p">(</span><span class="o">...</span><span class="p">,</span> <span class="ss">owner: </span><span class="n">owner</span><span class="p">)</span>
<span class="n">org</span>     <span class="o">=</span> <span class="no">Org</span><span class="p">.</span><span class="nf">create</span><span class="p">(</span><span class="o">...</span><span class="p">,</span> <span class="ss">owner: </span><span class="n">owner</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">twin</span>    <span class="o">=</span> <span class="no">OrgTwin</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">org</span><span class="p">)</span>
<span class="n">twin</span><span class="p">.</span><span class="nf">account</span> <span class="c1"># =&gt; returns org.owner.account</span>
</code></pre></div></div>

<p>assuming in the example above that you’ve setup a twin for the account that only exposes the type of account (pro, enterprise, etc) and leaves all the payment info out, you can see how it can be cleaner to display the profile of an organization without the need to litter your view with a bunch of logic and without passing it all the data that is encapsulated in the models (including passwords and other sensitive information).</p>

<p>There you go, not a lot of setup or fancy stuff that is required to get started making your application code a bit cleaner. The nice thing about trailblazer is that it’s modular and you can just use what you need and leave the rest behind. If you are just going to use the Decorator pattern, I recommend you go with the draper gem, otherwise be on the lookout for more posts from us on how to add other pieces of trailblazer to your app in the hopes of moving towards a much cleaner and maintainable code structure.</p>]]></content><author><name></name></author><category term="ruby-on-rails" /><category term="rails" /><category term="trailblazer" /><category term="architecture" /><summary type="html"><![CDATA[M.V.C., three letters with a lot of baggage. For the uninitiated, M.V.C. stands for Model-View-Controller. It’s design pattern for how to organize code…]]></summary></entry><entry><title type="html">Dynamic Hash in Ruby</title><link href="https://bearandgiraffe.com/blog/dynamic-hash-in-ruby/" rel="alternate" type="text/html" title="Dynamic Hash in Ruby" /><published>2017-02-28T18:08:57+00:00</published><updated>2017-02-28T18:08:57+00:00</updated><id>https://bearandgiraffe.com/blog/dynamic-hash-in-ruby</id><content type="html" xml:base="https://bearandgiraffe.com/blog/dynamic-hash-in-ruby/"><![CDATA[<p>Consider the following scenario: You have an app that you’re working on and you have a QA team that goes through certain scenarios to test the app and its functionality. Some tasks have to be done manually, others can be helped by pre-existing data such a as a user whose trial has expired. For that we want to seed the DB with a user who signed up and whose trial expiration date has passed. It’s very common problem, which is why Ruby on Rails comes with a seed functionality baked in.</p>

<p>BUT… there are many of these kinds of scenarios, and creating and maintaining the seed code can be tedious. So you want to structure your code in a way that is maintainable. You come up with something like this:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">seed_user</span> <span class="nb">hash</span>
  <span class="k">if</span> <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">username: </span><span class="nb">hash</span><span class="p">[</span><span class="ss">:username</span><span class="p">].</span><span class="nf">downcase</span><span class="p">).</span><span class="nf">exists?</span>
    <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">username: </span><span class="nb">hash</span><span class="p">[</span><span class="ss">:username</span><span class="p">].</span><span class="nf">downcase</span><span class="p">).</span><span class="nf">first</span>
  <span class="k">else</span>
    <span class="no">User</span><span class="p">.</span><span class="nf">create</span> <span class="nb">hash</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_defaults</span> <span class="o">=</span> <span class="p">{</span>
  <span class="ss">administrator:    </span><span class="kp">false</span><span class="p">,</span>
  <span class="ss">name:             </span><span class="s1">'No Name'</span><span class="p">,</span>
  <span class="ss">password:         </span><span class="s1">'password'</span><span class="p">,</span>
  <span class="ss">trial_expiration: </span><span class="no">Time</span><span class="p">.</span><span class="nf">now</span> <span class="o">+</span> <span class="mi">30</span><span class="p">.</span><span class="nf">days</span><span class="p">,</span>
  <span class="ss">username:         </span><span class="s1">'foo'</span><span class="p">,</span>
<span class="p">}</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">######################################</span>
<span class="c1"># Admin User</span>
<span class="c1">######################################</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_specifics</span> <span class="o">=</span> <span class="p">{</span>
  <span class="ss">administrator:    </span><span class="kp">true</span><span class="p">,</span>
  <span class="ss">name:             </span><span class="s1">'Admin User'</span><span class="p">,</span>
  <span class="ss">username:         </span><span class="s1">'admin@example.com'</span><span class="p">,</span>
  <span class="ss">password:         </span><span class="s1">'admin'</span><span class="p">,</span>
<span class="p">}</span>
<span class="n">user_params</span> <span class="o">=</span> <span class="n">user_defaults</span><span class="p">.</span><span class="nf">merge</span><span class="p">(</span><span class="n">user_specifics</span><span class="p">)</span>
<span class="n">admin_user</span>  <span class="o">=</span> <span class="n">seed_user</span> <span class="n">user_params</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">######################################</span>
<span class="c1"># Expired Trial User</span>
<span class="c1">######################################</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_specifics</span> <span class="o">=</span> <span class="p">{</span>
  <span class="ss">name:             </span><span class="s1">'Expired Trial User'</span><span class="p">,</span>
  <span class="ss">username:         </span><span class="s1">'expiredTrial@example.com'</span><span class="p">,</span>
  <span class="ss">password:         </span><span class="s1">'expiredTrial'</span><span class="p">,</span>
  <span class="ss">trial_expiration: </span><span class="no">Time</span><span class="p">.</span><span class="nf">now</span><span class="p">,</span>
<span class="p">}</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_params</span>        <span class="o">=</span> <span class="n">user_defaults</span><span class="p">.</span><span class="nf">merge</span><span class="p">(</span><span class="n">user_specifics</span><span class="p">)</span>
<span class="n">expired_trial_user</span> <span class="o">=</span> <span class="n">seed_user</span> <span class="n">user_params</span>
<span class="n">expired_trial_user</span><span class="p">.</span><span class="nf">update</span> <span class="ss">trial_expiration: </span><span class="n">user_specifics</span><span class="p">[</span><span class="ss">:trial_expiration</span><span class="p">]</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># It's necessary to update the trial expiration attribute because the user creation process sets it automatically (in order to avoid people being able to pass it on and cheat).</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#... about 10 more scenarios like this.</span>
</code></pre></div></div>

<p>Looks straight forward doesn’t it?</p>

<p>Great. So we got that out of the way, but now it’s 6 months later and we’ve made an update to our model. We’ve added the concept of a payment subscription where we have a <code class="language-plaintext highlighter-rouge">Payment</code> model that can be associated with the <code class="language-plaintext highlighter-rouge">User</code> model and that payment object holds all the necessary information related to it. We don’t need to go into more detail about that structure for now. What we do know is that we now have to update our seeds. So we update the <code class="language-plaintext highlighter-rouge">user_defaults</code> hash to look like this:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_defaults</span> <span class="o">=</span> <span class="p">{</span>
  <span class="ss">administrator:    </span><span class="kp">false</span><span class="p">,</span>
  <span class="ss">name:             </span><span class="s1">'No Name'</span><span class="p">,</span>
  <span class="ss">password:         </span><span class="s1">'password'</span><span class="p">,</span>
  <span class="ss">trial_expiration: </span><span class="no">Time</span><span class="p">.</span><span class="nf">now</span> <span class="o">+</span> <span class="mi">30</span><span class="p">.</span><span class="nf">days</span><span class="p">,</span>
  <span class="ss">username:         </span><span class="s1">'foo'</span><span class="p">,</span>
  <span class="ss">payment:          </span><span class="no">Payment</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">payment_defaults</span><span class="p">),</span>
<span class="p">}</span>
</code></pre></div></div>

<p>You don’t need to worry about what <code class="language-plaintext highlighter-rouge">payment_defaults</code> is, just know that it’s some default values for the attributes related to the <code class="language-plaintext highlighter-rouge">Payment</code> model. Alright, so you are proud of yourself that you only had to add 1 line of code to support the new structure. You give yourself a pat on the back. Then a few minutes later, as you’re peeking into the development DB to check that everything look right, you notice that the 10s of users you created through the seeds all have the same <code class="language-plaintext highlighter-rouge">payment_id</code>. That’s not right!</p>

<p>It makes sense though, doesn’t it? The defaults hash got evaluated and the values set after the first use of it and then all of the users inherited the same defaults. So the same way they all will have the same <code class="language-plaintext highlighter-rouge">trial_expiration</code> date, they will also have the same <code class="language-plaintext highlighter-rouge">Payment</code> object. Hmmm… so what can we do now?</p>

<p>The first thought that comes to mind is to move the payment info from the default hash to the <code class="language-plaintext highlighter-rouge">user_specifics</code> hash. That way each user will have its own value. This will definitely solve the problem, but it doesn’t feel right. There has to be a way in Ruby where we can set values in a <code class="language-plaintext highlighter-rouge">Hash</code> to be dynamic. After all, we can do it for the keys (eg. <code class="language-plaintext highlighter-rouge">hash = {}; hash[key_name] = value</code>) so why not for the values?</p>

<p>Turns out there is not a built in way in Ruby to do this. There are a few posts out there on how to achieve this, but most resort to monkey patching the <code class="language-plaintext highlighter-rouge">Hash</code> class or created a new subclass, like the answer in this <a href="http://stackoverflow.com/questions/13431124/is-there-a-built-in-lazy-hash-in-ruby">SO question</a>:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">HashWithThunkValues</span> <span class="o">&lt;</span> <span class="no">Hash</span>
  <span class="k">def</span> <span class="nf">[]</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
    <span class="n">val</span> <span class="o">=</span> <span class="k">super</span>
    <span class="k">if</span> <span class="n">val</span><span class="p">.</span><span class="nf">respond_to?</span><span class="p">(</span><span class="ss">:call</span><span class="p">)</span>
      <span class="c1"># Force the thunk to get actual value.</span>
      <span class="n">val</span> <span class="o">=</span> <span class="n">val</span><span class="p">.</span><span class="nf">call</span>
      <span class="nb">self</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">val</span>
    <span class="k">end</span>

    <span class="n">val</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>or this other answer in the same question:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">LazyHash</span> <span class="o">&lt;</span> <span class="no">Hash</span>

  <span class="k">def</span> <span class="nf">[]</span> <span class="n">key</span>
    <span class="p">(</span><span class="n">_</span> <span class="o">=</span> <span class="p">(</span><span class="vi">@self</span><span class="o">||</span><span class="p">{})[</span><span class="n">key</span><span class="p">])</span> <span class="p">?</span> 
      <span class="p">((</span><span class="nb">self</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">_</span><span class="p">.</span><span class="nf">is_a?</span><span class="p">(</span><span class="no">Proc</span><span class="p">)</span> <span class="p">?</span> <span class="n">_</span><span class="p">.</span><span class="nf">call</span> <span class="p">:</span> <span class="n">_</span><span class="p">))</span> <span class="p">:</span> <span class="k">super</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>We don’t want to do all of that just for our seeds. Seems like overkill. Although, we might still be able to use these solutions to create our own. The idea of using a <code class="language-plaintext highlighter-rouge">Proc</code> or <code class="language-plaintext highlighter-rouge">lambda</code> as the value is what we want. So let’s update our defaults hash to:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_defaults</span> <span class="o">=</span> <span class="p">{</span>
  <span class="ss">administrator:    </span><span class="kp">false</span><span class="p">,</span>
  <span class="ss">name:             </span><span class="s1">'No Name'</span><span class="p">,</span>
  <span class="ss">password:         </span><span class="s1">'password'</span><span class="p">,</span>
  <span class="ss">trial_expiration: </span><span class="no">Time</span><span class="p">.</span><span class="nf">now</span> <span class="o">+</span> <span class="mi">30</span><span class="p">.</span><span class="nf">days</span><span class="p">,</span>
  <span class="ss">username:         </span><span class="s1">'foo'</span><span class="p">,</span>
  <span class="ss">payment:          </span><span class="o">-&gt;</span> <span class="p">{</span> <span class="no">Payment</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">payment_defaults</span><span class="p">)</span> <span class="p">},</span>
<span class="p">}</span>
</code></pre></div></div>

<p>If we leave the code as is, we’ll see the following error when we try to run the seeds:</p>

<pre><code class="language-output">NoMethodError: undefined method `primary_key' for Proc:Class
</code></pre>

<p>That’s because Rails is trying to set the <code class="language-plaintext highlighter-rouge">payment</code> association to the value of the <code class="language-plaintext highlighter-rouge">:payment</code> key in the hash, which is currently a <code class="language-plaintext highlighter-rouge">Proc</code> when it expects an <code class="language-plaintext highlighter-rouge">ActiveRecord</code> model. To make this work, we need to make sure the <code class="language-plaintext highlighter-rouge">Proc</code> is executed by calling the <code class="language-plaintext highlighter-rouge">call()</code> method on it. My initial instinct was to do it in place:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_defaults</span> <span class="o">=</span> <span class="p">{</span>
  <span class="ss">administrator:    </span><span class="kp">false</span><span class="p">,</span>
  <span class="ss">name:             </span><span class="s1">'No Name'</span><span class="p">,</span>
  <span class="ss">password:         </span><span class="s1">'password'</span><span class="p">,</span>
  <span class="ss">trial_expiration: </span><span class="no">Time</span><span class="p">.</span><span class="nf">now</span> <span class="o">+</span> <span class="mi">30</span><span class="p">.</span><span class="nf">days</span><span class="p">,</span>
  <span class="ss">username:         </span><span class="s1">'foo'</span><span class="p">,</span>
  <span class="ss">payment:          </span><span class="o">-&gt;</span> <span class="p">{</span> <span class="no">Payment</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">payment_defaults</span><span class="p">)</span> <span class="p">}.</span><span class="nf">call</span><span class="p">,</span>
<span class="p">}</span>
</code></pre></div></div>

<p>But that takes us back to the original problem we’re trying to solve since all of the users will get the same value. And we decided that we’re not going to monkey patch the <code class="language-plaintext highlighter-rouge">Hash</code> class. So we need add it somewhere else. Since we already defined a function that we use to seed the users, that is the easiest place we can add this in:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">seed_user</span> <span class="nb">hash</span>
  <span class="k">if</span> <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">username: </span><span class="nb">hash</span><span class="p">[</span><span class="ss">:username</span><span class="p">].</span><span class="nf">downcase</span><span class="p">).</span><span class="nf">exists?</span>
    <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">username: </span><span class="nb">hash</span><span class="p">[</span><span class="ss">:username</span><span class="p">].</span><span class="nf">downcase</span><span class="p">).</span><span class="nf">first</span>
  <span class="k">else</span>
    <span class="nb">hash</span><span class="p">[</span><span class="ss">:payment</span><span class="p">]</span> <span class="o">=</span> <span class="nb">hash</span><span class="p">[</span><span class="ss">:payment</span><span class="p">].</span><span class="nf">call</span> <span class="k">if</span> <span class="nb">hash</span><span class="p">[</span><span class="ss">:payment</span><span class="p">]</span>
    <span class="no">User</span><span class="p">.</span><span class="nf">create</span> <span class="nb">hash</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>In our case, we know exactly which part of the hash is a <code class="language-plaintext highlighter-rouge">Proc</code> and which isn’t. We could theoretically look through each <code class="language-plaintext highlighter-rouge">key</code> and check the <code class="language-plaintext highlighter-rouge">value</code> to see if it’s a <code class="language-plaintext highlighter-rouge">Proc</code> and then call the <code class="language-plaintext highlighter-rouge">call</code> method on it. That would be more dynamic. But again, it’s a bit of an overkill for our use case. If it’s simple and it works as is, then the answer to any other optimization is <code class="language-plaintext highlighter-rouge">YAGNI</code>. Once you do have a reason to refactor it, then how you would do that would be determined at that time. Whereas at this particular moment, <code class="language-plaintext highlighter-rouge">YOU AIN'T GONNA NEED IT!</code></p>

<p>Now, when we run the seeds, we do see that a new <code class="language-plaintext highlighter-rouge">Payment</code> object is created for each user, and each user has a unique <code class="language-plaintext highlighter-rouge">payment_id</code>. All it took was 2 new lines of code, the one in the hash and the one in the <code class="language-plaintext highlighter-rouge">seed_user</code> method. With these 2 lines of code we are able to create dynamic users with unique values for our seeds.</p>

<p>Have you needed dynamic hashes in your application? Share with us your use cases and how you solved them, we’d love to hear how others have tackled this problem.</p>]]></content><author><name></name></author><category term="ruby-on-rails" /><category term="rails" /><category term="ruby" /><summary type="html"><![CDATA[Consider the following scenario: You have an app that you’re working on and you have a QA team that goes through certain scenarios to test the app and its…]]></summary></entry><entry><title type="html">Rails: Email Previews</title><link href="https://bearandgiraffe.com/blog/rails-email-previews/" rel="alternate" type="text/html" title="Rails: Email Previews" /><published>2017-02-20T16:02:01+00:00</published><updated>2017-02-20T16:02:01+00:00</updated><id>https://bearandgiraffe.com/blog/rails-email-previews</id><content type="html" xml:base="https://bearandgiraffe.com/blog/rails-email-previews/"><![CDATA[<p>The Rails guides have a <a href="http://api.rubyonrails.org/v4.1/classes/ActionMailer/Base.html#class-ActionMailer::Base-label-Previewing+emails">section</a> about how to preview emails in your app so that you can work on them in development without the need to actually send the emails out. The process is straight forward, I’ll take you another example just in case you don’t want to open the other link :)</p>

<p>Let’s assume you’re building a simple app that asks users to sign up and once they have, you send them a welcome email. Nothing fancy. If you want to test out your email, you would create a file under the <code class="language-plaintext highlighter-rouge">test</code> directory, more precisely under the <code class="language-plaintext highlighter-rouge">test/mailers/previews/sign_up_mailer_preview.rb</code>:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Preview all emails at http://localhost:3000/rails/mailers/sign_up_mailer</span>
<span class="k">class</span> <span class="nc">SignUpMailerPreview</span> <span class="o">&lt;</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Preview</span>
 <span class="k">def</span> <span class="nf">welcome_email</span>
   <span class="no">SignUpMailer</span><span class="p">.</span><span class="nf">welcome_email</span> <span class="no">User</span><span class="p">.</span><span class="nf">first</span>
 <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>But as you can tell, this scenario assumes that you already have a user in the database, which it fetches and then uses in the email. You obviously need a user in order to mimic exactly the process of the app. But… you might not want to use data from the DB, for many reasons, one being that you might want to control exactly what data you are fetching, the first user in your DB might not represent exactly what a newly registered user looks like.</p>

<p>The other option you can opt for is using fixtures. Or in our case, using FactoryGirl:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Preview all emails at http://localhost:3000/rails/mailers/sign_up_mailer</span>
<span class="k">class</span> <span class="nc">SignUpMailerPreview</span> <span class="o">&lt;</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Preview</span>
 <span class="k">def</span> <span class="nf">welcome_email</span>
   <span class="n">user</span> <span class="o">=</span> <span class="no">FactoryGirl</span><span class="p">.</span><span class="nf">create</span><span class="p">(</span><span class="ss">:user</span><span class="p">)</span>
   <span class="no">SignUpMailer</span><span class="p">.</span><span class="nf">welcome_email</span> <span class="n">user</span>
 <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>But now we have another problem that arises, each time you try to preview the welcome email, you are creating a new user in the DB. Not only does that pollute your dev DB with unnecessary rows, it is also susceptible to validations errors, like a uniqueness validation on the email. The easy fix is to use <code class="language-plaintext highlighter-rouge">FactoryGirl.build</code> instead of <code class="language-plaintext highlighter-rouge">FactoryGirl.create</code> which does not save the user to the DB and avoids adding the rows and the validation errors. With a tiny caveat, if you are including an URL in the email that links to a path dependent on the user, like <code class="language-plaintext highlighter-rouge">profile_path(user)</code>, you would need an object that was persisted to the DB, mostly because the `to_params` in this case is returning an ID, which is then passed to the path helper, and if the object is not persisted it would not have an ID.</p>

<p>Which brings us to the next iteration:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Preview all emails at http://localhost:3000/rails/mailers/sign_up_mailer</span>
<span class="k">class</span> <span class="nc">SignUpMailerPreview</span> <span class="o">&lt;</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Preview</span>
  <span class="k">def</span> <span class="nf">welcome_email</span>
    <span class="n">mail</span> <span class="o">=</span> <span class="kp">nil</span>
   
    <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span><span class="p">.</span><span class="nf">transaction</span> <span class="k">do</span>
      <span class="n">user</span> <span class="o">=</span> <span class="no">FactoryGirl</span><span class="p">.</span><span class="nf">create</span><span class="p">(</span><span class="ss">:user</span><span class="p">)</span>
      <span class="n">mail</span> <span class="o">=</span> <span class="no">SignUpMailer</span><span class="p">.</span><span class="nf">welcome_email</span> <span class="n">user</span>
      <span class="k">raise</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Rollback</span><span class="p">,</span> <span class="err">“</span><span class="no">Don</span><span class="err">’</span><span class="n">t</span> <span class="n">really</span> <span class="n">want</span> <span class="n">these</span> <span class="n">objects</span> <span class="n">committed</span> <span class="n">to</span> <span class="n">the</span> <span class="n">db!</span><span class="err">”</span>
    <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">mail</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">ActionMailer::Preview</code> expects a <code class="language-plaintext highlighter-rouge">Mail</code> object to be returned, which is why we need to return it at the end of the method. In between, we utilize the <code class="language-plaintext highlighter-rouge">transaction</code> feature of <code class="language-plaintext highlighter-rouge">ActiveRecord</code> to create the elements and then rollback all the changes after we’re done using them in the mailer.</p>

<p>Unfortunately, we’re not done yet! This setup can get very complicated, and resource intensive. Consider the scenario where you want to send an email after a <code class="language-plaintext highlighter-rouge">Comment</code> has been posted. This <code class="language-plaintext highlighter-rouge">Comment</code> object depends on a <code class="language-plaintext highlighter-rouge">Post</code> object, which depends in turn on an <code class="language-plaintext highlighter-rouge">Author</code> object. Maybe you can also imagine the <code class="language-plaintext highlighter-rouge">Post</code> being dependent on a <code class="language-plaintext highlighter-rouge">Publication</code>, and so on and so forth. That’s a lot of set up that needs to go into the mailer preview. If you’ve done it right, you have all of those associations included in your <code class="language-plaintext highlighter-rouge">FactoryGirl</code> definitions. It is still a lot of DB objects that are being created.</p>

<p>Every once in a while, you get the following error: <code class="language-plaintext highlighter-rouge">ActiveRecord::AssociationTypeMismatch</code> with something like <code class="language-plaintext highlighter-rouge">Expected User(12345678) got User(12345679)</code> and the only difference is the ID of the object. That stumped me for a while. It expected a <code class="language-plaintext highlighter-rouge">User</code> and got a <code class="language-plaintext highlighter-rouge">User</code>. WAT?</p>

<p>From what I’ve read, Rails renders the preview in two parts. The top part that represents the headers of the email, and the bottom part which is the body of the email. So my very unscientific conclusion is that some of the objects are getting redeclared, maybe because they are getting garbage collected? If anyone has a better understanding of this issue, I definitely would appreciate a clarification.</p>

<p>To get around that problem, I’ve come up with this solution:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Preview all emails at http://localhost:3000/rails/mailers/comments_mailer</span>
<span class="k">class</span> <span class="nc">CommentsMailerPreview</span> <span class="o">&lt;</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Preview</span>
  <span class="k">def</span> <span class="nf">notify_author</span>
    <span class="n">author</span> <span class="o">=</span> <span class="no">OpenStruct</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="no">FactoryGirl</span><span class="p">.</span><span class="nf">attributes_for</span><span class="p">(</span><span class="ss">:author</span><span class="p">))</span>
    <span class="n">reader</span> <span class="o">=</span> <span class="no">OpenStruct</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="no">FactoryGirl</span><span class="p">.</span><span class="nf">attributes_for</span><span class="p">(</span><span class="ss">:reader</span><span class="p">))</span>
    <span class="n">article</span> <span class="o">=</span> <span class="no">OpenStruct</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="no">FactoryGirl</span><span class="p">.</span><span class="nf">attributes_for</span><span class="p">(</span><span class="ss">:article</span><span class="p">).</span><span class="nf">merge</span><span class="p">({</span> <span class="ss">author: </span><span class="n">author</span> <span class="p">}))</span>
    <span class="n">comment</span> <span class="o">=</span> <span class="no">OpenStruct</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="no">FactoryGirl</span><span class="p">.</span><span class="nf">attributes_for</span><span class="p">(</span><span class="ss">:comment</span><span class="p">).</span><span class="nf">merge</span><span class="p">({</span> <span class="ss">article: </span><span class="n">article</span><span class="p">,</span> <span class="ss">reader: </span><span class="n">reader</span> <span class="p">}))</span>
    <span class="no">CommentsMailer</span><span class="p">.</span><span class="nf">notify_author</span> <span class="n">comment</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>In this example, we are still using <code class="language-plaintext highlighter-rouge">FactoryGirl</code> to get the right attributes (eg. name, email, etc), with the knowledge that <code class="language-plaintext highlighter-rouge">attributes_for</code> does not return any associations. What I realized, though, is that the mailer couldn’t care less whether the objects it has are <code class="language-plaintext highlighter-rouge">ActiveRecord</code> objects or plain ole Ruby objects. At least in most instances. So, to get away from everything Rails related, <code class="language-plaintext highlighter-rouge">OpenStruct</code> is the perfect substitute as it provides the same interface and can be instantiated from the hash returned by <code class="language-plaintext highlighter-rouge">FactoryGirl.attributes_for</code>. The benefit we get from this approach is reducing the dependency on the DB and other elements that are not necessary for the task at hand.</p>

<p>We’ve covered different ways we can achieve the same outcome. Each of those has its pros and cons. Personally, I use the approach that creates <code class="language-plaintext highlighter-rouge">AR</code> objects when it’s feasible because that will mimic the real scenario more accurately, but when that fails or becomes too taxing on the app that it crashes the server locally, I resort to the <code class="language-plaintext highlighter-rouge">OpenStruct</code> approach. What strategies do you use for testing emails in development?</p>]]></content><author><name></name></author><category term="ruby-on-rails" /><category term="rails" /><category term="email" /><category term="testing" /><summary type="html"><![CDATA[The Rails guides have a section about how to preview emails in your app so that you can work on them in development without the need to actually send the…]]></summary></entry><entry><title type="html">File Upload: Rails + Refile + Dropzone</title><link href="https://bearandgiraffe.com/blog/file-upload-rails-refile-dropzone/" rel="alternate" type="text/html" title="File Upload: Rails + Refile + Dropzone" /><published>2017-02-08T16:02:04+00:00</published><updated>2017-02-08T16:02:04+00:00</updated><id>https://bearandgiraffe.com/blog/file-upload-rails-refile-dropzone</id><content type="html" xml:base="https://bearandgiraffe.com/blog/file-upload-rails-refile-dropzone/"><![CDATA[<p>Finding a good tutorial on how to add file upload to a Rails application is easy. But most of them will focus on how to integrate a specific gem like <code class="language-plaintext highlighter-rouge">paperclip</code> or <code class="language-plaintext highlighter-rouge">carrierwave</code> or <code class="language-plaintext highlighter-rouge">refile</code> into your application, but very rarely do you have a tutorial that will walk you through the full process of building out a feature from start to finish. So let’s change that…</p>

<h2 id="requirements">Requirements</h2>

<p>First, let’s start with the requirements. Let’s assume you are building an application which requires users to upload a document. That seems simple, right? It is, theoretically. In this theoretical app, we have a few models that we can represent: <code class="language-plaintext highlighter-rouge">TaskCreator</code>, <code class="language-plaintext highlighter-rouge">Task</code>, <code class="language-plaintext highlighter-rouge">TaskDoer</code>, and <code class="language-plaintext highlighter-rouge">Doc</code>.</p>

<p><code class="language-plaintext highlighter-rouge">TaskCreator</code>’s job is to create <code class="language-plaintext highlighter-rouge">Tasks</code> and assign them to a <code class="language-plaintext highlighter-rouge">TaskDoer</code>, and each <code class="language-plaintext highlighter-rouge">Task</code> will have a name which serves as the description of the <code class="language-plaintext highlighter-rouge">Doc</code> that is required from the <code class="language-plaintext highlighter-rouge">TaskDoer</code> to upload. The model architecture would look something like this:</p>

<figure>
  <img src="/assets/images/blog/file-upload-rails-refile-dropzone/1.png" alt="model architecture for our theoretical app" width="907" height="756" loading="lazy" />
  <figcaption>model architecture for our theoretical app</figcaption>
</figure>

<p>I will be leaving out some details that are outside of the scope of this post, but in a nutshell, what you need to know is that we have a <code class="language-plaintext highlighter-rouge">User</code> model that can sign in, and we have 2 types of <code class="language-plaintext highlighter-rouge">Users</code>, a <code class="language-plaintext highlighter-rouge">TaskCreator</code> and a <code class="language-plaintext highlighter-rouge">TaskDoer</code> which are what we need to focus on. In our theoretical app, a <code class="language-plaintext highlighter-rouge">User</code> can only be one of the two roles, not both. Your app design choices might be different, which is why I won’t go into details about this part. Another thing to note is that in our architecture we have an attribute called <code class="language-plaintext highlighter-rouge">number_of_items</code> on the <code class="language-plaintext highlighter-rouge">Task</code> model which allows us to specify how many <code class="language-plaintext highlighter-rouge">Docs</code> are required to be uploaded for each <code class="language-plaintext highlighter-rouge">Task</code>. For the sake of this post, we will assume all <code class="language-plaintext highlighter-rouge">Tasks</code> require only 1 <code class="language-plaintext highlighter-rouge">Doc</code> but you can see how this can be flexible and allow for multiples if your app requires it.</p>

<p>So far so good, the requirements are clear, but there’s one component that is missing which will drive some of the technical decisions. That component is the UI. So here’s a quick sketch:</p>

<figure>
  <img src="/assets/images/blog/file-upload-rails-refile-dropzone/2.jpg" alt="List of Tasks" width="1024" height="768" loading="lazy" />
  <figcaption>List of Tasks</figcaption>
</figure>

<figure>
  <img src="/assets/images/blog/file-upload-rails-refile-dropzone/3.jpg" alt="Upload modal" width="1024" height="768" loading="lazy" />
  <figcaption>Upload modal</figcaption>
</figure>

<figure>
  <img src="/assets/images/blog/file-upload-rails-refile-dropzone/4.jpg" alt="Upload complete" width="1024" height="768" loading="lazy" />
  <figcaption>Upload complete</figcaption>
</figure>

<p>Note: Keynote (or PowerPoint) can be a handy tool for quick sketching wireframes, you don’t need a fancy tool to do that.</p>

<p>The hidden requirements that were extracted from these sketches is that the UI will have a list of <code class="language-plaintext highlighter-rouge">Tasks</code> that are assigned to a <code class="language-plaintext highlighter-rouge">TaskDoer</code>, once the <code class="language-plaintext highlighter-rouge">TaskDoer</code> clicks on the <code class="language-plaintext highlighter-rouge">upload</code> button, a modal will pop up asking the <code class="language-plaintext highlighter-rouge">TaskDoer</code> to upload a <code class="language-plaintext highlighter-rouge">Doc</code> either by drag/drop over the drop area (which is the cloud icon) or by using the native browse functionality. Once the upload is complete the list of <code class="language-plaintext highlighter-rouge">Tasks</code> is automatically updated to mark the <code class="language-plaintext highlighter-rouge">Task</code> as complete by switching the button text from <code class="language-plaintext highlighter-rouge">Upload</code> to <code class="language-plaintext highlighter-rouge">View</code> and color from blue to green. For simplicity, we will assume that a <code class="language-plaintext highlighter-rouge">Task</code> is complete if it has a <code class="language-plaintext highlighter-rouge">Doc</code> associated with it, but completed <code class="language-plaintext highlighter-rouge">Tasks</code> will be grouped together at the bottom of the list and pending ones will be grouped at the top of the list.</p>

<p>Here’s the interaction as a <code class="language-plaintext highlighter-rouge">gif</code> because you can’t have a serious post without a <code class="language-plaintext highlighter-rouge">gif</code>:</p>

<figure>
  <img src="/assets/images/blog/file-upload-rails-refile-dropzone/5.gif" alt="Upload experience" width="1024" height="768" loading="lazy" />
  <figcaption>Upload experience</figcaption>
</figure>

<p>So, to make the obvious clear we will need a way to handle both the native browse functionality to select files to upload and the drag and drop method. While making it all happen without reloading the page. You might be expecting me here to say that I will be using something like <code class="language-plaintext highlighter-rouge">ReactJS</code> or <code class="language-plaintext highlighter-rouge">AngularJS</code> to handle the process in the browser, but as you can tell from the title of the post, I won’t. But I will note that handling the list of <code class="language-plaintext highlighter-rouge">Tasks</code> and updating based on each one’s status is a good candidate for something like <code class="language-plaintext highlighter-rouge">React</code>, but when it’s possible to avoid using another dependency that usually wins for me, especially when the new dependency has the potential of adding complexity instead of reducing it. As you will see from the rest of the post that in this case using what <code class="language-plaintext highlighter-rouge">Rails</code> gives us will be super simple, but then again, this is a theoretical app with its complexity reduced fictitiously so YMMV.</p>

<h2 id="tech-choices">Tech Choices</h2>

<h3 id="ruby-onrails">Ruby on Rails</h3>

<p><code class="language-plaintext highlighter-rouge">Rails</code> is an obvious choice for me. It’s a powerful framework that lets me focus on the business requirements while its convention over configuration philosophy reduces the amount of repetitive work I need to do. Looking at the model architecture from above you will see that the most intricate part is the associations between the models but with <code class="language-plaintext highlighter-rouge">Rails</code>’ <code class="language-plaintext highlighter-rouge">has_one</code> / <code class="language-plaintext highlighter-rouge">has_many</code> / <code class="language-plaintext highlighter-rouge">belongs_to</code> methods that are provided by <code class="language-plaintext highlighter-rouge">ActiveRecord</code> we won’t have much work to do on that front and we can focus on the important part which is to provide the user the best experience handling the file uploads.</p>

<h3 id="refile">Refile</h3>

<p>There are a couple of gems that handle file uploads in <code class="language-plaintext highlighter-rouge">Ruby</code> and <code class="language-plaintext highlighter-rouge">paperclip</code> might be the most known one, but I had a great experience using <code class="language-plaintext highlighter-rouge">carrierwave</code> in the past on many projects and <code class="language-plaintext highlighter-rouge">refile</code> is the better, more modern version of that written by the same people. It does say “Ruby file uploads, take 3” on the project <code class="language-plaintext highlighter-rouge">github</code> <a href="https://github.com/refile/refile">page</a> after all, which means that all of the lessons learned from the first couple of times have led to a better tool this time around.</p>

<h3 id="dropzonejs">DropzoneJS</h3>

<p>After some quick googling to see what people are using for a drag and drop solution, I landed on the <code class="language-plaintext highlighter-rouge">DropzoneJS</code> <a href="http://www.dropzonejs.com/">website</a> and that seemed to provide the cleanest solution of all of the ones I had seen, and a good documentation. A nice looking site also helps when you’re trying to learn a new tool, because ugly sites are hard to read and if it’s hard to read it’s hard to comprehend. So that was my choice for this piece of the puzzle.</p>

<p>If you have a suggestion for another library to use, share it with us.</p>

<h2 id="time-tobuild">Time to Build</h2>

<p>Let’s get to the code, shall we?</p>

<h3 id="user-stories">User Stories</h3>

<p>First, we start with the user story description:</p>

<p>The story above sets up the scenario we care about but is outside of the scope of this post, so I’ll let you fill in the details. The one we care about the most is this one:</p>

<p>and with that goes the steps implementation:</p>

<p>That’s a lot of code. Most of it is not specific to our case, it’s code that you would use to test any feature using <code class="language-plaintext highlighter-rouge">capybara</code> and <code class="language-plaintext highlighter-rouge">cucumber</code>. The one thing worth noting is that <code class="language-plaintext highlighter-rouge">capybara</code> gives us a helper method that we can use to simulate someone attaching a file <code class="language-plaintext highlighter-rouge">attach_file</code>. You may have noticed that we’re lacking code to test the drag and drop feature, which is impossible to do. In either case, we wouldn’t want to test the functionality of libraries that we use anyway. We are not concerned with testing <code class="language-plaintext highlighter-rouge">Rails</code> functionality, neither would be concerned with testing <code class="language-plaintext highlighter-rouge">refile</code> nor <code class="language-plaintext highlighter-rouge">dropzonejs</code>. What we do want to test however is that the workflow we’ve described works. In other words, do the things we expect to happen after a user’s interaction do indeed happen. And that’s what you see in our example, we test that the user is seeing the right feedback messages, an email is sent out, etc.</p>

<p>Of course, none of this code will pass at the moment because we have not yet implemented any of it. So we should get to that next.</p>

<p><strong>DISCLAIMER:</strong> I would not normally write out the entire set of tests first before doing any code. I would build it out piece by piece and get the first test to pass and move on to the next. But as of this writing, Medium does not support pasting in individual files from a <code class="language-plaintext highlighter-rouge">gist</code>, instead, it spits out all of the files of a <code class="language-plaintext highlighter-rouge">gist</code> together, which means if I only want to show one snippet at a time I have to create a separate <code class="language-plaintext highlighter-rouge">gist</code> for each. That can be very tedious. So instead, I’ve created a separate <code class="language-plaintext highlighter-rouge">gist</code> for each file, and that’s what you see. Just keep that in mind if you ever feel that it would be daunting to try to reproduce this effort yourself.</p>

<h3 id="gems">Gems</h3>

<p>The next step would be to install the gems, add the following to your <code class="language-plaintext highlighter-rouge">Gemfile</code>:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Use Dropzone for drag and drop of document to upload.</span>
<span class="n">gem</span> <span class="s1">'dropzonejs-rails'</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Use Refile for uploading document</span>
<span class="n">gem</span> <span class="s1">'refile'</span><span class="p">,</span> <span class="ss">require: </span><span class="p">[</span><span class="s1">'refile/rails'</span><span class="p">,</span> <span class="s1">'refile/simple_form'</span><span class="p">],</span> <span class="ss">github:  </span><span class="s1">'manfe/refile'</span>
<span class="n">gem</span> <span class="s1">'refile-mini_magick'</span>
<span class="n">gem</span> <span class="s1">'refile-s3'</span>
</code></pre></div></div>

<p>and run <code class="language-plaintext highlighter-rouge">bundle install</code>. Note that we are using the <code class="language-plaintext highlighter-rouge">'manfe/refile</code> fork because of a <code class="language-plaintext highlighter-rouge">Rails 5</code> compatibility issue currently. You might not need to do that, so check the gem’s page for the latest info.</p>

<h3 id="ui">UI</h3>

<p>From here I like to work backwards from the UI to the backend. The reason I like to do that is because I want to work from the user’s perspective, not the developer’s perspective. It’s the same reason I write the feature descriptions first (the <code class="language-plaintext highlighter-rouge">cucumber</code> tests from above). User behavior is the primary driver for the design of the app. When working in this manner I tend to notice many things that I had not thought of at first glance when I started architecting the feature and it allows me to go back to the user stories and update them. These changes usually come at no cost because I still have not implemented any code, which means that the design of the code structure can change easily.</p>

<p>I am going to skip the part where the <code class="language-plaintext highlighter-rouge">TaskCreator</code> creates the <code class="language-plaintext highlighter-rouge">Tasks</code>, that could be a good exercise for you to do on your own. Instead, I’m going to pick up from the <code class="language-plaintext highlighter-rouge">TaskDoer</code>’s perspective. Which means a bunch of <code class="language-plaintext highlighter-rouge">Tasks</code> has already been created, and the <code class="language-plaintext highlighter-rouge">TaskDoer</code> is looking at their dashboard with a list of <code class="language-plaintext highlighter-rouge">Tasks</code> and wants to upload a <code class="language-plaintext highlighter-rouge">Doc</code> for one of them. For that, we assume that we have a <code class="language-plaintext highlighter-rouge">Dashboard</code> controller that fetches all the <code class="language-plaintext highlighter-rouge">Tasks</code> associated with the <code class="language-plaintext highlighter-rouge">TaskDoer</code> and then lists them out. In other words, the <code class="language-plaintext highlighter-rouge">index.html.erb</code> view template has the following code:</p>

<div class="language-erb highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s1">'tasks/list'</span><span class="p">,</span> <span class="ss">locals: </span><span class="p">{</span> <span class="ss">completed_tasks: </span><span class="vi">@completed_tasks</span><span class="p">,</span> <span class="ss">pending_tasks: </span><span class="vi">@pending_tasks</span> <span class="p">}</span> <span class="cp">%&gt;</span>
</code></pre></div></div>

<p>Where the <code class="language-plaintext highlighter-rouge">tasks/_list.html.erb</code> partial is the following:</p>

<p>I’ve removed any classes or styling related info from this <code class="language-plaintext highlighter-rouge">HTML</code> snippet and kept only the necessary stuff. We have a heading at the top that lets the user know how many completed and pending <code class="language-plaintext highlighter-rouge">Tasks</code> there are, and then lists each group separately since our requirement was to group the completed <code class="language-plaintext highlighter-rouge">Tasks</code> at the bottom. This part is also very simple, the real work starts in the upload modal we referenced on line <code class="language-plaintext highlighter-rouge">27</code>.</p>

<p>Obviously, for the modal we are using <code class="language-plaintext highlighter-rouge">Bootstrap</code> but you can ignore that part. The first thing to note <code class="language-plaintext highlighter-rouge">&lt;%= simple_form_for @doc, remote: true, html: { class: ‘dropzone' } do |f| %&gt;</code>, and more specifically <code class="language-plaintext highlighter-rouge">remote: true</code> and <code class="language-plaintext highlighter-rouge">class: 'dropzone'</code>. We want the form to submit the <code class="language-plaintext highlighter-rouge">Doc</code> remotely so we can update the list without refreshing the page, and <code class="language-plaintext highlighter-rouge">DropzoneJS</code> requires us to add the <code class="language-plaintext highlighter-rouge">dropzone</code> class to our <code class="language-plaintext highlighter-rouge">form</code>.</p>

<p>Then comes the part below <code class="language-plaintext highlighter-rouge">&lt;!-- Dropzone --&gt;</code> which specifies the area that we want to consider the drop zone for the drag and drop and matches the template that we saw in the wireframes above. We have the cloud icon and the fake button that serves as a visual cue but in fact, if the user clicks on any part of that whole area the file browser will pop up since we specifically designated it all with the tag <code class="language-plaintext highlighter-rouge">data-dz-clickable</code>. Then we have the part that glues it all together which is this <code class="language-plaintext highlighter-rouge">&lt;%= f.input :file, as: :attachment, direct: true, label: false, input_html: { class: 'hidden' } %&gt;</code>. This is the part that lets <code class="language-plaintext highlighter-rouge">refile</code> upload the document to the server and attach it to the <code class="language-plaintext highlighter-rouge">Doc</code>. We want it hidden because we don’t want to show the default file input the browser displays, instead, we’re using the layout we mentioned as the visual element that lets the user know that they need to upload a file and how to do it.</p>

<p>We then have the preview section that we use to preview files that are images. You can leave that out or use the default template that <code class="language-plaintext highlighter-rouge">DropzoneJS</code> provides. In our case we just want to show the <code class="language-plaintext highlighter-rouge">filename</code> and the <code class="language-plaintext highlighter-rouge">size</code> of the file, and in case it’s an image display the thumbnail. Then we’ve set up a progress bar that will display the progress of the upload as it happens. That’s pretty much it for the template. Next, we’ll take a look as the <code class="language-plaintext highlighter-rouge">js</code> that makes it all work as expected.</p>

<h3 id="js">JS</h3>

<p>To make <code class="language-plaintext highlighter-rouge">DropzoneJS</code> hook into our form, we need to add some configurations using <code class="language-plaintext highlighter-rouge">js</code>, so let’s add a <code class="language-plaintext highlighter-rouge">uplod_doc.coffee</code> file to our assets and require it into our <code class="language-plaintext highlighter-rouge">application.js</code> manifest (I’ll let you handle that part on your own).</p>

<p>In our case, we’re customizing quite a bit of the <code class="language-plaintext highlighter-rouge">DropzoneJS</code>’s behavior. We don’t want it to do anything automatically for us because we have multiple <code class="language-plaintext highlighter-rouge">Tasks</code> on the same page and each one of them has its own modal which then contains its own specific form. So we want to avoid the library trying to attach a <code class="language-plaintext highlighter-rouge">dropzone</code> to the same area multiple times because that will result in errors and weird behavior. And we want it to be active only if the modal is visible. That explains lines <code class="language-plaintext highlighter-rouge">2</code>, <code class="language-plaintext highlighter-rouge">4</code>, and <code class="language-plaintext highlighter-rouge">9</code>.</p>

<p>Then we’ve specified some of the options that <code class="language-plaintext highlighter-rouge">DropzoneJS</code> makes available to us. Primarily we only want one <code class="language-plaintext highlighter-rouge">Doc</code> per upload, and we told it which <code class="language-plaintext highlighter-rouge">input</code> to use as the file input by specifying the <code class="language-plaintext highlighter-rouge">paramName</code>. We don’t want it to process the file before the user clicks on the <code class="language-plaintext highlighter-rouge">Upload</code> button, so we set <code class="language-plaintext highlighter-rouge">autoProcessQueue</code> to <code class="language-plaintext highlighter-rouge">false</code>.</p>

<p>In this snippet:</p>

<div class="language-coffeescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">maxfilesexceeded</span><span class="o">:</span> <span class="p">(</span><span class="nx">file</span><span class="p">)</span> <span class="o">-&gt;</span>
  <span class="k">this</span><span class="p">.</span><span class="na">removeAllFiles</span><span class="p">()</span>
  <span class="k">this</span><span class="p">.</span><span class="na">addFile</span><span class="p">(</span><span class="nx">file</span><span class="p">)</span>
</code></pre></div></div>

<p>we are making sure that if the user selects a new file after already selecting one, that it overrides it instead of trying to upload both ( <code class="language-plaintext highlighter-rouge">DropzoneJS</code> lets you select and upload multiple files at the same time, but that’s not what we want for our app).</p>

<p>Skipping ahead to line <code class="language-plaintext highlighter-rouge">47</code>, here we specifying that once the button is clicked and there are files in the queue to be uploaded, we should disable the button and replace the text with a sinner, then process the queue. Then on line <code class="language-plaintext highlighter-rouge">44</code> we listen to the event broadcasted by <code class="language-plaintext highlighter-rouge">DropzoneJS</code> which returns the progress of the upload and update the progress bar.</p>

<p>Now back to line <code class="language-plaintext highlighter-rouge">21</code> which handles the response of the call once it’s done. First, it restores the button back to its original state (re-enables it and removes the spinner), then it hides the modal and displays the success message. Then we want to update the list of <code class="language-plaintext highlighter-rouge">Tasks</code> so in this case, we make another call to fetch the updated list. This where using something like <code class="language-plaintext highlighter-rouge">AngularJS</code> or <code class="language-plaintext highlighter-rouge">ReactJS</code> would have been handy to clean this up. But since I said we were going to keep it simple, the 2 <code class="language-plaintext highlighter-rouge">$.get</code> calls will have to do.</p>

<p>Lines <code class="language-plaintext highlighter-rouge">68</code> to <code class="language-plaintext highlighter-rouge">78</code> don’t do a lot in this case. They hook into the <code class="language-plaintext highlighter-rouge">Refile</code> event listeners and update the state of the button when the upload is triggered and complete. It’s a bit redundant since we are already handling this in the code before it, but I left it there to illustrate that it’s something available to you to use.</p>

<p>If you’ve gotten this far, you have a modal that pops up for the user to upload a <code class="language-plaintext highlighter-rouge">Doc</code> and the user can either drag and drop or select a file from the file browser. Once they do that though, they might see the preview but the upload does not work. So we should have 1 or 2 passing scenarios but that’s about it. Time to make them all pass.</p>

<h3 id="backend">Backend</h3>

<p>We’ve gotten this far without writing too much <code class="language-plaintext highlighter-rouge">Ruby</code> or <code class="language-plaintext highlighter-rouge">Rails</code> code if you haven’t noticed, so let’s get to it already.</p>

<p>Based on the work we’ve already done, we know exactly which routes we need. Those were determined by the tests and by the work we did in the UI. We don’t have to guess whether we need a certain route or controller, we already know, and that’s a big benefit of working through it while being mindful of the user interaction.</p>

<p>Here are the routes we need:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">resources</span> <span class="ss">:docs</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span> <span class="ss">:create</span><span class="p">,</span> <span class="ss">:show</span><span class="p">,</span> <span class="ss">:update</span> <span class="p">]</span> <span class="k">do</span>
  <span class="n">collection</span> <span class="k">do</span>
    <span class="n">get</span> <span class="s1">'/reload'</span> <span class="o">=&gt;</span> <span class="s1">'docs#reload'</span>
  <span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="n">member</span> <span class="k">do</span>
    <span class="n">get</span> <span class="s1">'/reload'</span> <span class="o">=&gt;</span> <span class="s1">'docs#reload_doc'</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>which tells us that we need a <code class="language-plaintext highlighter-rouge">DocsController</code>:</p>

<p>Quick note, we haven’t mentioned view a <code class="language-plaintext highlighter-rouge">Doc</code> before but in the controller you might have noticed the <code class="language-plaintext highlighter-rouge">show</code> action. This is another example of what you might be able to do even though it might not fit in our theoretical app per se.</p>

<p>The relevant section is in the <code class="language-plaintext highlighter-rouge">create</code> action. You might be wondering what’s up with the <code class="language-plaintext highlighter-rouge">@operation</code>, <code class="language-plaintext highlighter-rouge">@model</code>, and <code class="language-plaintext highlighter-rouge">@form</code> objects are all about. They come from using <code class="language-plaintext highlighter-rouge">trailblazer</code> and that’s a topic for another day. What you need to know is that the <code class="language-plaintext highlighter-rouge">trailblazer</code> operation takes the form params, runs the appropriate validations, and then process them according to whichever business logic you specify. In this case, it looks something like this:</p>

<p>Which basically takes the <code class="language-plaintext highlighter-rouge">params</code> passed the controller, which includes the <code class="language-plaintext highlighter-rouge">Task</code> <code class="language-plaintext highlighter-rouge">id</code>, the <code class="language-plaintext highlighter-rouge">file</code>, and the <code class="language-plaintext highlighter-rouge">current_user</code> and creates a <code class="language-plaintext highlighter-rouge">Doc</code> object and saves it to the database. Our <code class="language-plaintext highlighter-rouge">Doc</code> model is the following:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Doc</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span>
  <span class="c1"># Associations</span>
  <span class="n">belongs_to</span> <span class="ss">:task</span>
  <span class="n">belongs_to</span> <span class="ss">:uploader</span><span class="p">,</span> <span class="ss">class_name: </span><span class="s1">'TaskDoer'</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="n">attachment</span> <span class="ss">:file</span><span class="p">,</span>
    <span class="ss">extension:    </span><span class="sx">%w[pdf jpg jpeg gif png]</span><span class="p">,</span>
    <span class="ss">content_type: </span><span class="sx">%w[image/jpeg image/png image/gif application/pdf]</span>
<span class="k">end</span>
</code></pre></div></div>

<p>and the missing piece is the template that goes with the <code class="language-plaintext highlighter-rouge">create</code> action:</p>

<p>which takes care of loading the <code class="language-plaintext highlighter-rouge">DOM</code> with the updated list of <code class="language-plaintext highlighter-rouge">Tasks</code>.</p>

<p>That’s it! Easy, right?</p>

<p>I have mostly talked about the <code class="language-plaintext highlighter-rouge">create</code> action but the code you see includes parts that are used for the <code class="language-plaintext highlighter-rouge">update</code> action, which is very similar even though I have not specifically talked about or included all the required pieces. I trust you’d be able to fill in the blanks.</p>

<p>I hope this can help you implement file uploads in <code class="language-plaintext highlighter-rouge">Rails</code> with drag and drop capabilities, and customize it to your own needs.</p>

<p><strong>DISCLAIMER:</strong> This post did not tackle the issue of security. Could be a topic for another post in the future. So be sure to follow and be on the lookout for more content like this.</p>]]></content><author><name></name></author><category term="ruby-on-rails" /><category term="rails" /><category term="file-uploads" /><summary type="html"><![CDATA[Finding a good tutorial on how to add file upload to a Rails application is easy. But most of them will focus on how to integrate a specific gem like…]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://bearandgiraffe.com/assets/images/blog/file-upload-rails-refile-dropzone/1.png" /><media:content medium="image" url="https://bearandgiraffe.com/assets/images/blog/file-upload-rails-refile-dropzone/1.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>