Do not use empty arrays to mean falsey in logic

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dumb-mistakes-and-gotchas category.

Last Updated: 2024-11-21

The following code incorrectly displayed a widget about upgrades to customers

# view
<%= render :partial => 'orders/buy_updates_widget', :locals => {:order => @order } if @possible_upgrades %>

# controller
@possible_upgrades = @order.possible_upgrades

The issue was @order.possible_upgrades returned an array no matter what. It just happened to be empty when there were no possible upgrades. But an empty array is still truthy in Ruby.

The fix was to explicitly check for there being elements in that array.

<%= render :partial => 'orders/buy_updates_widget', :locals => {:order => @order } if @possible_upgrades.present? %>