Skip to content

Commit f531fda

Browse files
Add support for Rack::Multipart::UploadedFile and don't care about parameter presence in the validation.
1 parent 8d98e1d commit f531fda

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

lib/grape/validations/coerce.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ def validate_param!(attr_name, params)
1616
end
1717
end
1818

19+
class InvalidValue; end
1920
private
2021

2122
def _valid_array_type?(type, values)
@@ -27,8 +28,11 @@ def _valid_array_type?(type, values)
2728
def _valid_single_type?(klass, val)
2829
if klass == Virtus::Attribute::Boolean
2930
val.is_a?(TrueClass) || val.is_a?(FalseClass)
31+
elsif klass == Rack::Multipart::UploadedFile
32+
val.is_a?(Hashie::Mash) && val.key?(:tempfile)
3033
else
31-
val.is_a?(klass)
34+
# allow nil, to ignore when a parameter is absent
35+
val.nil? || val.is_a?(klass)
3236
end
3337
end
3438

@@ -47,7 +51,7 @@ def coerce_value(type, val)
4751
# not the prettiest but some invalid coercion can currently trigger
4852
# errors in Virtus (see coerce_spec.rb)
4953
rescue
50-
nil
54+
InvalidValue.new
5155
end
5256

5357
end

spec/grape/validations/coerce_spec.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ class API < Grape::API
3232

3333
params do
3434
requires :int, :coerce => Integer
35+
optional :int2, :coerce => Integer
3536
optional :arr, :coerce => Array[Integer]
3637
optional :bool, :coerce => Array[Boolean]
3738
end
@@ -76,12 +77,12 @@ def app
7677
end
7778

7879
it 'should coerce inputs' do
79-
get('/coerce', :int => "43")
80+
get('/coerce', :int => "43", :int2 => "42")
8081
last_response.status.should == 200
8182
ret = MultiJson.load(last_response.body)
8283
ret["int"].should == "Fixnum"
83-
84-
get('/coerce', :int => "40", :arr => ["1","20","3"], :bool => [1, 0])
84+
85+
get('/coerce', :int => "40", :int2 => "42", :arr => ["1","20","3"], :bool => [1, 0])
8586
# last_response.body.should == ""
8687
last_response.status.should == 200
8788
ret = MultiJson.load(last_response.body)
@@ -90,4 +91,8 @@ def app
9091
ret["bool"].should == true
9192
end
9293

94+
it 'should not return an error when an optional parameter is nil' do
95+
get('/coerce', :int => "40")
96+
last_response.status.should == 200
97+
end
9398
end

0 commit comments

Comments
 (0)