Skip to content

Commit 95072d2

Browse files
committed
Fix coercion of complex arrays
1 parent a37df3e commit 95072d2

File tree

3 files changed

+33
-9
lines changed

3 files changed

+33
-9
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ Next Release
88
#### Fixes
99

1010
* [#1038](https://github.com/intridea/grape/pull/1038): Avoid dup-ing the String class when used in inherited params - [@rnubel](https://github.com/rnubel).
11+
* [#1042](https://github.com/intridea/grape/issues/1042): Fix coercion of complex arrays - [@dim](https://github.com/dim).
1112

1213
0.12.0 (6/18/2015)
1314
==================

lib/grape/validations/validators/coerce.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ def _valid_single_type?(klass, val)
4141
end
4242

4343
def valid_type?(val)
44-
if @option.is_a?(Array) || @option.is_a?(Set)
44+
if val.instance_of?(InvalidValue)
45+
false
46+
elsif @option.is_a?(Array) || @option.is_a?(Set)
4547
_valid_array_type?(@option.first, val)
4648
else
4749
_valid_single_type?(@option, val)

spec/grape/validations/validators/coerce_spec.rb

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ def app
1111
end
1212

1313
describe 'coerce' do
14+
module CoerceValidatorSpec
15+
class User
16+
include Virtus.model
17+
attribute :id, Integer
18+
attribute :name, String
19+
end
20+
end
21+
1422
context 'i18n' do
1523
after :each do
1624
I18n.locale = :en
@@ -82,14 +90,6 @@ def app
8290
end
8391

8492
context 'complex objects' do
85-
module CoerceValidatorSpec
86-
class User
87-
include Virtus.model
88-
attribute :id, Integer
89-
attribute :name, String
90-
end
91-
end
92-
9393
it 'error on malformed input for complex objects' do
9494
subject.params do
9595
requires :user, type: CoerceValidatorSpec::User
@@ -148,6 +148,27 @@ class User
148148
expect(last_response.status).to eq(200)
149149
expect(last_response.body).to eq('TrueClass')
150150
end
151+
152+
it 'Array of Complex' do
153+
subject.params do
154+
requires :arry, coerce: Array[CoerceValidatorSpec::User]
155+
end
156+
subject.get '/array' do
157+
params[:arry].size
158+
end
159+
160+
get 'array', arry: [31]
161+
expect(last_response.status).to eq(400)
162+
expect(last_response.body).to eq('arry is invalid')
163+
164+
get 'array', arry: { id: 31, name: 'Alice' }
165+
expect(last_response.status).to eq(400)
166+
expect(last_response.body).to eq('arry is invalid')
167+
168+
get 'array', arry: [{ id: 31, name: 'Alice' }]
169+
expect(last_response.status).to eq(200)
170+
expect(last_response.body).to eq('1')
171+
end
151172
end
152173

153174
context 'Set' do

0 commit comments

Comments
 (0)