ruby-grape / ruby-grape/grape

Result of the block in the 'given' method are ignored

Open
#2,191 4 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

Hello!

In the Grape 1.0.2 the code below works fine:

params do
  requires :payment_type, type: String, values: ['ccard', 'paypal', 'applepay']
  given payment_type: ->(val) { val == 'applepay' } do
    optional :m_card_holder, type: Hash, as: :card_holder do
      optional :first_name, type: String, allow_blank: false, desc: 'Cardholder first name'
      optional :last_name, type: String, allow_blank: false, desc: 'Cardholder last name'
    end
  end
  given payment_type: ->(val) { !(val === 'applepay') } do
    optional :card_holder, type: String, allow_blank: false
  end
end
post '', root: 'payments' do
  # Payments processing
  # ...
end

When the request were from Apple Pay, the card_holder parameter became Hash and were parsed as Hash,
otherwise it been treated as String. It was fine for a time, but then the Grape were upgraded to 1.5.3,
this behavior became broken. In the version 1.5.3, result of the blocks in the 'given' method are ignored
and 'declared' method resturns all the parameters defined in 'params' without conditions. In the case above, the 'cardholder',
passed from request as string in accordance with payment_type='ccard', parsed by Grape as Hash instead of string,
and causes exception

undefined method `any?' for "NA ME":String

in the line https://github.com/ruby-grape/grape/blob/e83e81fe95d71134f2156aa6f31c22fcf954227f/lib/grape/dsl/inside_route.rb#L61

It is unexpected behaviour and I didn't find any notes about changes in the 'given' methods, it's looks like a bug.

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 with lib/grape/dsl/inside_route.rb at the linked line and reproduce the payment_type example on Grape 1.5.3. Trace how given blocks affect declared parameters, then verify that card_holder keeps the conditional type and no longer raises the reported String/Hash exception.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
api, backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.