我正在努力争取一些希望你可能有专业知识帮助的事情。
我在Ruby 2.0.0p247(Rails 3.2.13)中编写了一个API,它带有一组控制器,可以调用一个名为send_response的辅助函数,它接受状态和可选参数,并将其格式化为正确的HTTP响应然后通过JSON将其返回给最终用户,然后所有执行都应该停止。 API调用受数据库支持的令牌保护。
我正在使用render json: response, :status => response['status'] and return false'
,但无论如何,执行似乎仍在继续。示例:在我使用错误参数的情况下添加日志条目的API调用会得到一个JSON响应,说明错误的参数,但日志条目仍然会被添加。
'send_response()'调用的来源:
def send_response( status, options = {})
source = options[:source] || nil
count = options[:count] || -1
data = options[:data] || nil
id = options[:id] || -1
trigger_id = options[:trigger_id] || -1
response = {}
case status
when 'ok', 200
response['status'] = 200
response['message'] = 'success'
response['count'] = count unless count == -1
response['data'] = data unless data == nil
response['id'] = id unless id == -1
response['trigger_id'] = trigger_id unless trigger_id == -1
when 'bad_request', 400
response['status'] = 400
response['message'] = 'error'
response['data'] = data unless data == nil
when 'unauthorized', 401
response['status'] = 401
response['message'] = 'unauthorized'
response['data'] = data unless data == nil
when 'internal_error', 500
response['status'] = 500
response['message'] = 'error'
response['data'] = data unless data == nil
else
response['status'] = 500
response['message'] = 'error'
response['data'] = 'Invalid send_response() sent.'
end
response['source'] = caller[0][/`.*'/][1..-2] if Rails.env.development?
render json: response, :status => response['status'] and return false
end
我的控制器调用此函数的一个示例:
# Make sure the user is using the correct parameters, otherwise kick 'em out
params.each do |key,value|
if params_list.include?(key) == false
send_response 500, data: 'Invalid parameters used!'
end
end
我完全不知道为什么执行没有结束,任何帮助都会非常感谢我指出正确的方向。
提前致谢!
- 杰森
答案 0 :(得分:0)
return
完成当前方法的执行 - 在您的情况下,如果终止send_response
方法并使其返回false。您想要返回“父”方法:
params.each do |key,value|
if params_list.include?(key) == false
send_response 500, data: 'Invalid parameters used!' and return false
end
end