让我们想象一下我有一个班级
class Test < ActiveRecord::Base
include AuthenticatorHelper
def test
authenticate_or_fail!
puts "If I fail, this should be unreachable"
end
end
和
module AuthenticationHelper
def authenticate_or_fail!
@user = User.find(params[:token])
unless @user
render :json => {code: 401, :err => 'Unauthorized'} and return
end
end
end
我想要做的是验证或回复json msg。但是,由于嵌套,它显然会忽略我的返回语句,并且它将始终打印我的消息
如果我失败了,这应该无法访问
答案 0 :(得分:1)
关于问题
您可以将调用解压缩为before_filter
/ before_action
(基于rails版本)。
class Test < ActiveRecord::Base
include AuthenticatorHelper
before_action :authenticate_or_fail!
def test
puts "If I fail, this should be unreachable"
end
end
有关详细信息,请参阅the documentation。
因为你的helper方法在出现故障时呈现,所以rails会阻止调用test
方法。那么你不需要and return
部分,它只会从方法返回,因此是NoOp。
除了这个问题外,还值得注意的是:
我不想为此指出错误。我只是想阻止OP稍后遇到一系列错误。
User.find(params[:token])
如果未找到记录,则会引发异常。因此,如果令牌无效,则不会评估unless @user
部分。你可以用
User.find_by(id: params[:token])
代替。
您的类看起来像一个控制器,名为Test
并继承自ActiveRecord::Base
。第一个是不寻常的,因为TestsController
会更多地沿着铁路线而且秒看起来是错误的。控制器必须继承ApplicationController
(它本身继承自ActionController::Base
)