Required and optional fields


#1

Hi,

I’m trying to deal with optional and required field in my domain entity.
I have an Article with an required field ‘title’ and an optional field ‘title2’

class Article < Dry::Struct
  constructor_type(:schema)

  attribute :title, Types::Strict::String
  attribute :title2, Types::String.optional
end

I want those behaviors :

Article.new                                    # this should fail (miss title)
Article.new(title: 'ok')                     # should be success
Article.new(title: 'ok', title2: 'ok')    # should be success 

I tried multiple constructor_type, but I cannot found the right one.

Did I miss something ?


#2

Ok, I found the answer, maybe I could post this to stackoverflow, maybe useful for someone.

class Article < Dry::Struct
  constructor_type(:strict_with_defaults)

  attribute :title,  Types::Strict::String
  attribute :title2, Types::String.optional.default('')
end

Bye!