我正在使用Rails编写的客户端应用程序来使用Rails API。如果用户未经过身份验证,则必须显示登录页面。我创建了一个只从一个Ruby类进行API调用的结构。现在从Ruby类中,如果响应状态是401,那么我必须显示登录页面。有没有办法将用户重定向到我的Ruby类的登录页面?
这是我的客户代码
class Client
def execute(method, url, params)
response = case method
when :get
HTTParty.get(url, query: params)
when :post
HTTParty.post(url, body: params)
when :put
HTTParty.put(url, body: params)
when :delete
HTTParty.delete(url, body: params)
else
nil
end
if response.status == 401
# should redirect to login page
else
# Send result to caller which will parse it and send back to the controller action who called it
end
end
end
答案 0 :(得分:2)
我通过引发自定义异常并在ApplicaionController中捕获它来解决了这个问题。 从那里我可以轻松地重定向到登录页面。