Params with default values [feature request?]
Nobody has claimed this yet.
- Dominant language
- Ruby
- Stars
- 10k
- Forks
- 1.2k
- Avg merge
- 14h 38m
- Merged PRs (30d)
- 92
Description
Hi folks, consider the following example:
resource :companies do
params do
requires :name, allow_blank: false
end
post do
# where `current_user` is the signed in user
Company.create(declared(params).merge!(seller_id: current_user.id))
end
end
Wouldn't be nice if we could write something like:
resource :companies do
params do
requires :name, allow_blank: false
# `default` is an example, maybe another name makes more sense
default :seller_id, default_value: ->() { current_user.id }
end
post do
Company.create(declared(params))
end
end
It would help keeping our code DRY.
What do you think? Is there some way to do something similar it today?
Note after opening this issue:
I just discover it works:
resource :companies do
params do
requires :name, allow_blank: false
optional :seller_id, default: 1
end
post do
Company.create(declared(params))
end
end
declared(params) contains seller_id with the proper value 1.
but all these dont work:
optional :seller_id, default: @current_user.id
optional :seller_id, default: ->() { @current_user.id }
module ApiHelpers
extend Grape::API::Helpers
def current_user
@current_user
end
end
helpers ApiHelpers
...
optional :seller_id, default: current_user.id
# neither
optional :seller_id, default: ->() { current_user.id }
...
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 by reproducing the examples in the params block, comparing static defaults with defaults that reference current_user or a lambda. Trace how optional parameters are processed before declared(params) is built. Done would require an agreed approach for context-dependent defaults, documented behavior, and tests covering the supported form.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- ruby
- Domain
- api
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100