Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

coerce_with should be called for params with nil value #2164

Merged
merged 3 commits into from
Mar 5, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions lib/grape/validations/types/custom_type_coercer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,6 @@ def initialize(type, method = nil)
# this should always be a string.
# @return [Object] the coerced result
def call(val)
return if val.nil?

coerced_val = @method.call(val)

return coerced_val if coerced_val.is_a?(InvalidValue)
Expand Down
38 changes: 38 additions & 0 deletions spec/grape/validations/validators/coerce_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,44 @@ def self.parse(_val)
expect(last_response.body).to eq('3')
end

context 'Integer type and coerce_with should' do
before do
subject.params do
optional :int, type: Integer, coerce_with: (lambda do |val|
if val.nil?
0
else
val.to_i
end
end)
end
subject.get '/' do
params[:int].class.to_s
end
end

it 'coerce nil value to integer' do
get '/', int: nil

expect(last_response.status).to eq(200)
expect(last_response.body).to eq('Integer')
end

it 'not coerce missing field' do
get '/'

expect(last_response.status).to eq(200)
expect(last_response.body).to eq('NilClass')
end

it 'coerce integer as integer' do
get '/', int: 1

expect(last_response.status).to eq(200)
expect(last_response.body).to eq('Integer')
end
end

context 'Integer type and coerce_with potentially returning nil' do
before do
subject.params do
Expand Down