How to have an optional local variable in a partial template in rails?
ruby, ruby-on-rails
Solution
Read the Passing local variables to sub templates section in the ActionView::Base docs
Basically it says you should use this pattern:
<% if local_assigns.has_key? :headline %>
Headline: <%= headline %>
<% end %>
For you, this might translate to something like:
<div style="width: <%= local_assigns.has_key?(:optional_width) ? optional_width : 500 %>px;">
<!-- filler -->
</div>
important!
According to the docs
Testing using `defined? headline` will not work. This is an implementation restriction.
Problem
I was thinking that at the top of my partial I would have something like this ``` <% optional_width = default_value unless (defined? optional_width) ``` But I've had inconsistent results with this, I'm thinking this is not a good way to do this. What is the "correct" way to do this in rails?