Suppose that I want to have a block of default content within a
template that is replaced with the content of a specific partial only
if that partial exists. Obviously there is the brute force approach
of simply rendering the default content unless the relevant partial
file exists in which case the relevant partial is rendered instead. I
suspect that there may be a more elegant way to skin this cat. Any
suggestions?
In terms of elegance, I think that it’s about a toss up. However, I
think that your suggestion has a slight distinct advantage. If I use
my approach, I have to deal with the actual partial twice, once to
test whether it exists and once to render it if it does. Using your
approach, I only have to deal with the actual partial once, i.e., to
render it. I’m adopting your approach whch, btw, works great. Thanks
for the suggestion.
Exceptions handling in Ruby is done the following way.
begin
rescue
end
When a partial template is missing Rails will throw an exception. As a
result, to catch a missing partial template exception
(ActionView::MissingTemplate) you need to rescue that exception by name.
In
ERB the syntax for this is <% rescue ActionView::MissingTemplate %>.