Dry::Struct default from another attribute using a lambda

Hey guys,

I wanted to be able to define a struct with an attribute that defaults on the value of another attribute within the same struct:

class Foo < Dry::Struct
  attribute :requested_by_id, Types::String
  attribute :executed_by_id, Types::String.optional.default(->(foo) { foo.requested_by_id }) 
end 

Though default does not seem to accept a block.
Any idea how to achieve this?

This won’t be supported. You can achieve something similar by simply defining a method:

def executed_by_id
  @executed_by_id || requested_by_id
end

Alternatively, you can override .new and set the default value there.

2 Likes