How to use array of user defined objects in dry-struct


#1

Hi,
I am trying to switch from virtus to dry-struct on a project but I have trouble finding how to use array of custom types, can someone point me in the right direction ?

require ‘dry-types’
require ‘dry-struct’

module Types
include Dry::Types.module
end

class User < Dry::Struct
attribute :name, Types::String
attribute :tags, Types::Array[Types::String]
end

class Group < Dry::Struct
attribute :users, Types::Array[User]
end

u1 = User.new(name: “John”, tags: [‘one’, ‘tw’])
u2 = User.new(name: “Alice”, tags: [‘one’])

g = Group.new(users: [u1, u2])
p g

This fails when trying to create the group with this error:
(Array) has invalid type for :users violates constraints (can’t convert Array into Hash failed) (Dry::Struct::Error)


#2

Does attribute :users, Types::Strict::Array.of(User) work?


#3

Thanks, it works :slight_smile: