Dry::Types::Struct non-empty string attribute


#1

Hi All,

I was wondering how one could ensure that a Dry::Types::Struct attribute is a non-blank string.

I was able to get this behavior with

class MyClass < Dry::Types::Struct

     attribute :name, Types::Strict::String.constrained( format: /\S/) # contains at least one non-whitespace character
end

However this triggers a very unclear error message & I did not find a way to specify a more specific error string.

 MyClass.new(name: '  ')
  -->  Dry::Types::StructError: [MyClass.new] "  " (String) has invalid type for :name

kind regards
Pieter


#2

This would be the sort of error message to expect for dry-types’ behaviour as it stands right now.

It looks like you’ve got your type set up to do what you like, anyway? If you’d like to open a discussion about improving error messages for struct initialization, I’d encourage you to go ahead and open an issue over at http://github.com/dry-rb/dry-struct/, which is where future development of the structs will be happening :slight_smile:


#3

Yes it’s been on my todo list for a long time - improve type error handling in structs. I’ll get to it at some point. This is one of the reasons why I wanted to extract Struct into dry-struct, since this project needs more code and more attention and shouldn’t be part of dry-types.