grape icon indicating copy to clipboard operation
grape copied to clipboard

Cannot distinguish empty Array from missing parameters

Open AaronBaldwin opened this issue 5 years ago • 3 comments

  optional :my_field, type: Array

When this optional field is set to [] (a valid value), Grape API removes it from the parameters. I cannot find any way to make this work in 0.14.0. I've tried using the coerce_with specifier, but that does not get called in either case of nil or [].

References: https://github.com/ruby-grape/grape/issues/1316 https://github.com/ruby-grape/grape/issues/707

I've tried the strategies posted on these other issues, but as mentioned, the coerce_with does not work and there is not anything in the docs about this behavior and how to fix it.

AaronBaldwin avatar Jan 22 '20 22:01 AaronBaldwin

Try writing a spec for what you intend to see @AaronBaldwin ?

dblock avatar Jan 23 '20 13:01 dblock

When this optional field is set to [] (a valid value), Grape API removes it from the parameters

Could you provide an example how the value was set to this field?(has json payload used?) and why do you think grape removes it?

dm1try avatar Jan 23 '20 15:01 dm1try

In case of Grape 1.3.1, the field is kept, however, the value "mutates" :slightly_smiling_face:

require 'grape'

class API < Grape::API
  prefix :api
  version 'v1', using: :path
  params do
    optional :collection, type: Array
  end
  post '/' do
    declared = declared(params)

    puts declared.inspect
  end
end

options = {
  method: 'POST',
  params: {
    collection: []
  }
}

env = Rack::MockRequest.env_for('/api/v1', options)
API.call env

Output:

{"collection"=>nil}

If collection=nil, the output would be {"collection"=>[]} :flushed:

dnesteryuk avatar Mar 31 '20 16:03 dnesteryuk