I have an ERB template which has a few helper methods from other gems
sample.html.erb
<h1>All The Stuff</h1>
<% all_the_stuff.each do |stuff| %>
<div><%= stuff %></div>
<% end %>
lib/random_file.rb
def all_the_stuff
if ALL_THE_STUFF.exists?
ALL_THE_STUFF
else
fail AllTheStuffException
end
end
Now, if ALL_THE_STUFF
were not not exist, I'll get an ActionView::Template::Error
. However, that will not be caught be an exception handling at the controller level.
In case of the controllers, I rescue exceptions in the ApplicationController
using rescue_from
. Is there a single place to put this for all my ERB templates?
How do I handle exceptions caught within a template (not due to controller code)?
I believe a better solution would be the following:
class ThingsController < ApplicationController
def sample
@things = Thing.all
end
end
# views/things/sample.html.erb
<h1>All The Things</h1>
<% if @things.present? %>
<% @things.each do |thing| %>
<div><%= thing %></div>
<% end %>
<% else %>
There are no things at the moment.
<% end %>
This is the rails way and avoids using any Exception
class as a control flow, which is usually a bad idea.
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