我想强制表单输入
"1,3,5"
进入:
[1,3,5]
我将dry-types
gem 用于其他强制和约束。我需要知道:
这是否可以通过导轨或干式中的任何内置机制实现?
如果不是,我如何使用dry-types为其定义自定义强制?
我想强制表单输入
"1,3,5"
进入:
[1,3,5]
我将dry-types
gem 用于其他强制和约束。我需要知道:
这是否可以通过导轨或干式中的任何内置机制实现?
如果不是,我如何使用dry-types为其定义自定义强制?
我会考虑两种解决方法:
你可以修补干型
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
我使用的是干式验证,它在引擎盖下使用干式。您可以使用自定义类型对输入进行预处理,该类型可以根据需要对其进行转换:
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。