dry-rb / dry-struct

Typed struct and value objects
https://dry-rb.org/gems/dry-struct
MIT License
412 stars 62 forks source link

Missing attribute and maybe type #166

Open DawidJanczak opened 3 years ago

DawidJanczak commented 3 years ago

Describe the bug

When I have a field that’s required, but its value is a maybe (attribute :missing, Types::String.maybefor example) not passing that field does not fail when I create an object with that attribute missing, but it does fail later. In our case it fails when we callas_json` on the resulting struct, but the error itself seems to be coming from dry-types so I suspect this isn’t the only scenario when this would fail.

To Reproduce

Reproducible script can be found under https://github.com/DawidJanczak/dry-struct-maybe-attribute-oddity/blob/master/test.rb

Expected behavior

Either instantiating a struct should fail earlier (this would be a potentially breaking change) or as_json should work as expected.

My environment

flash-gordon commented 3 years ago

I'm not sure I follow, dry-struct doesn't define as_json, why should it care? Serializing to JSON is not part of the gem and I'm against mixing concerns in general.

DawidJanczak commented 3 years ago

Apologies @flash-gordon, I should have explained a bit more. It's not really about to_json per se - that just highlights the bug. The main problem here is that the struct is not failing on missing key where I believe it should. I had a brief discussion with @solnic about it here https://discourse.dry-rb.org/t/dry-struct-missing-attribute-and-maybe-type/1198

flash-gordon commented 3 years ago

Thanks, I'll look into that. My gut feeling tells me such a change would break a lot of code.

solnic commented 3 years ago

@flash-gordon do you know why this happens though? Was it on purpose?