Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate mutual exclusivity of params in Grape API (Ruby)

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.

like image 363
Rene Wooller Avatar asked Dec 29 '25 10:12

Rene Wooller


2 Answers

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

like image 130
Jaro Avatar answered Dec 30 '25 22:12

Jaro


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.

like image 41
NARKOZ Avatar answered Dec 30 '25 23:12

NARKOZ