Skip to content

Commit

Permalink
validation for array in params
Browse files Browse the repository at this point in the history
  • Loading branch information
flyerhzm committed Feb 12, 2013
1 parent f16d66c commit 4cccf84
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
8 changes: 5 additions & 3 deletions lib/grape/validations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ def initialize(attrs, options, required, scope)
def validate!(params)
params = @scope.params(params)

@attrs.each do |attr_name|
if @required || params.has_key?(attr_name)
validate_param!(attr_name, params)
(params.is_a?(Array) ? params : [params]).each do |resource_params|
@attrs.each do |attr_name|
if @required || resource_params.has_key?(attr_name)
validate_param!(attr_name, resource_params)
end
end
end
end
Expand Down
29 changes: 26 additions & 3 deletions spec/grape/validations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,29 @@ def app; subject end
end
end

context 'group' do
before do
subject.params {
group :items do
requires :key
end
}
subject.get '/required' do 'required works'; end
end

it 'errors when param not present' do
get '/required'
last_response.status.should == 400
last_response.body.should == 'missing parameter: items[key]'
end

it "doesn't throw a missing param when param is present" do
get '/required', { :items => [:key => 'hello', :key => 'world'] }
last_response.status.should == 200
last_response.body.should == 'required works'
end
end

context 'custom validation' do
module CustomValidations
class Customvalidator < Grape::Validations::Validator
Expand Down Expand Up @@ -147,19 +170,19 @@ def validate_param!(attr_name, params)
end
end
end

specify 'the parent namespace uses the validator' do
get '/nested/one', { :custom => 'im wrong, validate me'}
last_response.status.should == 400
last_response.body.should == 'custom: is not custom!'
end

specify 'the nested namesapce inherits the custom validator' do
get '/nested/nested/two', { :custom => 'im wrong, validate me'}
last_response.status.should == 400
last_response.body.should == 'custom: is not custom!'
end

specify 'peer namesapces does not have the validator' do
get '/peer/one', { :custom => 'im not validated' }
last_response.status.should == 200
Expand Down

0 comments on commit 4cccf84

Please sign in to comment.