0

我的 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到每个渲染调用,这对我来说似乎不太干燥。这种模式有替代品吗?

4

1 回答 1

0

You can write it as follows

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
于 2013-03-26T09:18:00.580 回答