Skip to content

Commit 7404f1e

Browse files
committed
coerce an empty string to nil in case of the bool type
1 parent 5d226f2 commit 7404f1e

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
#### Fixes
1111

12+
* [#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).
1213
* [#2043](https://github.com/ruby-grape/grape/pull/2043): Modify declared for nested array and hash - [@kadotami](https://github.com/kadotami).
1314
* Your contribution here.
1415

lib/grape/validations/types/primitive_coercer.rb

+8-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 maintain 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,12 @@ 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 community wants to have
60+
# a different behavior.
61+
def treat_as_nil?(val)
62+
val == '' && type == Grape::API::Boolean
63+
end
5864
end
5965
end
6066
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)