In Ruby, it's common to use the double pipe operator to test if a variable is falsy and to apply some kind of default setting when variables are undefined. Here's a line of config I just came across in a codebase I'm doing some work on:
config.uh_product_name = ENV['UH_PRODUCT_NAME'] || 'Unicorn Hunt'
This is all well and good if ENV["UH_PRODUCT_NAME"]
is nil
. But in this case, because of the way the .env file is set by default, ENV["UH_PRODUCT_NAME"]
is an empty string ""
, which is truthy. So the default is not applied.
I could do this to handle this case:
config.uh_product_name = ENV['UH_PRODUCT_NAME'].present? ? 'Unicorn Hunt' : ENV['UH_PRODUCT_NAME']
But that's much less readable and ends up with a line of code that potentially stretches off screen.
So, does anyone know of a shorthand operator along the lines of ||
that applies Rails's .blank?
or treats empty strings as falsy? Something like this perhaps:
config.uh_product_name = ENV['UH_PRODUCT_NAME'] ?|| 'Unicorn Hunt'
Aucun commentaire:
Enregistrer un commentaire