Why does this rescue syntax work?

Ok, so I have this application method that I work with, and it works in production. My question is, why does this work? Is this new Ruby syntax?

def edit
  load_elements(current_user) unless current_user.role?(:admin)

  respond_to do |format|
    format.json { render :json => @user }   
    format.xml  { render :xml => @user }
    format.html
  end

rescue ActiveRecord::RecordNotFound
  respond_to_not_found(:json, :xml, :html)
end
+5
source share
4 answers

rescueno need to bind to the explicit beginwhen they are in the method, just as the syntax is defined. For example, see # 19 here and this SO question , as well as the workaround above .

+13
source

salvation can work alone. no need to start and end always.

You can use salvation in your one-line form to return the value when other things on the line go wrong:

h = { :age => 10 }
h[:name].downcase                         # ERROR
h[:name].downcase rescue "No name"  
+2

rescue the word is part of the definition of a method

But in controllers it’s better to save errors with rescue_from

0
source

try it

def edit
  begin
    load_elements(current_user) unless current_user.role?(:admin)

    respond_to do |format|
      format.json { render :json => @user }   
      format.xml  { render :xml => @user }
      format.html
    end

  rescue ActiveRecord::RecordNotFound
    respond_to_not_found(:json, :xml, :html)
  end
end
-2
source

All Articles