[英]Exit Ruby On Rails controller method from helper
Let's imagine I have a class假设我有一堂课
class Test < ActiveRecord::Base
include AuthenticatorHelper
def test
authenticate_or_fail!
puts "If I fail, this should be unreachable"
end
end
and和
module AuthenticationHelper
def authenticate_or_fail!
@user = User.find(params[:token])
unless @user
render :json => {code: 401, :err => 'Unauthorized'} and return
end
end
end
What I want to do is either authenticate or reply with a json msg.我想要做的是使用 json msg 进行身份验证或回复。 However, it will obviously ignore my return statement due to nesting and it will always print my message但是,由于嵌套,它显然会忽略我的 return 语句,并且它会始终打印我的消息
If I fail, this should be unreachable如果我失败了,这应该是无法访问的
Regarding the question关于问题
You could extract the call into a before_filter
/ before_action
(based on the rails version).您可以将调用提取到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
Please see the documentation for further details.有关更多详细信息,请参阅文档。
Because your helper method renders in case of a failure, rails will prevent the test
method to be called.因为您的辅助方法会在失败时呈现,所以 rails 将阻止调用test
方法。 You will not need the and return
part then, which would only have returned from the method anyway and as such was a NoOp.那时您将不需要and return
部分,无论如何它只会从方法返回,因此是 NoOp。
Apart from the question but also noteworthy:除了这个问题还要值得注意的是:
I don't want to point out errors for the sake of it.我不想为此指出错误。 I just want to prevent the OP from running into a series of bugs later on.我只是想防止 OP 以后遇到一系列错误。
User.find(params[:token])
Will raise an exception if no record is found.如果没有找到记录,将引发异常。 Because of that, the unless @user
part will not be evaluated in case of an invalid token.因此,在令牌无效的情况下, unless @user
部分将不会被评估。 You could use你可以用
User.find_by(id: params[:token])
instead.反而。
Your class which looks like it acts as a controller is named Test
and inherits from ActiveRecord::Base
.您的类看起来像一个控制器,名为Test
并继承自ActiveRecord::Base
。 The first is unusual as TestsController
would be more along the lines of rails and the seconds looks plain wrong.第一个是不寻常的,因为TestsController
会更多地沿着轨道线并且秒看起来完全错误。 A controller has to inherit from ApplicationController
(which itself inherits from ActionController::Base
)控制器必须从ApplicationController
继承(它本身从ActionController::Base
继承)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.