2012-04-10 25 views
5

好的,我有這種方法我正在使用的應用程序,它在生產中工作。我的問題爲什麼這個工作?這是新的Ruby語法嗎?這個救援語法爲什麼起作用?

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 
+1

參見http://stackoverflow.com/questions/1542672/how-does-一次性使用救援在軌道上沒有開始和結束塊 – 2012-04-10 13:06:58

回答

13

rescue■不要需要被綁定到當它們處於方法中時,顯式爲begin,這就是語法定義的方式。例如,請參閱#19 herethis SO question以及the dupe above

+0

謝謝...尼斯鏈接。 – Vik 2012-04-10 13:15:51

0

rescue字是方法定義的一部分

但在控制器更好地與rescue_from

-2

搶救錯誤試試這個

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 
+0

我知道這將工作....我的問題是爲什麼我的語法工作 – Trace 2012-04-10 13:03:03

+0

在內部使用「救援」是完全合法的一個方法定義(和隱式'begin'),沒有明確的'begin'。 – 2012-04-10 13:11:58

2

營救可以單獨工作。永遠不需要開始和結束。

您可以使用救援在單行形式返回一個值時,就行了其他事情出差錯:

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

儘管這不是OP的問題,但它將它用作語句修飾符。當然,你是對的,但它並不直接回答這個問題。 – 2012-04-10 13:13:24