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 or false 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 as false to true which is obviously not the intent. Instead, for default values of true, this should be used.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.