From 95072d221e5ea497967b6260369999cd986ae12d Mon Sep 17 00:00:00 2001 From: Dimitrij Denissenko Date: Mon, 22 Jun 2015 16:51:11 +0100 Subject: [PATCH] Fix coercion of complex arrays --- CHANGELOG.md | 1 + lib/grape/validations/validators/coerce.rb | 4 +- .../validations/validators/coerce_spec.rb | 37 +++++++++++++++---- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd1866cb8..c4af284b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ Next Release #### Fixes * [#1038](https://github.com/intridea/grape/pull/1038): Avoid dup-ing the String class when used in inherited params - [@rnubel](https://github.com/rnubel). +* [#1042](https://github.com/intridea/grape/issues/1042): Fix coercion of complex arrays - [@dim](https://github.com/dim). 0.12.0 (6/18/2015) ================== diff --git a/lib/grape/validations/validators/coerce.rb b/lib/grape/validations/validators/coerce.rb index 6b8b500b4..3255c2c53 100644 --- a/lib/grape/validations/validators/coerce.rb +++ b/lib/grape/validations/validators/coerce.rb @@ -41,7 +41,9 @@ def _valid_single_type?(klass, val) end def valid_type?(val) - if @option.is_a?(Array) || @option.is_a?(Set) + if val.instance_of?(InvalidValue) + false + elsif @option.is_a?(Array) || @option.is_a?(Set) _valid_array_type?(@option.first, val) else _valid_single_type?(@option, val) diff --git a/spec/grape/validations/validators/coerce_spec.rb b/spec/grape/validations/validators/coerce_spec.rb index 756fe4f38..391e58f59 100644 --- a/spec/grape/validations/validators/coerce_spec.rb +++ b/spec/grape/validations/validators/coerce_spec.rb @@ -11,6 +11,14 @@ def app end describe 'coerce' do + module CoerceValidatorSpec + class User + include Virtus.model + attribute :id, Integer + attribute :name, String + end + end + context 'i18n' do after :each do I18n.locale = :en @@ -82,14 +90,6 @@ def app end context 'complex objects' do - module CoerceValidatorSpec - class User - include Virtus.model - attribute :id, Integer - attribute :name, String - end - end - it 'error on malformed input for complex objects' do subject.params do requires :user, type: CoerceValidatorSpec::User @@ -148,6 +148,27 @@ class User expect(last_response.status).to eq(200) expect(last_response.body).to eq('TrueClass') end + + it 'Array of Complex' do + subject.params do + requires :arry, coerce: Array[CoerceValidatorSpec::User] + end + subject.get '/array' do + params[:arry].size + end + + get 'array', arry: [31] + expect(last_response.status).to eq(400) + expect(last_response.body).to eq('arry is invalid') + + get 'array', arry: { id: 31, name: 'Alice' } + expect(last_response.status).to eq(400) + expect(last_response.body).to eq('arry is invalid') + + get 'array', arry: [{ id: 31, name: 'Alice' }] + expect(last_response.status).to eq(200) + expect(last_response.body).to eq('1') + end end context 'Set' do