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

field using types turned into array when declared(params) #2112

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 1 addition & 2 deletions lib/grape/dsl/inside_route.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,9 @@ def handle_passed_param(params_nested_path, has_passed_children = false, &_block
route_options_params = options[:route_options][:params] || {}
type = route_options_params.dig(key, :type)
has_children = route_options_params.keys.any? { |k| k != key && k.start_with?(key) }

if type == 'Hash' && !has_children
{}
elsif type == 'Array' || type&.start_with?('[')
elsif type == 'Array' || type && type.start_with?('[') && !type.include?(',')
Copy link
Contributor

Choose a reason for hiding this comment

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

You are right @dblock that working with Strings here is not ideal. I don't know enough to know if there is a better alternative.

[]
elsif type == 'Set' || type&.start_with?('#<Set')
Set.new
Expand Down
37 changes: 37 additions & 0 deletions spec/grape/validations/params_scope_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,43 @@ def app
end
end

context 'when using multiple types' do
it 'coerces the parameter via the type\'s parse method' do
subject.params do
requires :bar, type: Array do
optional :foo, types: [String, Float, Integer], coerce_with: ->(c) {
if c
if /([0-9]+):([0-9]+):([0-9]+)/ =~ c.to_s
'HH:MM:SS format'
elsif /\A[0-9]+\.{0,1}[0-9]*\z/ =~ c.to_s
'Float or Integer format'
else
'Invalid Time value'
end
end
}
end
end
subject.post('/types') { declared(params)[:bar].first[:foo] }

post '/types', bar: [{ foo: '00:00:01' }]
expect(last_response.status).to eq(201)
expect(last_response.body).to eq('HH:MM:SS format')

post '/types', bar: [{ foo: 1 }]
expect(last_response.status).to eq(201)
expect(last_response.body).to eq('Float or Integer format')

post '/types', bar: [{ foo: 1.0 }]
expect(last_response.status).to eq(201)
expect(last_response.body).to eq('Float or Integer format')

post '/types', bar: [{ foo: nil }]
expect(last_response.status).to eq(201)
expect(last_response.body).to eq('')
end
end

context 'when using custom types' do
module ParamsScopeSpec
class CustomType
Expand Down