From 234a4e85c8533b29668ed865984544d7402b4927 Mon Sep 17 00:00:00 2001 From: Braktar Date: Mon, 5 Oct 2020 16:29:01 +0200 Subject: [PATCH 1/2] nil of types return array --- spec/grape/validations/params_scope_spec.rb | 37 +++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/spec/grape/validations/params_scope_spec.rb b/spec/grape/validations/params_scope_spec.rb index 9ef14af9ff..6ab21c2584 100644 --- a/spec/grape/validations/params_scope_spec.rb +++ b/spec/grape/validations/params_scope_spec.rb @@ -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 From 579fabcd42f1d22ab87938347e8d8af7d5c1b2e6 Mon Sep 17 00:00:00 2001 From: Braktar Date: Mon, 5 Oct 2020 17:00:43 +0200 Subject: [PATCH 2/2] Avoid limit case --- lib/grape/dsl/inside_route.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/grape/dsl/inside_route.rb b/lib/grape/dsl/inside_route.rb index 6f4becfea2..e03ebed1d4 100644 --- a/lib/grape/dsl/inside_route.rb +++ b/lib/grape/dsl/inside_route.rb @@ -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?(',') [] elsif type == 'Set' || type&.start_with?('#