Skip to content

Commit

Permalink
The length validator only takes effect for parameters with types th…
Browse files Browse the repository at this point in the history
…at support `#length` method
  • Loading branch information
OuYangJinTing committed Jul 25, 2024
1 parent 2b8567a commit b7a7701
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#### Features

* [#2475](https://github.com/ruby-grape/grape/pull/2475): Remove Grape::Util::Registrable - [@ericproulx](https://github.com/ericproulx).
* [#2464](https://github.com/ruby-grape/grape/pull/2464): The `length` validator only takes effect for parameters with types that support `#length` method - [@OuYangJinTing](https://github.com/OuYangJinTing).
* Your contribution here.

#### Fixes
Expand Down
2 changes: 1 addition & 1 deletion lib/grape/validations/validators/length_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def initialize(attrs, options, required, scope, **opts)
def validate_param!(attr_name, params)
param = params[attr_name]

raise ArgumentError, "parameter #{param} does not support #length" unless param.respond_to?(:length)
return unless param.respond_to?(:length)

return unless (!@min.nil? && param.length < @min) || (!@max.nil? && param.length > @max)

Expand Down
16 changes: 16 additions & 0 deletions spec/grape/validations/validators/length_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@
post 'zero_max' do
end

params do
requires :list, type: [Integer], length: { min: 2 }
end
post 'nil_param' do
end

params do
requires :list, type: [Integer], length: { min: 2, message: 'not match' }
end
Expand Down Expand Up @@ -187,6 +193,16 @@
end
end

describe '/nil_param' do
context 'does not raise an error' do
it do
expect do
post '/nil_param', list: nil
end.not_to raise_error
end
end
end

describe '/type_is_not_array' do
context 'raises an error' do
it do
Expand Down

0 comments on commit b7a7701

Please sign in to comment.