dry-struct icon indicating copy to clipboard operation
dry-struct copied to clipboard

Missing attribute and maybe type

Open DawidJanczak opened this issue 4 years ago • 4 comments

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

  • Affects my production application: YES
  • Ruby version: 2.7
  • OS: Linux hp 5.10.11-arch1-1 #1 SMP PREEMPT Wed, 27 Jan 2021 13:53:16 +0000 x86_64 GNU/Linux

DawidJanczak avatar Feb 09 '21 05:02 DawidJanczak

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.

flash-gordon avatar Feb 09 '21 08:02 flash-gordon

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

DawidJanczak avatar Feb 09 '21 09:02 DawidJanczak

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

flash-gordon avatar Feb 09 '21 17:02 flash-gordon

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

solnic avatar Feb 10 '21 05:02 solnic