[Dry-struct] .meta(omittable: true) vs. .optional.default(nil)

I would like to ask for clarification about optional attributes in structs. What is the difference between

.meta(omittable: true)

and

.optional.default(nil) ?

Which is recommended in which situation? Are they different concepts or do they solve the same (or similar) problem? Or does one API supersede the other, possibly?

These are different things. One describes a possibly missing key and makes sense only in the context of a hash or a struct. The second one is about values that can be nil. You won’t see a difference when access an attribute with struct.attribute_name but missing keys won’t appear in the .attributes and .to_h output, have a look:

 :001 > Dry.Struct(name: 'string', age?: 'integer').new(name: 'John').to_h
 => {:name=>"John"} 
 :002 > Dry.Struct(name: 'string', age: Types::Integer.optional.default(nil)).new(name: 'John').to_h
 => {:name=>"John", :age=>nil} 

FYI age? is a shortcut for omittable: true aka required: false

1 Like

I try to summarize again to confirm.

Optional is a type definition detail. The type will allow both any of it’s values, but nil in addition.

Not required (aka. omittable) is a struct (schema?) definition detail. It makes it ‘optional’ (in common parlance, but I see how saying that might be confusing because of how this library names things).

I think I got it. Thanks for your answer.