如何使用 Ruby 的 Grape 验证数组长度?

How to validate Array length using Ruby's Grape?

我有一组项目,我想确保它有至少一个项目不超过两个。(a值范围的种类)。 Grape 是否提出了任何优雅的方法来解决长度验证问题?

目前我有这样的结构。

params do
  requires :items, type Array[String] # ???
end

我正在考虑使用自定义验证编写a class,它接收最大值和最小值并将它们与数组长度进行比较。

Grape README:

中有一个解释如何执行此操作的示例
class Length < Grape::Validations::Base
  def validate_param!(attr_name, params)
    unless params[attr_name].length <= @option
      fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must be at the most #{@option} characters long"
    end
  end
end

对于数组的最大长度,您可以按照您期望的方式工作:

class MaxLength < Grape::Validations::Base
  def validate_param!(attr_name, params)
    unless params[attr_name].length <= @option
      fail Grape::Exceptions::Validation, 
      params: [attr_name.to_s],
      message: "must be at the most #{@option} elements long"
    end
  end
end

这是数组的最小长度:

class MinLength < Grape::Validations::Base
  def validate_param!(attr_name, params)
    unless params[attr_name].length >= @option
      fail Grape::Exceptions::Validation, 
      params: [attr_name.to_s],
      message: "must be at the least #{@option} elements long"
    end
  end
end

然后调用它:

params do
  requires :array, type: Array, min_length: 1, max_length: 2, desc: 'Array with defined length'
end