Search code examples
rubyoopreadabilityrefactoringcode-readability

How can this 6 line method be refactored to be more readable?


I'm trying to clean up this ridonkulously ugly method here, that's crying out for refactoring, but I'm not sure what kind of structure would do this best (i.e. a case statement, or simply a carefully formatted if then statements)

At first glance, it looks like it would be an ideal place for a case statement with a few well placed when's, but my understanding was that case statements can only be used to for a single variable, not two, and various fiddlings with irb to try these statements using hashes or arrays haven't shed much light here either.

How would you do this? Are there any common tricks in Ruby to avoid code like this when checking multiple booleans like this?

  def has_just_one_kind_of_thing?(item, controller)
    if (controller == 'foos' && item.widgets.blank?) || (controller == 'foos' && item.doohickeys.blank?) || (controller == 'bars' && item.widgets.blank?) || (controller == 'bars' && item.doohickeys.blank?) || (controller == 'bazes' && item.widgets.blank?) || (controller == 'bazes' && item.contraptions.blank?)
      return true
    else 
      return false
    end
  end

Solution

  • Something such as this, perhaps?

    def has_just_one_kind_of_thing?(item, controller)
        return case controller
          when 'foos', 'bars'
            item.widgets.blank? || item.doohickeys.blank?
          when 'bazes'
            item.widgets.blank? || item.contraptions.blank?
          else 
            false
        end
      end
    

    The outer return may not be necessary (not entirely sure what Ruby requires, I'm still fairly new to it myself), but I prefer leaving it in so the intent is obvious.