Why does this rescue syntax work?

半世苍凉 提交于 2019-12-12 11:06:51

问题


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

回答1:


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.




回答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"  



回答3:


rescue word is part of method definition

But in controllers better to rescue errors with rescue_from




回答4:


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


来源:https://stackoverflow.com/questions/10089204/why-does-this-rescue-syntax-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!