Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ValuesValidator for params wrapped in with block #2382

Merged
merged 2 commits into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/grape/validations/validators/values_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,12 @@ def except_message
end

def required_for_root_scope?
@required && @scope.root?
return false unless @required
Copy link
Contributor Author

@numbata numbata Dec 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"fail fast" if the param is not required.


scope = @scope
scope = scope.parent while scope.lateral?
Comment on lines +90 to +91
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated the logic here to handle nested parameters within a with block. The method now traverses up the scope hierarchy to check if the parameter's root scope is required, ensuring correct validation even when parameters are deeply nested within a `with' block.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could extract this into lateral_scope or something like that, although I am not sure it's worth it


scope.root?
end

def validation_exception(attr_name, message)
Expand Down
16 changes: 16 additions & 0 deletions spec/grape/validations/validators/values_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,13 @@ def even?(value)
optional :name, type: String, values: %w[a b], allow_blank: true
end
get '/allow_blank'

params do
with(type: String) do
requires :type, values: ValuesModel.values
end
end
get 'values_wrapped_by_with_block'
end
end

Expand Down Expand Up @@ -730,4 +737,13 @@ def app
end
end
end

context 'when wrapped by with block' do
it 'rejects an invalid value' do
get 'values_wrapped_by_with_block'

expect(last_response.status).to eq 400
expect(last_response.body).to eq({ error: 'type is missing, type does not have a valid value' }.to_json)
end
end
end