1

Is it possible to run a custom validator against each element of array in Grape? I know I can validate whole array with my validator, but I think error messages would be better if I use it for each element.

My parameters look like this:

  "conditions": [
      {
          "field": "interests",
          "operator": "any",
          "value": ['cars', 'cats']
      },
      {
          "field": "age",
          "operator": "gt",
          "value": 25
      }
  ]

With requires :conditions, type: Array, valid_conditions: true the validator is run for the whole array. Is it best I can get?

katafrakt
  • 2,438
  • 15
  • 19

2 Answers2

0

This is totally possible, You can assert the value for specific keys in a response.

assert_equal some_obj[0].first[1], "interests" 

Here is this same thing in irb

   Success weeds out the uncommitted ~ irb
2.2.3 :001 > a = [{:field=>"interests", :operator=>"any", :value=>["cars", "cats"]}]
 => [{:field=>"interests", :operator=>"any", :value=>["cars", "cats"]}]
2.2.3 :002 > a[0].first
 => [:field, "interests"]
2.2.3 :003 > a[0].first[1]
 => "interests"
2.2.3 :004 >
znon
  • 71
  • 2
0

Yes it's possible, but you have to use a custom validator.

Here is an example

class Validator < Grape::Validations::Base
  def validate_param!(attr_name, params)
    unless params[attr_name].each { //your code here }
      fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: 'your message'
    end
  end
end

You would then use it like this:

requires :conditions, type: Array, validator: true