在顶部调用render方法可以吗?
Is it OK to call render method at the top?
我的网络应用程序处理来自第三方的 webhooks API,我需要在收到它们时使用 200 OK 代码进行响应。在 some_api_webhook
方法中进行实际处理之前,我需要检查一些条件,如果其中任何一个失败 - 我不能进一步处理。在 some_api_webhook
方法的顶部调用 render
方法可以吗?有人告诉我 render
应该只放在方法的底部...
我原来的方法:
def some_api_webhook
unless condition_a
render nothing: true, status: :ok, content_type: "text/html"
return
end
unless condition_b
render nothing: true, status: :ok, content_type: "text/html"
return
end
unless condition_c
render nothing: true, status: :ok, content_type: "text/html"
return
end
# main logic is below
# ...
# ...
end
我更喜欢重写的版本,因为它没有对 render
:
的重复调用
def some_api_webhook
render nothing: true, status: :ok, content_type: "text/html"
return unless condition_a
return unless condition_b
return unless condition_c
# main logic is below
# ...
# ...
end
有趣的是,我一直认为渲染会 return 来自动作,并且不会处理低于它的任何内容。刚刚做了一个快速测试,结果证明这是错误的。在下面的代码中,put 语句仍然被执行。
def index
render 'index'
puts "Got here!"
end
因此在这方面,除非渲染是有条件的,否则在这方面放置渲染并不重要,而在您的情况下它似乎不是。
我的网络应用程序处理来自第三方的 webhooks API,我需要在收到它们时使用 200 OK 代码进行响应。在 some_api_webhook
方法中进行实际处理之前,我需要检查一些条件,如果其中任何一个失败 - 我不能进一步处理。在 some_api_webhook
方法的顶部调用 render
方法可以吗?有人告诉我 render
应该只放在方法的底部...
我原来的方法:
def some_api_webhook
unless condition_a
render nothing: true, status: :ok, content_type: "text/html"
return
end
unless condition_b
render nothing: true, status: :ok, content_type: "text/html"
return
end
unless condition_c
render nothing: true, status: :ok, content_type: "text/html"
return
end
# main logic is below
# ...
# ...
end
我更喜欢重写的版本,因为它没有对 render
:
def some_api_webhook
render nothing: true, status: :ok, content_type: "text/html"
return unless condition_a
return unless condition_b
return unless condition_c
# main logic is below
# ...
# ...
end
有趣的是,我一直认为渲染会 return 来自动作,并且不会处理低于它的任何内容。刚刚做了一个快速测试,结果证明这是错误的。在下面的代码中,put 语句仍然被执行。
def index
render 'index'
puts "Got here!"
end
因此在这方面,除非渲染是有条件的,否则在这方面放置渲染并不重要,而在您的情况下它似乎不是。