Skip to content

Commit aa72fa7

Browse files
author
Braktar
committed
Coerce_with nil value but not the missing fields
1 parent 8996fb1 commit aa72fa7

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

lib/grape/validations/types/custom_type_coercer.rb

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,6 @@ def initialize(type, method = nil)
5252
# this should always be a string.
5353
# @return [Object] the coerced result
5454
def call(val)
55-
return if val.nil?
56-
5755
coerced_val = @method.call(val)
5856

5957
return coerced_val if coerced_val.is_a?(InvalidValue)

spec/grape/validations/validators/coerce_spec.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,44 @@ def self.parse(_val)
754754
expect(last_response.body).to eq('3')
755755
end
756756

757+
context 'Integer type and coerce_with should' do
758+
before do
759+
subject.params do
760+
optional :int, type: Integer, coerce_with: (lambda do |val|
761+
if val.nil?
762+
0
763+
else
764+
val.to_i
765+
end
766+
end)
767+
end
768+
subject.get '/' do
769+
params[:int].class.to_s
770+
end
771+
end
772+
773+
it 'coerce nil value to integer' do
774+
get '/', int: nil
775+
776+
expect(last_response.status).to eq(200)
777+
expect(last_response.body).to eq('Integer')
778+
end
779+
780+
it 'not coerce missing field' do
781+
get '/'
782+
783+
expect(last_response.status).to eq(200)
784+
expect(last_response.body).to eq('NilClass')
785+
end
786+
787+
it 'coerce integer as integer' do
788+
get '/', int: 1
789+
790+
expect(last_response.status).to eq(200)
791+
expect(last_response.body).to eq('Integer')
792+
end
793+
end
794+
757795
context 'Integer type and coerce_with potentially returning nil' do
758796
before do
759797
subject.params do

0 commit comments

Comments
 (0)