如何突破开始区块并跳转到救援区?
def function
begin
@document = Document.find_by(:token => params[:id])
next if @document.sent_at < 3.days.ago # how can I skip to the rescue block here?
@document.mark_as_viewed
rescue
flash[:error] = "Document has expired."
redirect_to root_path
end
end
Run Code Online (Sandbox Code Playgroud)
我尝试使用next不起作用.
好吧,你可能会提出错误.这就是开始/救援块的工作方式.但这并不是一个好主意 - 使用业务逻辑的错误处理通常是不受欢迎的.
似乎将重构作为一个简单的条件更有意义.就像是:
def function
@document = Invoice.find_by(:token => params[:id])
if @document.sent_at < 3.days.ago
flash[:error] = "Document has expired."
redirect_to root_path
else
@document.mark_as_viewed
end
end
Run Code Online (Sandbox Code Playgroud)
看起来好像你在这里混淆了几种不同类型的块相关关键字:
错误处理(begin/ rescue/ end)适用于您认为您尝试的某些内容可能引发错误并以特定方式响应的情况.
next 用于迭代 - 当您循环遍历集合并希望跳到下一个元素时.
条件表达式(if,unless,else等)是用于检查的东西的状态,并根据其执行的代码不同的比特以常规方式.