ruby-on-railsrubydry-rb

Missing Module when using DryValidations to validate query params


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?


Solution

  • 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