我正在编写一个仅具有 REST API(没有 Web 界面等)的 Rails 应用程序。我需要检查是否使用正确的参数发出请求,如果没有则返回不同的错误代码。例如,我所有的 API 端点都需要一个 user_access_token 和一个 client_id。其他一些端点需要存在其他不同的参数。
在所有 Controller 中,我都有执行此检查的代码,但代码越来越重复,并且有许多 if 条件可以提取出来并放在其他地方。所以我想在我的 ApplicationController
中添加一个 before_filter
来执行此检查。我定义了一个包含所有端点到 required_params 映射的散列,并且此过滤器在控制权传递给相关的实际 Controller 之前运行。
但是对于某些端点,它变得有点复杂,因为如果存在一些其他参数,则需要一些参数,并且在某些情况下,需要两个参数之一。所以现在我想知道是否有更好的方法来做到这一点。
我做的对吗?有更好/标准化的方法吗?或者一些 gem 可以做到这一点?
最佳答案
我必须查看一些代码才能理解上下文。但它基本上听起来像你有你的所有其他 Controller 继承自的基础 ApplicationController。不同的是您期望的参数(除了始终需要提供的 user_access_token 和 client_id 之外)。由于您使用的是继承,因此您可以在 ApplicationController 中定义一个方法,其中包含您期望的参数列表,然后在您的子类中覆盖该方法以检查添加其他参数。您的基础 Controller 将负责进行实际验证,但子类将有机会覆盖所需的参数。
class ApplicationController < ActionController::Base
before_filter :validate_params
protected
def required_params
[:user_access_token, :client_id]
end
def validate_params
unless (require_params - params.keys).count.zero?
# do something
end
end
end
class AnotherController < ApplicationController
protected
def required_params
p = super + [:email, :password]
p = p + [:another, :and_another] if some_condition?
p
end
end
本质上,您会让子类决定是否需要添加任何额外的必需参数。当然我不知道你的确切背景是什么,但希望这会帮助你朝着正确的方向前进。当你有机会的时候做一些关于多态性的研究:-)
关于ruby-on-rails - Rails 中的 REST API 参数验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18521397/