我的Rails控制器中有以下模式:
def get_details
# check params for valid input
...
if !valid
render :json, error_info, :status => 400 and return
end
begin
...
...
...
render :json => result, :status => 200 and return
rescue Exception => e
if e.is_a? ActiveRecord::RecordNotFound
render :json => error_info, :status => 404 and return
end
end
end
由于渲染没有返回,我必须在每个渲染调用中添加and return
,这对我来说似乎不太干。有这种模式的替代方案吗?
答案 0 :(得分:0)
您可以按照以下方式编写
def get_details
# check params for valid input
...
if !valid
return render_with(error_info, 400)
else
begin
...
...
...
return render_with(result, 200)
rescue Exception => e
if e.is_a? ActiveRecord::RecordNotFound
return render_with(error_info, 404)
end
end
end
end
private
def render_with(result_info, status_code)
render :json => result_info, :status => status_code
end