grape icon indicating copy to clipboard operation
grape copied to clipboard

Extend `given` to check against the value

Open danieldraper opened this issue 10 years ago • 6 comments

It would be nice to allow a value to be specified on a given so that different parameters could be included for example:

params do
  requires :grant_type, type: String, values: [:password, :refresh_token]
  requires :client_id, type: String

  given :grant_type, value: ->(*) { |attr| attr == :password } do
    requires :username, type: String
    requires :password, type: String
  end

  given :grant_type, value: ->(*) { |attr| attr == :refresh_token } do
    requires :refresh_token, type: String
  end
end

danieldraper avatar May 12 '16 10:05 danieldraper

I like it.

dblock avatar May 12 '16 11:05 dblock

I'm happy to look into implementation, any pointers on accessing the value from https://github.com/ruby-grape/grape/blob/master/lib/grape/dsl/parameters.rb or should I be looking elsewhere?

danieldraper avatar May 12 '16 11:05 danieldraper

@danieldraper that section of code is executed right when your API loads, and is what defines the new parameter scope with a dependent_on value. You'll need to update that to save the value lambda for later reference, and update ParamsScope#should_validate? to verify that, if the scope is dependent on an attribute, it also satisfies the value lambda.

Zooming out a bit, right now, given can take more than one parameter. You could either enforce the value check for all dependent parameters, or use a different format (maybe something like, given foo: ->(val) { val == :bar }, baz: ->(val) { val == :qaz } ... though it's a bit limiting and not as clear).

rnubel avatar May 12 '16 15:05 rnubel

@danieldraper can you check https://github.com/ruby-grape/grape/pull/1443 and close this issue please? Thanks.

glaucocustodio avatar Jul 19 '16 18:07 glaucocustodio

@dblock Could you close this, please?

towanda avatar Oct 31 '16 15:10 towanda

Closing via #1443.

dblock avatar Nov 01 '16 11:11 dblock