ruby-grape / ruby-grape/grape

Params with default values [feature request?]

Open
#1,396 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug?
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.