rubyapirackruby-grapegrape-api

Ruby/Grape required parameters on a certain condition


For one of my methods the following isn't working. I pretty much copied everything straight out of the official documentation:

params do
requires :authenticationType, type: Array[String], values: ['LOCAL', 'AD']
given authenticationType: ->(val) { val == 'LOCAL' } do
  requires :admin, type: String, allow_blank: false, regexp: /^[\w\.\@-]{1,64}$/
  requires :password, type: String, allow_blank: false, regexp: /^[\w\.\@-]{1,64}$/
end
end

It is giving an error on the "given" line. Anyone know what is wrong. My goal: ONLY if 'authenticationType' == 'LOCAL' should the user provide 'admin' and 'password'

error:

[ 2017-03-03 00:39:18.4848 14970/7f5d0603f700 age/Cor/App/Implementation.cpp:304 ]: Could not spawn process for application /vagrant/masterapi: An error occurred while starting up the preloader. Error ID: 0bd79149 Error details saved to: /tmp/passenger-error-3OYsdJ.html Message from application: Grape::Exceptions::UnknownParameter (Grape::Exceptions::UnknownParameter)
/usr/local/lib/ruby/gems/2.3.0/gems/grape-0.16.2/lib/grape/dsl/parameters.rb:170:in block in given'
/usr/local/lib/ruby/gems/2.3.0/gems/grape-0.16.2/lib/grape/dsl/parameters.rb:169:in
each'
/usr/local/lib/ruby/gems/2.3.0/gems/grape-0.16.2/lib/grape/dsl/parameters.rb:169:in given' /vagrant/masterapi/controllers/papi_controller.rb:93:in block in '


Solution

  • The 'given' accepts proc only since grape version 0.17, implemented in merge request (MR) 1443. So you should either update, or if that's not feasible, try back-porting this MR to 0.16.2.

    Here's the README for your version.

    Also, in your example, authenticationType param is of type Array[String], so (at least in grape 0.17), the proc will receive a Hashie::Array.

    This means:

    ->(val) { val == 'LOCAL' }

    should be

    ->(val) { val.first == 'LOCAL' }