-
-
Notifications
You must be signed in to change notification settings - Fork 62
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Sum operator not working when default values are defined #158
Comments
This is expected, in some way. dry-struct has to have a way to pick the right variant. There are two possible solutions for you
class A < Dry::Struct
attribute :tag, Types::String.constrained(eql: 'a')
attribute :foo_a, Types::String.default("foo_a".freeze)
attribute :foo_b, Types::String.default("foo_b".freeze)
end
class B < Dry::Struct
attribute :tag, Types::String.constrained(eql: 'b')
attribute :bar_a, Types::String.default("bar_a".freeze)
attribute :bar_b, Types::String.default("bar_b".freeze)
end
# then pass the tag to pick the right struct
(A | B).(bar_a: "example", bar_b: "example", tag: 'b')
# => #<B tag="b" bar_a="example" bar_b="example">
class A < Dry::Struct
schema schema.strict
attribute :foo_a, Types::String.default("foo_a".freeze)
attribute :foo_b, Types::String.default("foo_b".freeze)
end
class B < Dry::Struct
schema schema.strict
attribute :bar_a, Types::String.default("bar_a".freeze)
attribute :bar_b, Types::String.default("bar_b".freeze)
end
# now A will reject unexpected keys and dry-struct will try B
(A | B).(bar_a: "example", bar_b: "example")
=> #<B bar_a="example" bar_b="example"> You can always use strict structs by creating a base class: class StrictStruct < Dry::Struct
schema schema.strict
end
class A < StrictStruct
# ...
end
class B < StrictStruct
# ...
end Both ways are OK. |
@flash-gordon is this documented? |
@solnic I don't know what exactly to document, it's not a common issue tbh. Regardless, dry-struct is barely documented |
@flash-gordon IIRC people trip on how sum types work on a regular basis (the fact that you need one variant to fail in order for the other to be used isn't that obvious from the API point of view). I reported #159 about this |
Describe the bug
Given this setup:
And this data:
I would expect:
What I get is:
I would expect the values I pass in to take precedence over the default values and for the sum operator to evaluate the keys and values to choose which struct to use.
To Reproduce
Please see above
Expected behavior
Please see above
Your environment
The text was updated successfully, but these errors were encountered: