【问题标题】:Missing Module when using DryValidations to validate query params使用 DryValidations 验证查询参数时缺少模块
【发布时间】:2018-10-29 13:46:17
【问题描述】:

我有一个 jsonapi 端点,我在其中获取查询参数“include”,其中包含由“,”分隔的多个对象
现在,我使用 Dry::Validations 验证我的参数,并希望对这个字段进行预处理,以便获得一个字符串数组。 为了实现这一点,我根据文档制作了这个:

module CustomTypes
  include Dry::Types.module

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

现在,当我运行测试时,我得到了这个错误:

失败/错误: IncludeRelatedObject = Types::String.constructor do |itm| itm.split(',')&.map :chomp 结束

名称错误: 未初始化的常量 CustomTypes::Types

这是我的验证:

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

你知道我的代码有什么问题吗?

【问题讨论】:

    标签: ruby-on-rails ruby dry-rb


    【解决方案1】:

    include Dry::Types.module 基本上将常量变形到它所包含的模块中。您得到了 CustomTypes::String 等,这是您的自定义类型中应该引用的内容:

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

    【讨论】:

      【解决方案2】:

      要为验证定义自定义类型,您应该使用 Types 模块。所以你应该把模块名从CustomTypes改成Types

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-02
        • 2015-12-05
        • 2019-03-29
        相关资源
        最近更新 更多