[Dry::Struct] Reusing a set of common attributes

I ended up with the following version:

require ‘dry-struct’

module Types
  include Dry::Types.module
  
  Uuid = Types::String
                  .constructor(&:upcase)
                  .constrained(format: /^[0-9A-F]{8}-[0-9A-F]{4}-[1-5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/)
end

module CommonAttributes
  def self.included(mod)
    mod::attribute :uuid, Types::Uuid
  end
end

class StructA < Dry::Struct::Value
  include CommonAttributes
  attribute :attr_a, Types::String
end

class StructB < Dry::Struct
  include CommonAttributes
  attribute :attr_b, Types::String
end

Cheers!

1 Like