Make it possible to coerce nil Array of Types to []
Nobody has claimed this yet.
- Dominant language
- Ruby
- Stars
- 10k
- Forks
- 1.2k
- Avg merge
- 14h 38m
- Merged PRs (30d)
- 92
Description
Going back to our discussion in https://github.com/ruby-grape/grape/pull/2040#issuecomment-615483919, I've found it a bit tedious dealing with optional Array[Integer], Array[String], etc. types. Suppose I have an API with an optional parameter:
optional :values, type: Array[String], coerce_with: ->(val) { val.split(',').map(&:strip) }
I have four cases to consider for a PUT request:
| Parameter provided | Value | Intended behavior |
|---|---|---|
| Y | nil | Clear all values |
| Y | [] | Clear all values |
| N | N/A | Leaving existing values alone |
| Y | ["test", "foo"] | Update existing values |
The first two cases are identical, but we have hundreds of API calls, and I'd rather not fix all the supporting code because nil is now a valid input.
For optional parameters, I can't use default: [] because this always includes the parameter, even though it's optional. Adding the default value will cause us to clear out the values when I only want to coerce the value if the parameter is provided.
In Grape v1.3.x, the coercion method is not run for nil, so I can't even manually coerce nil to some other value with a custom method. To upgrade to Grape v1.3.x, I have to do the coercion within the API handler with this helper function:
def coerce_nil_param_to_array(params, key)
params.tap do |params|
params[key] = [] if params.key?(key) && params[key].nil?
end
end
For example:
update_params = declared_params(include_missing: false)
update_params = coerce_nil_param_to_array(declared_params, :values)
This isn't ideal; I could iterate through the options inside the route, but that doesn't feel right.
Now I'm wondering whether the coercion method should be run for nil types? Or make that an option?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the parameter-handling paths exposed through coerce_with, declared_params(include_missing: false), and the route options, then compare how optional Array types handle nil versus omitted parameters. Done means the intended nil-to-array behavior is defined and covered for the four cases: nil, [], omitted, and a populated array.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- ruby
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 32/100