Skip to content

Commit 0219c75

Browse files
authored
Fix a regression in coerce_with when coercion returns nil (#2026)
Previously nil was handled as valid value for coercion for integer parameters. With refactoring introduced in 1.3.0 integer parameter coerced with a custom method can't coerce to nil any more. This change reverts back to previous behavior where coercion to nil was allowed.
1 parent c8fd21b commit 0219c75

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#### Fixes
1111

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

lib/grape/validations/types/custom_type_coercer.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def call(val)
6060
end
6161

6262
def coerced?(val)
63-
@type_check.call val
63+
val.nil? || @type_check.call(val)
6464
end
6565

6666
private

spec/grape/validations/validators/coerce_spec.rb

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -525,6 +525,46 @@ def self.parsed?(value)
525525
expect(last_response.body).to eq('3')
526526
end
527527

528+
context 'Integer type and coerce_with potentially returning nil' do
529+
before do
530+
subject.params do
531+
requires :int, type: Integer, coerce_with: (lambda do |val|
532+
if val == '0'
533+
nil
534+
elsif val.match?(/^-?\d+$/)
535+
val.to_i
536+
else
537+
val
538+
end
539+
end)
540+
end
541+
subject.get '/' do
542+
params[:int].class.to_s
543+
end
544+
end
545+
546+
it 'accepts value that coerces to nil' do
547+
get '/', int: '0'
548+
549+
expect(last_response.status).to eq(200)
550+
expect(last_response.body).to eq('NilClass')
551+
end
552+
553+
it 'coerces to Integer' do
554+
get '/', int: '1'
555+
556+
expect(last_response.status).to eq(200)
557+
expect(last_response.body).to eq('Integer')
558+
end
559+
560+
it 'returns invalid value if coercion returns a wrong type' do
561+
get '/', int: 'lol'
562+
563+
expect(last_response.status).to eq(400)
564+
expect(last_response.body).to eq('int is invalid')
565+
end
566+
end
567+
528568
it 'must be supplied with :type or :coerce' do
529569
expect do
530570
subject.params do

0 commit comments

Comments
 (0)