Skip to content

Commit

Permalink
Merge 7404f1e into 5d226f2
Browse files Browse the repository at this point in the history
  • Loading branch information
dnesteryuk committed May 3, 2020
2 parents 5d226f2 + 7404f1e commit bdd9545
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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.

Expand Down
10 changes: 8 additions & 2 deletions lib/grape/validations/types/primitive_coercer.rb
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 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.
Expand All @@ -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
Expand Down
4 changes: 4 additions & 0 deletions spec/grape/validations/types/primitive_coercer_spec.rb
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 bdd9545

Please sign in to comment.