Missing Module when using DryValidations to validate query params

91 Views Asked by At

I have a jsonapi endpoint where I get the query parameter "include" with several objects seperated by a ","
Now, I validate my params with Dry::Validations and would like to preproccess this field so that I get an array of strings. To achive this I made this according to the docu:

module CustomTypes
  include Dry::Types.module

  IncludeRelatedObject = Types::String.constructor do |itm|
    itm.split(',')&.map :chomp
  end
end

Now, when I run my tests I get this error:

Failure/Error: IncludeRelatedObject = Types::String.constructor do |itm| itm.split(',')&.map :chomp end

NameError: uninitialized constant CustomTypes::Types

And this is my validation:

Dry::Validation.Params do
  configure do
    config.type_specs = true
  end
  optional(:include, CustomTypes::IncludeRelatedObject).each { :filled? & :str? }
end

Any ideas what's wrong with my code?

2

There are 2 best solutions below

0
On BEST ANSWER

include Dry::Types.module basically inflects constants into the module it’s being included into. You got CustomTypes::String amongst others and this is what should be referenced in your custom type:

module CustomTypes
  include Dry::Types.module

  # IncludeRelatedObject = Types::String.constructor do |itm|
  IncludeRelatedObject = CustomTypes::String.constructor do |itm|
    itm.split(',').map(&:chomp)
  end
end
0
On

To define a custom type for validations you should use a Types module. So you should change the module name from CustomTypes to Types.

module Types
  include Dry::Types.module

  IncludeRelatedObject = Types::String.constructor do |itm|
    itm.split(',')&.map :chomp
  end
end