Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, Ruby always returns the value of the last statement by default, so we can get rid of the if/else:</p> <pre><code>def has_just_one_kind_of_thing?(item, controller) (controller == 'foos' &amp;&amp; item.widgets.blank?) || (controller == 'foos' &amp;&amp; item.doohickeys.blank?) || (controller == 'bars' &amp;&amp; item.widgets.blank?) || (controller == 'bars' &amp;&amp; item.doohickeys.blank?) || (controller == 'bazes' &amp;&amp; item.widgets.blank?) || (controller == 'bazes' &amp;&amp; item.contraptions.blank?) end </code></pre> <p>Now let's reformat for readability.</p> <pre><code>def has_just_one_kind_of_thing?(item, controller) (controller == 'foos' &amp;&amp; item.widgets.blank?) || (controller == 'foos' &amp;&amp; item.doohickeys.blank?) || (controller == 'bars' &amp;&amp; item.widgets.blank?) || (controller == 'bars' &amp;&amp; item.doohickeys.blank?) || (controller == 'bazes' &amp;&amp; item.widgets.blank?) || (controller == 'bazes' &amp;&amp; item.contraptions.blank?) end </code></pre> <p>There, now it's a lot easier to see patterns in the algorithm. It looks like there are two questions being asked here: is the controller one of [foos|bars|bazes] and are either widgets or doohickeys blank. Let's factor out the first question:</p> <pre><code>def has_just_one_kind_of_thing?(item, controller) %w[foos bars bazes].include?(controller) &amp;&amp; (item.widgets.blank? || item.doohickeys.blank?) end </code></pre> <p>This gets the method down to a managable size. But I infer from the method name that you are looking for the case where either widgets or doohickeys has items, but not both and not neither. If that is so, an XOR might be more appropriate:</p> <pre><code>def has_just_one_kind_of_thing?(item, controller) %w[foos bars bazes].include?(controller) &amp;&amp; (item.widgets.blank? ^ item.doohickeys.blank?) end </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload