Skip to content

Commit

Permalink
Reset index before iterating
Browse files Browse the repository at this point in the history
Add reset_index to facilitate
  • Loading branch information
ericproulx committed Jun 25, 2024
1 parent bd76c1f commit 70e2ea8
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/grape/validations/attributes_iterator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ def each(&block)
private

def do_each(params_to_process, parent_indicies = [], &block)
@scope.reset_index # gets updated depending on the size of params_to_process
params_to_process.each_with_index do |resource_params, index|
# when we get arrays of arrays it means that target element located inside array
# we need this because we want to know parent arrays indicies
Expand Down
4 changes: 4 additions & 0 deletions lib/grape/validations/params_scope.rb
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ def required?
!@optional
end

def reset_index
@index = nil
end

protected

# Adds a parameter declaration to our list of validations.
Expand Down
42 changes: 42 additions & 0 deletions spec/grape/validations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1988,6 +1988,48 @@ def validate_param!(attr_name, params)
expect(last_response.status).to eq(400)
end
end

# Ensure there is no leakage of indices between requests
context 'required with a hash inside an array' do
before do
subject.params do
requires :items, type: Array do
requires :item, type: Hash do
requires :name, type: String
end
end
end
subject.post '/required' do
'required works'
end
end

let(:valid_item) { { item: { name: 'foo' } } }

let(:params) do
{
items: [
valid_item,
valid_item,
{}
]
}
end

it 'makes sure the error message is independent of the previous request' do
post_with_json '/required', {}
expect(last_response).to be_bad_request
expect(last_response.body).to eq('items is missing, items[item][name] is missing')

post_with_json '/required', params
expect(last_response).to be_bad_request
expect(last_response.body).to eq('items[2][item] is missing, items[2][item][name] is missing')

post_with_json '/required', {}
expect(last_response).to be_bad_request
expect(last_response.body).to eq('items is missing, items[item][name] is missing')
end
end
end

describe 'require_validator' do
Expand Down

0 comments on commit 70e2ea8

Please sign in to comment.