2

When defining an API using Grape, there is a very convenient way of validating the presence and type of parameters, e.g.:

params do
    requires :param1, type: String
    optional :param1, type: Integer
end

However I can't see a convenient way of specifying that two parameters are mutually exclusive. EG it would be something like:

params do
    requires :creatureName, type: String
    requires 
        either :scaleType, type: String
        or :furType, type: String 
end

I'm interested in suggestions for the most convenient way to get around this.

Ashish Chopra
  • 1,413
  • 9
  • 23
Rene Wooller
  • 1,107
  • 13
  • 22

3 Answers3

4

You can also use exactly_one_of:

params do
  optional :scale_type
  optional :fur_type
  exactly_one_of :scale_type, :fur_type
end

at_least_one_of, all_or_none_of are also available. More about it here

Jaro
  • 860
  • 9
  • 21
2

Parameters can be defined as mutually_exclusive, ensuring that they aren't present at the same time in a request.

params do
  optional :beer
  optional :wine
  mutually_exclusive :beer, :wine
end

Warning: Never define mutually exclusive sets with any required params. Two mutually exclusive required params will mean params are never valid, thus making the endpoint useless. One required param mutually exclusive with an optional param will mean the latter is never valid.

NARKOZ
  • 27,203
  • 7
  • 68
  • 90
1

Looking for the same thing. Your question got me to open the hood and see if it could be done. Here's the pull request

oliverbarnes
  • 2,111
  • 1
  • 20
  • 31