variable key names using Grape API in Rails

59 views Asked by At

From the grape documentation on validation/coercion all the examples they provide with hashes and nested hashes seem to assume that I know precisely the name of every key inside a hash object, along with the exact number of keys I'll have for each hash object. There seem to be plenty of ways to customize validations for the values, and even the data types of those keys - but is there no way to handle keys dynamically?

The structure I have looks something like this

param_name = { randomSHA256Value: { 0: "string 1", 1: "string 2", 2: "string 3" } }

The only thing I can predict is that I have parameter called param_name and that it's a hash object. I can't predict the actual keyname of randomSHA256Value and I don't know how many keys will be nested within it.

1

There are 1 answers

0
APysnack On

For anyone who may encounter this in the future, I was able to get the desired results by using:

params do
  requires :param_name, type: Array[Hash]
end

It's possible that the structure of Hash needs to be declared somewhere, but I don't think it does.

It accepts an array of hash objects and doesn't require any explicit naming of the keys inside the hash. So ultimately I was able to do something like

[{ key_1: randomSHA256Value,
   key_2: ["string 1", "string 2", "string 3"] }]

and once the data was received, I could reshape it as necessary