Boolean or true is always true

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-12-03

I wanted to control whether a form element in a web framework used AJAX (remote) or not -- and to default to true if no preference was specified (i.e. if the locals dictionary did not have the remote key. I came up with the following:

form_for(@user, remote: locals[:remote] || true)

Later I discovered a bug: when I called it with locals equal to {remote: false}, remote ended up being true!

The problem was that the logic works out as false || true which is always true

Instead I should have explicitly checked for nil

locals[:remote].nil? true : locals[:remote]

Lesson

  1. bool OR true is always true.
  2. When you wish for a default behavior based on nil, it's better to be explicit.