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

时间:2019-07-12 23:22:20

标签: ruby grape

我有一系列项目,并希望确保它具有至少一个项目不超过两个。(一种值范围)。 Grape会提出任何优雅的方法来解决长度验证问题吗?

目前我有这样的结构。

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

我正在考虑编写具有自定义验证的类,该类将接收最大值和最小值并将它们与数组长度进行比较。

1 个答案:

答案 0 :(得分:1)

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