2

我想强制表单输入

"1,3,5"

进入:

[1,3,5]

我将dry-typesgem 用于其他强制和约束。我需要知道:

  • 这是否可以通过导轨干式中的任何内置机制实现?

  • 如果不是,我如何使用dry-types为其定义自定义强制?

4

3 回答 3

3

我会考虑两种解决方法:

  • 将具有逗号分隔值的字符串转换为数字数组,然后将其提供给干类型(据我所知,您目前正在做什么)
  • 为这种可转换为数组的字符串定义自定义构造类型,这是一篇关于它的文章
于 2017-07-23T17:48:33.010 回答
3

你可以修补干型

app/config/initializers/dry_type_patch.rb

module Dry
  module Types
    class Array < Definition
      class Member < Array
        alias old_try, try
        def try(input, &block)
          input = input.split(',') if input.is_a?(::String)
          old_try(input, &block)
        end
      end
    end
  end
end
于 2017-07-23T17:57:20.567 回答
1

我使用的是干式验证,它在引擎盖下使用干式。您可以使用自定义类型对输入进行预处理,该类型可以根据需要对其进行转换:

NumberArrayAsString =
  Dry::Types::Definition
  .new(Array)
  .constructor { |input| input.split(',').map { |v| Integer(v) } }

在完整的上下文中,使用干验证:

# frozen_string_literal: true

require 'dry-validation'

NumberArrayAsString =
  Dry::Types::Definition
  .new(Array)
  .constructor { |input| input.split(',').map { |v| Integer(v) } }

ExampleContract = Dry::Validation.Params do
  configure do
    config.type_specs = true
  end

  required(:ids, NumberArrayAsString)
end

puts ExampleContract.call(ids: '1,3,5').inspect
#<Dry::Validation::Result output={:ids=>[1, 3, 5]} errors={}>

这适用于干验证 0.13,但类似的代码应该适用于 1.0。

于 2019-07-08T16:09:40.357 回答