我在我的 hotel_controller 中有几个操作,我在其中调用 API 来取回数据。我创建了不同的服务来将我的 API 调用保持在我的 Controller 逻辑之外。对于每个 API 调用,我都会遇到一些“一般响应错误”,例如 unauthorized
或 not found
例如。由于这些错误对所有 API 调用都很常见,因此我想在我的酒店 Controller 中创建一个私有(private)方法来处理它们:
private
def global_error_checking(response)
if response.message == "Unauthorized"
redirect_to unauthorized_path and return
elsif response.message == "Not Found"
redirect_to not_found_path and return
else
end
end
然后在需要它的 Controller 的每个方法中,我会在检查特定错误之前调用 global_error_checking 方法。例如 :
def index
service = Hotels::GetHotelListService.new( account_id: params[:account_id],
user_email: session[:user_email],
user_token: session[:user_token]
)
@response = service.call
global_error_checking(@response)
if @response["hotels"].blank?
flash[:notice] = "You have not created any hotels yet !"
redirect_to account_path(params[:account_id])
else
@hotels = @response["hotels"]
@account = @response["account"]
end
end
问题是执行后
global_error_checking
, Controller 的 Action 继续进行并且不会停止,即使条件为 global_error_checking
很满意。1) 如果
global_error_checking
中出现条件,如何停止整个 Controller 方法的执行?满意吗?2)是否有更好的方法来实现这一目标?
最佳答案
我不会将参数命名为“响应”,因为 Controller 已经在使用它。
我注意到的另一件事是您正在以不同的方式访问此“@response”,这可能没问题,但看起来不对。在您的 global_error_checking 方法中,您正在使用点语法 (response.message) 访问它的属性,但是在您的 Controller 操作中,您正在访问它,就好像它是一个哈希一样。同样,这可能没问题,具体取决于其数据类型。
如果我是你,我会将其重构为:
class SomeController < ApplicationController
def index
@hotels = some_resource['hotels']
@account = some_resource['account']
end
private
def some_resource
@_some_resource ||= begin
service = Hotels::GetHotelListService.new({
account_id: params[:account_id],
user_email: session[:user_email],
user_token: session[:user_token]
})
result = service.call
if result['message'] == 'Unauthorized'
redirect_to unauthorized_path and return
elsif result['message'] == 'Not Found'
redirect_to unauthorized_path and return
else
result
end
end
end
end
关于ruby-on-rails - 在子方法中满足条件时中断 Controller 父操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35384424/