Optional Parameters in View Partials
It's generally good practise to pass variables to view partials using locals rather than littering your code with @variables
.
This allows better reuse of the partial.
To make the locals optional, provide default values if they are nil
or undefined. I have seen many recommendations to do this with a test for defined?
According to the rails api this will not work and local_assigns.has_key?
should be used.
My preference is to use ||=
With 2 caveats:
- If the default value is
nil
orfalse
the right hand side of the expression will always be evaluated. I can live with this as I think the any effect on performance will be insignificant. - The second caveat is when the default is
true
. The above statement would convert a local passed in asfalse
totrue
which is obviously not the intent. Instead, for default values oftrue
, this should be used.