From 7d834109a158ced143ebfc856840b3ea340c9a34 Mon Sep 17 00:00:00 2001 From: Dmitriy Nesteryuk Date: Sun, 3 May 2020 16:19:42 +0300 Subject: [PATCH] coerce an empty string to nil in case of the bool type --- CHANGELOG.md | 1 + lib/grape/validations/types/primitive_coercer.rb | 10 ++++++++-- spec/grape/validations/types/primitive_coercer_spec.rb | 4 ++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0517bbb63f..00ea150f2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ #### Fixes +* [#2049](https://github.com/ruby-grape/grape/pull/2049): Coerce an empty string to nil in case of the bool type - [@dnesteryuk](https://github.com/dnesteryuk). * [#2043](https://github.com/ruby-grape/grape/pull/2043): Modify declared for nested array and hash - [@kadotami](https://github.com/kadotami). * Your contribution here. diff --git a/lib/grape/validations/types/primitive_coercer.rb b/lib/grape/validations/types/primitive_coercer.rb index 334bf90497..d8f371bb65 100644 --- a/lib/grape/validations/types/primitive_coercer.rb +++ b/lib/grape/validations/types/primitive_coercer.rb @@ -36,7 +36,7 @@ def initialize(type, strict = false) def call(val) return InvalidValue.new if reject?(val) - return nil if val.nil? + return nil if val.nil? || treat_as_nil?(val) return '' if val == '' super @@ -46,7 +46,7 @@ def call(val) attr_reader :type - # This method maintaine logic which was defined by Virtus. For example, + # This method maintain logic which was defined by Virtus. For example, # dry-types is ok to convert an array or a hash to a string, it is supported, # but Virtus wouldn't accept it. So, this method only exists to not introduce # breaking changes. @@ -55,6 +55,12 @@ def reject?(val) (val.is_a?(String) && type == Hash) || (val.is_a?(Hash) && type == String) end + + # Dry-Types treats an empty string as invalid. However, Grape community wants to have + # a different behavior. + def treat_as_nil?(val) + val == '' && type == Grape::API::Boolean + end end end end diff --git a/spec/grape/validations/types/primitive_coercer_spec.rb b/spec/grape/validations/types/primitive_coercer_spec.rb index d215bf3325..f97b0d9977 100644 --- a/spec/grape/validations/types/primitive_coercer_spec.rb +++ b/spec/grape/validations/types/primitive_coercer_spec.rb @@ -26,6 +26,10 @@ it 'returns an error when the given value cannot be coerced' do expect(subject.call(123)).to be_instance_of(Grape::Validations::Types::InvalidValue) end + + it "coerces an empty string to nil" do + expect(subject.call('')).to be_nil + end end context 'String' do