5

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
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321

4 Answers4

13

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.

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
2

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"  
Vik
  • 5,931
  • 3
  • 31
  • 38
  • This uses it as a statement modifier, though, which isn't the OP's question. You're correct, of course, but it doesn't directly answer the question. – Dave Newton Apr 10 '12 at 13:13
0

rescue word is part of method definition

But in controllers better to rescue errors with rescue_from

mikdiet
  • 9,859
  • 8
  • 59
  • 68
-3

try this

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
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
  • It's perfectly legal to use a `rescue` inside a method definition (and implicit `begin`) without an explicit `begin`. – Dave Newton Apr 10 '12 at 13:11