Does Rails offer any way to exit early or "return" from a view that is being rendered?
For example, I have a view structured as follows:
<h1>Your records summary</h1>
<% if @current_user.has_records? %>
<p>You don't have any records.</p>
<% else %>
... long block of view emission code here ...
<% end %>
In non-erb code, I'd just return
from that if
condition, and wouldn't need to put that long block inside an else
. It would look like:
<h1>Your records summary</h1>
<% if @current_user.has_records? %>
<p>You don't have any records.</p>
<% return (or something) %>
<% end %>
... long block of view emission code here ...
Is there a way to do something like that in the erb?
EDIT: To be clear, I'm not asking for alternate approaches, such as have been suggested. I'm not a Rails noob. I really just want to know whether Ruby provides a mechanism for what I suggested or not.
redirect_to and render do not return Keep in mind that redirect_to and render do not cause the action to stop executing. It is not like calling return in a Ruby method.
Ruby Break Keyword (Exit Loop Early) The break keyword is like next , but it ends the loop & returns a value, instead of skipping just one iteration.
In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement.
To break out from a ruby block simply use return keyword return if value.
This is an old question, but I figured I'd take the time to spare future people the hour or so of their lives trying to figure out if this is doable.
I've discovered that, as far back as Rails 3.2, this is actually possible.
It requires some knowledge of ActionView internals and I do not advocate anyone do this in production code. Further, this particular implementation only works with the built-in ERB engine used by Rails which, itself, uses Erubi.
Alright, now that we're done with the warnings, on to the action!
The surprisingly simple answer is to return @output_buffer.to_s
.
As long as you've closed all your HTML tags before returning, it seems to work and everything is correctly rendered.
For the curious, this output buffer is currently configured in the initializer for the Erubi ERB handler. With the rest of the work done by the underlying Erubi::Engine implementation.
I've poked around at something that provides a less brittle way to go about returning early, but I've unsuccessful so far.
In Rails 3.2.2, return inside a template works just fine for me.
<% return unless allowed_tags %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With