Use Optional Local Variables In A Partial In Rails

Posted By Weston Ganger

Here are a few methods to work with optional local variables in a partial.

These examples show unless foo is defined then make foo = 'bar'.

# Method 1, Simple & Concise but won't work well for booleans or nil
<% foo ||= 'bar' %>

# Method 2
# If the second/default value here is a method, use this syntax to prevent premature call of the method
<% foo = local_assigns.fetch(:foo){ Post.all } %>
# Else, use this syntax
<% foo = local_assigns.fetch(:foo, 'bar') %>

This example intends these to be added at the top of your partial. You can easily adapt them to be used in place if its only a one time use.

Related External Links:

Article Topic:Software Development - Ruby / Rails

Date:September 06, 2016