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.


How about

<% foo ||= default_value %>

This says "use foo if it is not nil or true. Otherwise assign default_value to foo"