<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andy Croll on Medium]]></title>
        <description><![CDATA[Stories by Andy Croll on Medium]]></description>
        <link>https://medium.com/@andycroll?source=rss-72c0199c4d91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HQkEiO6geuDo_0kA.png</url>
            <title>Stories by Andy Croll on Medium</title>
            <link>https://medium.com/@andycroll?source=rss-72c0199c4d91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:29:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andycroll/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Enumerable avoids using temporary variables when looping]]></title>
            <link>https://medium.com/@andycroll/enumerable-avoids-using-temporary-variables-when-looping-253c5558e3ae?source=rss-72c0199c4d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/253c5558e3ae</guid>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[loop]]></category>
            <dc:creator><![CDATA[Andy Croll]]></dc:creator>
            <pubDate>Fri, 16 Mar 2018 22:28:03 GMT</pubDate>
            <atom:updated>2018-03-16T22:28:03.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPoIKcRHbEGGUMFuWmC0Og.jpeg" /></figure><p>Some of my favourite Ruby features are to be found in the Enumerable module. You can read more about it in the <a href="http://ruby-doc.org/core-2.5.0/Enumerable.html">Ruby documentation</a>.</p><p>A class representing a collection, such as Array, Set or Hash, has the methods and features of Enumerable included. These methods allow you to loop through the members of that group and take an action using each member of the collection as an input.</p><h3>Instead of…</h3><p>…using a C-style loop with a temporary variable, which would be fine in many other languages.</p><pre>total = 0<br>[1, 3, 5, 7].each do |num|<br>  total += num<br>end<br>total</pre><h3>Use…</h3><p>…your deep love of one of Ruby’s Enumerable methods, and implement using #inject.</p><pre>[1, 3, 5, 7].inject(0) do |total, number|<br>  total += number<br>end</pre><h3>Or better…</h3><p>…there’s a convenient #sum method in Enumerable.</p><pre>[1, 3, 5, 7].sum</pre><h3>But why?</h3><p>The longer I’ve used Ruby the more joy I find in the elegance enabled by its Enumerable methods. Using these constructions lead you write <em>idiomatic</em> Ruby, which is a smart sounding way of saying you’re writing Ruby in a Ruby-ish manner.</p><p>When dealing with larger loops there are often significant improvements to memory usage and speed when using built-in Enumerable methods.</p><p>If you ever see the “temporary variable setup” at the beginning of a loop there’s most likely an opportunity to express yourself more concisely with an Enumerable method.</p><h3>Why not?</h3><p>Methods like #inject might seem confusing and be unfamiliar to newer Rubyists. They are a fundamental benefit of using Ruby, so you might as well dive in.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fa59077%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fa59077&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Fa59077%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href">https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href</a></iframe><p><em>Originally published at </em><a href="https://andycroll.com/ruby/enumerable-avoids-using-temporary-variables/"><em>andycroll.com</em></a><em>.</em></p><p>Sign up to the <a href="https://onerubything.com/">One Ruby Thing</a> email and get my next post in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=253c5558e3ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be sparing when using unless]]></title>
            <link>https://medium.com/@andycroll/be-sparing-when-using-unless-d4efe5b5300c?source=rss-72c0199c4d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4efe5b5300c</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andy Croll]]></dc:creator>
            <pubDate>Fri, 16 Mar 2018 22:23:50 GMT</pubDate>
            <atom:updated>2018-03-16T22:23:50.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8LO4Bb0JCLxwuuLCq0nUQ.jpeg" /></figure><p>One of Ruby’s strengths is its delightful, built-in syntactic sugar. One example of this is the keyword unless, which you can use in place of using if combined with a negative statement.</p><p>However, given the flexibility of Ruby’s syntax, it is easy to make code harder to understand than it needs to be.</p><h3>Instead of…</h3><p>…using unless in ways that makes your brain hurt.</p><pre># Example 1<br>unless something?<br>  # do something<br>else<br>  # do other thing<br>end</pre><pre># Example 2<br>unless something? || another_thing?<br>  # do something<br>end</pre><h3>Use…</h3><p>…if where it makes the code clearer.</p><pre># Example 1<br>if !something?<br>  # do other thing<br>else<br>  # do something<br>end</pre><pre># Example 2<br>if !something? &amp;&amp; !another_thing?<br>  # do something<br>end</pre><h3>But why?</h3><p>Avoid using an else block with an unless. This structure is hard to reason about because the else block is a double negative: it is “not not” the specified condition. Instead, replace the unless with an if, taking care to refactor the condition statement as needed, then swap around the blocks of code in the main and else branches.</p><p>It is <em>much</em> harder to understand the code when using an unless conditional with boolean algebra (&amp;&amp; or ||). It is an easy way to confuse yourself! The conditional unless one &amp;&amp; two is equivalent to if !one || !two. Although the logic looks messier the positive version is easier to reason about.</p><p>A complex if condition might well be an opportunity to extract the conditional into a well-named method so it can be more easily understood.</p><h3>Why not?</h3><p>I’m definitely not saying don’t use unless, but it’s important to remember it is <em>sugar</em> and thus important only to use it where it makes the resulting code clearer.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fa59077%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fa59077&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Fa59077%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href">https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href</a></iframe><p><em>Originally published at </em><a href="https://andycroll.com/ruby/be-sparing-when-using-unless/"><em>andycroll.com</em></a><em>.</em></p><p>Sign up to the <a href="https://onerubything.com/">One Ruby Thing</a> email and get my next post in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4efe5b5300c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Truthiness in Conditionals]]></title>
            <link>https://medium.com/@andycroll/truthiness-in-conditionals-681b04e7d829?source=rss-72c0199c4d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/681b04e7d829</guid>
            <category><![CDATA[truth]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Andy Croll]]></dc:creator>
            <pubDate>Fri, 16 Mar 2018 22:08:45 GMT</pubDate>
            <atom:updated>2018-03-16T22:08:45.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BShmRBOSyQaZDJOI9uF67Q.jpeg" /></figure><p>Ruby’s conditional syntax is ‘truthy’, meaning that any statement in a conditional that evaluates to nil is considered to be equivalent to false and anything not-nil can be considered to be true.</p><h3>Instead of…</h3><p>…overcomplicating your conditions.</p><pre># Example 1<br>unless something.nil?<br>  # do something<br>end</pre><pre># Example 2<br>if !something.nil?<br>  # do something<br>end</pre><pre># Example 3<br>if !!something<br>  # do something<br>end</pre><h3>Use…</h3><pre># Instead of Examples 1,2 &amp; 3<br>if something<br>  # do something<br>end</pre><h3>But why?</h3><p>Performing a #nil? check as part of a statement in a negative conditional, as in the first two examples (unless or if !), is often redundant. Any nil value is ‘falsey’, so you can achieve the same result with a positive conditional and no #nil? check.</p><p>Remove the nil? check and substitute the unless for an if (example 1) or remove the ! (example 2) and end up with clearer code that means the same thing.</p><p>The syntax of !!, in the third example, is shorthand for turning any value (either ‘truthy’ or ‘falsey’) into the <em>actual boolean values</em> true or false. However, given Ruby’s ‘truthy’ conditionals performing this conversion is redundant.</p><h3>Why not?</h3><p>This comes down to understandability. If you <em>really</em> are checking for nil — perhaps you’re treating an empty array and nil in different ways — then, by all means, explicitly use the check.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fa59077%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fa59077&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Fa59077%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href">https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href</a></iframe><p><em>Originally published at </em><a href="https://andycroll.com/ruby/truthiness-in-conditionals/"><em>andycroll.com</em></a><em>.</em></p><p>Sign up to the <a href="https://onerubything.com/">One Ruby Thing</a> email and get my next post in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=681b04e7d829" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set your page title in the view template using content_for]]></title>
            <link>https://medium.com/@andycroll/set-your-page-title-in-the-view-template-using-content-for-9da6a7c7befe?source=rss-72c0199c4d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/9da6a7c7befe</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[title]]></category>
            <dc:creator><![CDATA[Andy Croll]]></dc:creator>
            <pubDate>Sun, 04 Mar 2018 13:32:01 GMT</pubDate>
            <atom:updated>2018-03-16T22:00:50.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oe0cQf5UfFKsUQUNhpA5-A.jpeg" /></figure><p>Rails uses content_for as its primary way to store content in one place for use in other views, layouts or helpers. Find out more about content_for in the Rails documentation in the <a href="http://api.rubyonrails.org/v5.1.3/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for">ActionView helpers</a> section.</p><h3>Instead of…</h3><p>…using an instance variable in the controller…</p><h4>things_controller.rb</h4><pre>def show<br>  @page_title = &#39;Page Title&#39;<br>  # other controller stuff<br>end</pre><h4>And views/layouts/application.html.erb</h4><p>In the &lt;head&gt;.</p><pre>&lt;title&gt;&lt;%= @page_title || &#39;Default&#39; %&gt;&lt;/title&gt;</pre><h3>Use…</h3><p>…content_for and yield.</p><h4>things/show.html.erb</h4><p>I like to put the title at the top of the individual view file.</p><pre>&lt;% content_for(:html_title) { &#39;Title&#39; } %&gt;</pre><h3>And views/layouts/application.html.erb</h3><p>In the &lt;head&gt;.</p><pre>&lt;title&gt;<br>  &lt;%= content_for?(:html_title) ? yield(:html_title) : &quot;Default&quot; %&gt;<br>&lt;/title&gt;</pre><h3>But why?</h3><p>Using content_for keeps information about how to render the HTML inside the relevant view template, avoiding cluttering the controller with non-business logic.</p><p>You avoid creating yet another ‘magic’ instance variable that gets automatically passed to the view by Rails.</p><p>The content for the &lt;title&gt; is not referenced or referred to when rendering JSON or AJAX from the same controller action. Only the rendered HTML ever accesses that information. Therefore, there’s no need to expose this information in an instance variable: it belongs solely in the html.erb view template.</p><h3>Why not?</h3><p>You <em>are</em> ignoring the framework’s tools if you use the instance variable approach, but it <em>does</em> work.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fa59077%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fa59077&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Fa59077%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/08697e2378d3162b241b4b806c1013f9/href">https://medium.com/media/08697e2378d3162b241b4b806c1013f9/href</a></iframe><p><em>Originally published at </em><a href="https://andycroll.com/ruby/set-title-in-the-view-template-using-content-for/"><em>andycroll.com</em></a><em>.</em></p><p>Sign up to the <a href="https://onerubything.com/">One Ruby Thing</a> email and get my next post in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9da6a7c7befe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choose UUIDs for model IDs in Rails]]></title>
            <link>https://medium.com/@andycroll/choose-uuids-for-model-ids-in-rails-5afc6007e11d?source=rss-72c0199c4d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/5afc6007e11d</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[uuid]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Andy Croll]]></dc:creator>
            <pubDate>Sun, 04 Mar 2018 13:25:36 GMT</pubDate>
            <atom:updated>2018-03-16T22:01:12.015Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5fPSOvceEWF_8LH8XT4SA.jpeg" /></figure><p>A <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">universally unique identifier</a> (UUID) is a 128-bit number used to identify information in computer systems. Sometimes it is referred to as a ‘globally unique identifier’.</p><p>These are a native column type in PostgreSQL. You can find more details on native Postgres types in the <a href="http://guides.rubyonrails.org/active_record_postgresql.html">Rails Guides</a>.</p><h3>Instead of…</h3><p>…using Rails’ default incrementing integer id.</p><h3>Use…</h3><p>…PostgreSQL’s UUID support. Ruby on Rails has had the <a href="https://github.com/rails/rails/pull/21762">ability</a> to use UUIDs as the id for ActiveRecord models since version 5.0.</p><h4>Enable the PostgreSQL extension</h4><p>bin/rails g migration enable_extension_for_uuid</p><pre>class EnableExtensionForUuid &lt; ActiveRecord::Migration[5.1]<br>  def change<br>    enable_extension &#39;pgcrypto&#39; unless extension_enabled?(&#39;pgcrypto&#39;)<br>  end<br>end</pre><h4>Create config/initializers/generators.rb</h4><pre>Rails.application.config.generators do |g|<br>  g.orm :active_record, primary_key_type: :uuid<br>end</pre><p>This changes the default column type for primary keys, configuring your migration generator to set id: :uuid for new tables.</p><h4>In future migrations</h4><p>You’ll have to use type: :uuid when creating relations.</p><pre>class AddNewTable &lt; ActiveRecord::Migration[5.1]<br>  def change<br>    create_table :related_model do |t|<br>      t.references :other, type: :uuid, index: true<br>    end<br>  end<br>end</pre><h3>But why?</h3><p>Using UUIDs as the id in your Rails models instead of incrementing integers helps you avoid collisions. The UUIDs are <em>globally</em> unique meaning you can know that different models cannot possibly have the same id and you can even assign them client-side or in other systems.</p><p>With an incrementing integer id the size of your data can be inferred from the outside i.e. id 5 is the fifth record created. With UUIDs no-one can guess the size of your database tables, which might be information you are keen to keep secret. You <em>can</em> get round this by generating ‘public ids’ or ‘slugs’ for exposed URLs… but then, why not use a built-in tool?</p><p>From a security perspective, using UUIDs prevents the situation where a malicious attacker could attempt to gain access to data by guessing a model id in your URLs. UUIDs are extremely hard to guess.</p><p>This <em>is</em> a case where you are making a choice toward a little more complexity, but for good reasons.</p><h3>Why not?</h3><p>If you’re using PostgreSQL this is a straightforward change and has little performance cost. MySQL is a more complicated proposition and I wouldn’t bother.</p><p>ActiveRecord’s first and last scopes work in an unexpected way with UUID ids. You can no longer assume the ‘highest’ id is the most recent, which could be confusing for new developers to your codebase.</p><p>Using UUIDs is a good idea in brand new projects, but it might be wise to avoid transferring to UUIDs in a running production system unless you have a good reason to do so.</p><p>Translated into Japanese <a href="https://techracho.bpsinc.jp/hachi8833/2018_01_04/50565">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fa59077%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fa59077&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Fa59077%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/08697e2378d3162b241b4b806c1013f9/href">https://medium.com/media/08697e2378d3162b241b4b806c1013f9/href</a></iframe><p><em>Originally published at </em><a href="https://andycroll.com/ruby/choose-uuids-for-model-ids-in-rails/"><em>andycroll.com</em></a><em>.</em></p><p>Sign up to the <a href="https://onerubything.com/">One Ruby Thing</a> email and get my next post in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5afc6007e11d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use a pull request template]]></title>
            <link>https://medium.com/@andycroll/use-a-pull-request-template-d5f4a453c24d?source=rss-72c0199c4d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5f4a453c24d</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[pull-request]]></category>
            <dc:creator><![CDATA[Andy Croll]]></dc:creator>
            <pubDate>Sun, 04 Mar 2018 13:14:51 GMT</pubDate>
            <atom:updated>2018-03-16T22:01:34.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26BT03vaUoep1qCQ9NubvA.jpeg" /></figure><p>If you’re submitting work for review, pull requests are a great way to group related changes and discuss approaches and improvements. The audience for a pull request can be your immediate co-workers, other interested parties or even your future self.</p><p>It should describe the ‘what’, ‘why’ and high-level ‘how’ of the changes in your branch. It is important the description is detailed and sets the context for the changes you have made.</p><p>GitHub offers the ability to define pull request templates. See <a href="https://help.github.com/articles/creating-a-pull-request-template-for-your-repository/">their documentation</a>.</p><h3>Instead of…</h3><p>…writing one line of explanation. Or listing a bunch of commits. Or making it up each time.</p><h3>Use…</h3><p>…a template.</p><h4>.github/PULL_REQUEST_TEMPLATE.md</h4><pre>#### What does this PR do?</pre><pre>[TrelloCard/Issue/Story](LINK_TO_STORY)</pre><pre>##### Why are we doing this? Any context or related work?</pre><pre>#### Where should a reviewer start?</pre><pre>#### Manual testing steps?</pre><pre>#### Screenshots</pre><pre>---</pre><pre>#### Database changes</pre><pre>#### Deployment instructions</pre><pre>#### New ENV variables</pre><p>Each time anyone opens a pull request the description box is pre-filled with the markdown from this file.</p><h3>But why?</h3><p>Anything you do over and over works more efficiently if you have a process you follow every time. Having a template is a solid way to help you write useful pull request descriptions. It helps you pause and answer the questions posed by the default headings in the template.</p><p>It may well be that some pull requests don’t need all of the sections, but you can always just delete the irrelevant parts. Using this template <em>will</em> mean you’ve thought about the information in each section, even it was only to say “nah, don’t need it”.</p><p>Adding a pull request template is often one of my first additions when I join a project.</p><h3>Why not?</h3><p>This feels like a no-brainer to me. Having a template doesn’t stop you deleting the pre-filled headings and customising for specific pull requests. I’ve never regretted including one in a project.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fa59077%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fa59077&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Fa59077%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/08697e2378d3162b241b4b806c1013f9/href">https://medium.com/media/08697e2378d3162b241b4b806c1013f9/href</a></iframe><p><em>Originally published at </em><a href="https://andycroll.com/ruby/use-a-pull-request-template/"><em>andycroll.com</em></a><em>.</em></p><p>Sign up to the <a href="https://onerubything.com/">One Ruby Thing</a> email and get my next post in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5f4a453c24d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extract conditionals into well-named methods]]></title>
            <link>https://medium.com/@andycroll/extract-conditionals-into-well-named-methods-dd9cd896a294?source=rss-72c0199c4d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd9cd896a294</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Andy Croll]]></dc:creator>
            <pubDate>Sun, 21 Jan 2018 21:26:07 GMT</pubDate>
            <atom:updated>2018-01-21T21:26:07.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqWiy0o_m3Vr8Qvbjo9Cmw.jpeg" /></figure><p>One of the simplest (and most effective) ways to refactor is to <a href="https://refactoring.com/catalog/extractMethod.html">extract a method</a>. The naming of an extracted method is a great tool for communicating the thinking behind the code.</p><h3>Instead of…</h3><p>…using slightly complex statements in your conditionals.</p><pre>class BrightonCoffeeShop<br>  def initialize(name)<br>    @name = name<br>  end</pre><pre>  def good?<br>    if @name == &#39;Starbucks&#39; ||<br>       @name == &#39;Costa&#39; ||<br>       @name == &#39;Barry’s Caff&#39;<br>      false<br>    elsif @name == &#39;Coffee@33&#39; || @name == &#39;Small Batch&#39;<br>      true<br>    else<br>      false<br>    end<br>  end<br>end</pre><p>This implementation explicitly returns false if the name is unknown. The only way to guarantee a decent coffee shop experience is to rule out places you’ve never heard of. Right? :-)</p><h3>Use…</h3><p>…the Extract Method refactoring to move the logic into a private method, giving that method a name that clearly explains the concept of the code.</p><pre>class BrightonCoffeeShop<br>  def initialize(name)<br>    @name = name<br>  end<br><br>  def good?<br>    clean? &amp;&amp; local? &amp;&amp; excellent_coffee?<br>  end<br><br>  private<br><br>  def clean?<br>    !filthy?<br>  end<br><br>  def excellent_coffee?<br>    [&#39;Coffee@33&#39;, &#39;Small Batch&#39;].include?(@name)<br>  end<br><br>  def filthy?<br>    @name == &#39;Barry’s Caff&#39;<br>  end<br><br>  def local?<br>    !national_chain?<br>  end<br><br>  def national_chain?<br>    [&#39;Starbucks&#39;, &#39;Costa&#39;].include?(@name)<br>  end<br>end</pre><h3>But why?</h3><p>By extracting a method you, by definition, name it. Our #good? method states the specific criteria for a good coffee shop. The new private methods act as documentation for the class.</p><p>Before, all we really had was a list of ‘good’ and ‘bad’ coffee shops. We had no knowledge of how those lists were developed.</p><p>A naive refactoring of this class might have just stuffed all the good and bad names in arrays named GOOD and BAD and checked the coffee shop name against them. We would have lost the reasoning behind <em>why</em> the places were good or bad. And the <em>why</em> is the most important part.</p><p>In this case I’ve extracted the negative concepts of #filthy? and #national_chain? as well as the positive concepts like #clean? and #local?. This avoids using the negative versions of the private methods in the #good? method, making that method more readable. You could consider this overkill in some cases, but here it adds useful context as this class is heavily geared towards the positive qualities of a decent coffee shop.</p><p>Before any refactoring it is important to ensure good test coverage of the initial implementation to prevent accidental changes in functionality.</p><h3>Why not?</h3><p>In a simpler example, I might not even bother with this kind of refactoring, but here it serves as a nice documentation technique and clarifies the logic in the conditional.</p><p>In a more complex case, where a coffee shop has much more functionality (more than just being good or not) you might further refactor each of the different coffee shops into subclasses.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fa59077%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fa59077&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Fa59077%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href">https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href</a></iframe><p><em>Originally published at </em><a href="https://andycroll.com/ruby/extract-conditionals-into-well-named-methods/"><em>andycroll.com</em></a><em>.</em></p><p>Sign up to the <a href="https://onerubything.com/">One Ruby Thing</a> email and get my next post in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd9cd896a294" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use simplecov in your Rails test suite]]></title>
            <link>https://medium.com/@andycroll/use-simplecov-in-your-rails-test-suite-55448fb0059b?source=rss-72c0199c4d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/55448fb0059b</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[code-coverage]]></category>
            <dc:creator><![CDATA[Andy Croll]]></dc:creator>
            <pubDate>Mon, 15 Jan 2018 13:13:50 GMT</pubDate>
            <atom:updated>2018-01-15T13:14:38.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-lcBm9STpyHMSUGJsYB0A.jpeg" /></figure><p>A useful way of assessing the effectiveness of your testing is to use the <a href="https://github.com/colszowka/simplecov">simplecov gem</a> with your Rails application. It counts the number of times each line of application code is run during your test suite.</p><h3>Use…</h3><p>…simplecov in your tests.</p><h4>Add to Gemfile</h4><pre>group :test do<br>  gem &#39;simplecov&#39;, require: false<br>end</pre><p>And run bundle in the root directory of your project.</p><h4>Add to .gitignore</h4><p>Do not commit generated files in the coverage directory.</p><h4>Add to top of spec/spec_helper.rb or test/test_helper.rb</h4><pre>require &#39;simplecov&#39;<br>SimpleCov.start &#39;rails&#39; do<br>  add_filter &#39;/bin/&#39;<br>  add_filter &#39;/db/&#39;<br>  add_filter &#39;/spec/&#39; # for rspec<br>  add_filter &#39;/test/&#39; # for minitest<br>end</pre><p>Add this right at the top of the file. The add_filter lines means files matching the passed string are excluded from the results.</p><p>Then run your tests as normal, you’ll see a message that looks like:</p><pre>Coverage report generated for RSpec to /PATH_TO_YOUR_APP. 584 / 1068 LOC (54.68%) covered.</pre><h3>But why?</h3><p>Having an awareness of your level of coverage is useful as an input to understanding the stability of your application and protection against regressions.</p><p>Exploring the generated HTML reports (available in coverage/index.html) is a good way to see if there are areas of your code that are poorly tested.</p><p>It’s important to note that measuring your test coverage of your application’s code is a blunt instrument. In fact, aiming for 100% coverage is not a noble aim, or even useful.</p><blockquote><em>Some codebases with 100% test coverage will still have bugs, and some codebases with much lower coverage will not.<br>— Sarah Mei, </em><a href="https://twitter.com/sarahmei/status/819270166576058369"><em>11 Jan 2017</em></a></blockquote><h3>Why not?</h3><p>It could slow your test suite a little. But it’s only, at most, additional seconds in a multiple-minute test suite.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fa59077%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fa59077&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Fa59077%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href">https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href</a></iframe><p><em>Originally published at </em><a href="https://andycroll.com/ruby/use-simplecov/"><em>andycroll.com</em></a><em>.</em></p><p>Sign up to the <a href="https://onerubything.com/">One Ruby Thing</a> email and get my next post in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55448fb0059b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rescue specific errors. Avoid rescuing StandardError. Don’t rescue Exception.]]></title>
            <link>https://medium.com/@andycroll/rescue-specific-errors-avoid-rescuing-standarderror-dont-rescue-exception-521a88b58e1f?source=rss-72c0199c4d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/521a88b58e1f</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Andy Croll]]></dc:creator>
            <pubDate>Tue, 02 Jan 2018 21:43:04 GMT</pubDate>
            <atom:updated>2018-01-05T11:13:11.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnTqBxq6Nom04wdfpm96pw.jpeg" /></figure><p>There are many built-in error classes in Ruby and Rails. Most of these errors are subclasses of Ruby’s StandardError. You can find more information in the relevant <a href="http://ruby-doc.org/core-2.4.2/StandardError.html">Ruby docs</a>.</p><h3>Instead of…</h3><p>…rescuing Exception.</p><pre>def your_method<br>  # do something<br>rescue Exception =&gt; e<br>  # saved ALL THE THINGS<br>end</pre><h3>Or…</h3><p>…a non-specific rescue that implicitly rescues StandardError.</p><pre>def your_method<br>  # do something<br>rescue =&gt; e<br>  # saved StandardError and all subclasses<br>end</pre><h3>Use…</h3><p>…rescue on a specific named error.</p><pre>def your_method<br>  # do something<br>rescue SpecificProblemError =&gt; e<br>  # saved only what you meant to<br>rescue AnotherProblemError =&gt; e<br>  # saved a different kind of error<br>end</pre><h3>But why?</h3><p>Ruby’s Exception is the parent class to <em>all</em> errors. “Great” you might say, “I want to catch all errors”. But you don’t.</p><p>Exception includes the class of errors that can occur outside your application. Things like memory errors, or SignalException::Interrupt (sent when you manually quit your application by hitting Control-C). These are errors you <em>don’t</em> want to catch in your application as they are generally serious and related to external factors. Rescuing Exception can cause very unexpected behaviour.</p><p>StandardError is the parent of most Ruby and Rails errors. If you catch StandardError you’re not introducing the problems of rescuing Exception, but it is not a great idea. Rescuing <em>all</em> application-level errors might cover up unrelated bugs you don’t know about.</p><p>The safest approach is to rescue the error (or errors) you are expecting and deal with the consequences of that error inside the rescue block.</p><p>In the event of an unexpected error in your application you want to know that a new error has occurred and deal with the consequences of <em>that</em> new error inside its own rescue block.</p><p>Being specific with rescue means your code doesn’t accidentally swallow new errors. You avoid subtle hidden errors that lead to unexpected behaviour for your users and bug hunting for you.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fa59077%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fa59077&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Fa59077%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href">https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href</a></iframe><p><em>Originally published at </em><a href="https://andycroll.com/ruby/rescue-specific-errors-avoid-standarderror-do-not-rescue-exception/"><em>andycroll.com</em></a><em>.</em></p><p>Sign up to the <a href="https://onerubything.com/">One Ruby Thing</a> email and get my next post in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521a88b58e1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t use default_scope. Ever.]]></title>
            <link>https://medium.com/@andycroll/dont-use-default-scope-ever-441a934962cc?source=rss-72c0199c4d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/441a934962cc</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Andy Croll]]></dc:creator>
            <pubDate>Tue, 02 Jan 2018 21:30:19 GMT</pubDate>
            <atom:updated>2018-01-05T11:16:31.521Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Bg4Nm7NXAbWIqJ_dGQysQ.jpeg" /></figure><p>When you would like a scope to be applied across all queries on a model, you can use default_scope. See more in the <a href="http://guides.rubyonrails.org/active_record_querying.html#applying-a-default-scope">ActiveRecord Query Guide</a> and <a href="http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Default/ClassMethods.html#method-i-default_scope">Rails docs</a>.</p><p>Where you have a blog system with posts that can be set to be hidden, for when you are writing a draft.</p><h3>Instead of…</h3><p>…default_scope.</p><pre># app/models/post.rb<br>class Post &lt; ActiveRecord::Base<br>  default_scope { where(hidden: false) }<br>end</pre><h3>Use…</h3><p>…explicit scopes.</p><pre># app/models/post.rb<br>class Post &lt; ActiveRecord::Base<br>  scope, :published -&gt; { where(hidden: false) }<br>end</pre><p>…then you can do…</p><pre>Post.published</pre><h3>But why?</h3><p>Two reasons. Both to do with avoiding later confusion and bug hunting.</p><p>Adding a default scope affects your model initialization. In the example, Post.new is defaulted to hidden = false whether you are expecting it or not.</p><p>Trying <em>not</em> to use your defined default scope is a pain. To remove the default_scope when you don’t need it you have to use the unscoped scope (!) which removes <em>all</em> applied conditions including associations.</p><p>i.e. Post.first.comments.unscoped would return every comment in your database, not just those for the first Post.</p><p>The explicit use of named scopes is a clearer solution. Using default_scope will lead to many hours of bug hunting. Don’t do it to yourself.</p><h3>Where might I use it?</h3><p>Seriously. Trust me on this one. It will bite you.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fa59077%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fa59077&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Fa59077%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href">https://medium.com/media/b64a83cf1abac48bccd6cdb5b587f5a4/href</a></iframe><p><em>Originally published at </em><a href="https://andycroll.com/ruby/dont-use-default-scope/"><em>andycroll.com</em></a><em>.</em></p><p>Sign up to the <a href="https://onerubything.com/">One Ruby Thing</a> email and get my next post in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=441a934962cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>