Passing optional locals to Rails partials
When passing locals to Rails partials, you might run into cases where you need to pass optional locals in some places, but don’t want to pass it in every other place where you use the partial.
As an example, you have a
which you render like this:
And now you want to render the same partial from another view, but this time you want to pass a boolean flag to tell the partial to render the author bio as well.
If we now used the
show_author_bio local in the partial,
it would break the other view
which does not know about this local.
To use it safely, we can make use of
Even though we’re using it for passing a boolean value here, we could pass in any other object as well. For instance, we could pass in an optional author object:
Sadly, Rails documentation seems to be
missing details about this useful feature.
I'm not sure if this is because
it has been deprecated since Rails 4.
Do leave a comment below if you know why.
In earlier versions of Rails,
defined? did no work reliably in the views.
This is not the case in 4.2,
so the part of the ActionView::Base docs
local_assigns was removed.
You can use
defined? like this:
local_assigns is still available though,
and is still useful in cases
where you need to access the locals as a hash.
I went ahead and submitted a
adding documentation for
There’s also another open issue for the same
that also added documentation.
Hopefully we will soon have documentation for
DHH also opened an issue (#18962) about this yesterday, and had an interesting comment to make about this feature. ;-)
These f***ing Rails people have thought of everything!
local_assignsis exactly this and already available.