dry-rb / dry-types

Flexible type system for Ruby with coercions and constraints
https://dry-rb.org/gems/dry-types
MIT License
859 stars 134 forks source link

A bug with array, struct and sum of structs in `try` method #462

Open pyromaniac opened 1 year ago

pyromaniac commented 1 year ago

Describe the bug

Hi there, I found a couple of bugs working with structs and types in try method

To Reproduce

struct = Dry::Struct(id: Types::Integer)
type = Types::Array.of(struct)
# => #<Dry::Types[Constrained<Array<#<Class:0x0000000114d33398>> rule=[type?(Array)]>]>
type.try([{}])
# ArgumentError: error must be a CoercionError
# from /Users/pyromaniac/.rvm/gems/ruby-3.1.4@bookingsync/gems/dry-types-1.7.1/lib/dry/types/nominal.rb:122:in `failure'
# type.try([{id: 1}])
# => #<Dry::Types::Result::Success input=[#<#<Class:0x0000000114d33398> id=1>]>
type.try([struct.new(id: 1)])
# => #<Dry::Types::Result::Success input=[#<#<Class:0x0000000114d33398> id=1>]>
struct2 = Dry::Struct(id2: Types::Integer)
# => #<Class:0x0000000114f90c58>
type = Types::Array.of(struct | struct2)

# Btw, the inspection is also weird here
# => #<Dry::Types::Constrained:0x163b4>
type.try([{}])
# ArgumentError: error must be a CoercionError
# from /Users/pyromaniac/.rvm/gems/ruby-3.1.4@bookingsync/gems/dry-types-1.7.1/lib/dry/types/nominal.rb:122:in `failure'
type.try([{id: 1}])
# => #<Dry::Types::Result::Success input=[#<#<Class:0x0000000114d33398> id=1>]>
type.try([struct.new(id: 1)])
# NoMethodError: undefined method `input' for #<#<Class:0x0000000114d33398> id=1>
#
#               output << r.input unless Undefined.equal?(r.input)
#                                                         ^^^^^^
# from .rvm/gems/ruby-3.1.4/gems/dry-types-1.7.1/lib/dry/types/array/member.rb:79:in `block in try'

Expected behavior

No errors are expected for those 2 cases.

My environment