Skip to content

Commit 9f49439

Browse files
committed
coerce an empty string to nil in case of the bool type
1 parent 2a4e2c2 commit 9f49439

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
#### Fixes
1212

13+
* [#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).
1314
* [#2043](https://github.com/ruby-grape/grape/pull/2043): Modify declared for nested array and hash - [@kadotami](https://github.com/kadotami).
1415
* Your contribution here.
1516
* [#2040](https://github.com/ruby-grape/grape/pull/2040): Fix a regression with Array of type nil - [@ericproulx](https://github.com/ericproulx).

lib/grape/validations/types/primitive_coercer.rb

+9-2
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def initialize(type, strict = false)
3636

3737
def call(val)
3838
return InvalidValue.new if reject?(val)
39-
return nil if val.nil?
39+
return nil if val.nil? || treat_as_nil?(val)
4040
return '' if val == ''
4141

4242
super
@@ -46,7 +46,7 @@ def call(val)
4646

4747
attr_reader :type
4848

49-
# This method maintaine logic which was defined by Virtus. For example,
49+
# This method maintains logic which was defined by Virtus. For example,
5050
# dry-types is ok to convert an array or a hash to a string, it is supported,
5151
# but Virtus wouldn't accept it. So, this method only exists to not introduce
5252
# breaking changes.
@@ -55,6 +55,13 @@ def reject?(val)
5555
(val.is_a?(String) && type == Hash) ||
5656
(val.is_a?(Hash) && type == String)
5757
end
58+
59+
# Dry-Types treats an empty string as invalid. However, Grape considers an empty string as
60+
# absence of a value and coerces it into nil. See a discussion there
61+
# https://github.com/ruby-grape/grape/pull/2045
62+
def treat_as_nil?(val)
63+
val == '' && type == Grape::API::Boolean
64+
end
5865
end
5966
end
6067
end

spec/grape/validations/types/primitive_coercer_spec.rb

+4
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@
2626
it 'returns an error when the given value cannot be coerced' do
2727
expect(subject.call(123)).to be_instance_of(Grape::Validations::Types::InvalidValue)
2828
end
29+
30+
it 'coerces an empty string to nil' do
31+
expect(subject.call('')).to be_nil
32+
end
2933
end
3034

3135
context 'String' do

0 commit comments

Comments
 (0)