optional local variables in rails partial templates: how do I get out of the (defined? foo) mess?
I do this:
<% some_local = default_value if local_assigns[:some_local].nil? %>
Since local_assigns
is a hash, you could also use fetch with the optional default_value
.
local_assigns.fetch :foo, default_value
This will return default_value
if foo
wasn't set.
WARNING:
Be careful with local_assigns.fetch :foo, default_value
when default_value
is a method, as it will be called anyway in order to pass its result to fetch
.
If your default_value
is a method, you can wrap it in a block: local_assigns.fetch(:foo) { default_value }
to prevent its call when it's not needed.