Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to to rescue from errors in a Rails template (ERB file)

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)?

like image 976
absessive Avatar asked Nov 19 '22 22:11

absessive


1 Answers

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.

like image 159
Greg Answer Avatar answered Mar 05 '23 19:03

Greg Answer