Skip to content

Commit

Permalink
coerce an empty string to nil in case of the bool type
Browse files Browse the repository at this point in the history
  • Loading branch information
dnesteryuk committed May 3, 2020
1 parent 2a4e2c2 commit fe172fe
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@

#### 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.
* [#2040](https://github.com/ruby-grape/grape/pull/2040): Fix a regression with Array of type nil - [@ericproulx](https://github.com/ericproulx).
* Your contribution here.

### 1.3.2 (2020/04/12)

Expand Down
11 changes: 9 additions & 2 deletions lib/grape/validations/types/primitive_coercer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -46,7 +46,7 @@ def call(val)

attr_reader :type

# This method maintaine logic which was defined by Virtus. For example,
# This method maintains 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.
Expand All @@ -55,6 +55,13 @@ 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 considers an empty string as
# absence of a value and coerces it into nil. See a discussion there
# https://github.com/ruby-grape/grape/pull/2045
def treat_as_nil?(val)
val == '' && type == Grape::API::Boolean
end
end
end
end
Expand Down
4 changes: 4 additions & 0 deletions spec/grape/validations/types/primitive_coercer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit fe172fe

Please sign in to comment.