Skip to content

Commit

Permalink
Merge pull request #148 from dry-rb/140-fix-predicate-inference-from-…
Browse files Browse the repository at this point in the history
…array-with-member

Fix predicate inference for array with a member
  • Loading branch information
solnic authored May 30, 2019
2 parents d5c5209 + c10a3b6 commit 03e1a11
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/dry/schema/macros/key.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def filter(*args, &block)
# @api public
def value(*args, **opts, &block)
extract_type_spec(*args) do |*predicates, type_spec:|
super(*predicates, **opts, &block)
super(*predicates, type_spec: type_spec, **opts, &block)
end
end

Expand Down
3 changes: 3 additions & 0 deletions lib/dry/schema/macros/value.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ def call(*predicates, **opts, &block)
raise ArgumentError, 'wrong number of arguments (given 0, expected at least 1)'
end

type_spec = opts[:type_spec]
each(type_spec.type.member) if type_spec.respond_to?(:member)

self
end

Expand Down
18 changes: 17 additions & 1 deletion spec/integration/schema/type_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,31 @@
end

context 'single type spec with an array' do
subject(:schema) do
Dry::Schema.Params do
required(:nums).value(:array)
end
end

it 'infers array? check' do
expect(schema.(nums: nil).errors.to_h).to eql(nums: ['must be an array'])
end
end

context 'single type spec with an array with a member' do
subject(:schema) do
Dry::Schema.Params do
required(:nums).value(array[:integer])
end
end

it 'uses form coercion' do
it 'uses params coercion' do
expect(schema.(nums: %w(1 2 3)).to_h).to eql(nums: [1, 2, 3])
end

it 'infers array? + each(:integer?)' do
expect(schema.(nums: %w(1 oops 3)).errors.to_h).to eql(nums: { 1 => ['must be an integer'] })
end
end

context 'sum type spec without rules' do
Expand Down
8 changes: 8 additions & 0 deletions spec/unit/dry/schema/predicate_inferrer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ def type(*args)
expect(inferrer[type(:string)]).to be(inferrer[type(:string)])
end

it 'returns array? for an array type' do
expect(inferrer[type(:array)]).to eql([:array?])
end

it 'returns array? for an array type with member' do
expect(inferrer[type(:array).of(type(:integer))]).to eql([:array?])
end

it 'returns str? for a string type' do
expect(inferrer[type(:string)]).to eql([:str?])
end
Expand Down

0 comments on commit 03e1a11

Please sign in to comment.