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

Fix a regression in coerce_with when coercion returns nil #2026

Merged
merged 2 commits into from
Mar 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#### Fixes

* Your contribution here.
* [#2026](https://github.com/ruby-grape/grape/pull/2026): Fix a regression in `coerce_with` when coercion returns `nil` - [@misdoro](https://github.com/misdoro).
* [#2025](https://github.com/ruby-grape/grape/pull/2025): Fix Decimal type category - [@kdoya](https://github.com/kdoya).
* [#2019](https://github.com/ruby-grape/grape/pull/2019): Avoid coercing parameter with multiple types to an empty Array - [@stanhu](https://github.com/stanhu).

Expand Down
2 changes: 1 addition & 1 deletion lib/grape/validations/types/custom_type_coercer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def call(val)
end

def coerced?(val)
@type_check.call val
val.nil? || @type_check.call(val)
end

private
Expand Down
40 changes: 40 additions & 0 deletions spec/grape/validations/validators/coerce_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,46 @@ def self.parsed?(value)
expect(last_response.body).to eq('3')
end

context 'Integer type and coerce_with potentially returning nil' do
before do
subject.params do
requires :int, type: Integer, coerce_with: (lambda do |val|
if val == '0'
nil
elsif val.match?(/^-?\d+$/)
val.to_i
else
val
end
end)
end
subject.get '/' do
params[:int].class.to_s
end
end

it 'accepts value that coerces to nil' do
get '/', int: '0'

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

it 'coerces to Integer' do
get '/', int: '1'

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

it 'returns invalid value if coercion returns a wrong type' do
get '/', int: 'lol'

expect(last_response.status).to eq(400)
expect(last_response.body).to eq('int is invalid')
end
end

it 'must be supplied with :type or :coerce' do
expect do
subject.params do
Expand Down