Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this rescue syntax work?

Tags:

ruby

rescue

Ok so I have this method of an application I am working with and it works in production. My question 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
like image 567
Matt Elhotiby Avatar asked Apr 10 '12 12:04

Matt Elhotiby


2 Answers

rescues do not need to be tied to an explicit begin when they're in a method, that's just the way the syntax is defined. For examples, see #19 here and this SO question, as well as the dupe above.

like image 156
Dave Newton Avatar answered Oct 06 '22 00:10

Dave Newton


rescue can work alone . no need of begin and end always .

You can use rescue in its single line form to return a value when other things on the line go awry:

h = { :age => 10 }
h[:name].downcase                         # ERROR
h[:name].downcase rescue "No name"  
like image 35
Vik Avatar answered Oct 06 '22 01:10

Vik