Skip to content

Commit

Permalink
recursive type_check
Browse files Browse the repository at this point in the history
  • Loading branch information
Braktar committed Aug 26, 2020
1 parent 2fa48f1 commit 1256d3c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
14 changes: 13 additions & 1 deletion lib/grape/validations/types/custom_type_coercer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,25 @@ def infer_type_check(type)
# passed, or if the type also implements a parse() method.
type
elsif type.is_a?(Enumerable)
->(value) { value.respond_to?(:all?) && value.all? { |item| item.is_a? type[0] } }
lambda do |value|
value.is_a?(Enumerable) && value.all? do |val|
recursive_type_check(type.first, val)
end
end
else
# By default, do a simple type check
->(value) { value.is_a? type }
end
end

def recursive_type_check(type, value)
if type.is_a?(Enumerable) && value.is_a?(Enumerable)
value.all? { |val| recursive_type_check(type.first, val) }
else
!type.is_a?(Enumerable) && value.is_a?(type)
end
end

# Enforce symbolized keys for complex types
# by wrapping the coercion method such that
# any Hash objects in the immediate heirarchy
Expand Down
11 changes: 9 additions & 2 deletions spec/grape/validations/validators/coerce_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -631,10 +631,17 @@ def self.parsed?(value)
get '/coerce_nested_strings', values: 'a,b,c,d'
expect(last_response.status).to eq(200)
expect(JSON.parse(last_response.body)).to eq([%w[a b c d]])
expect(last_response.status).to eq(400)

get '/coerce_nested_strings', values: [%w[a c], %w[b]]
expect(last_response.status).to eq(200)
expect(JSON.parse(last_response.body)).to eq([%w[a c], %w[b]])

get '/coerce_nested_strings', values: [%w[a], %w[b]]
get '/coerce_nested_strings', values: [[]]
expect(last_response.status).to eq(200)
expect(JSON.parse(last_response.body)).to eq([%w[a], %w[b]])
expect(JSON.parse(last_response.body)).to eq([[]])

get '/coerce_nested_strings', values: [['a', { bar: 0 }], ['b']]
end

it 'parses parameters with Array[Integer] type' do
Expand Down

0 comments on commit 1256d3c

Please sign in to comment.