以干验证为例:
require "dry-validation"
module Types
include Dry::Types.module
Name = Types::String.constructor do |str|
str ? str.strip.chomp : str
end
end
SignUpForm = Dry::Validation.Params do
configure do
config.type_specs = true
end
required(:code, Types::StrictString).filled(max_size?: 4)
required(:name, Types::Name).filled(min_size?: 1)
required(:password, :string).filled(min_size?: 6)
end
result = SignUpForm.call(
"name" => "\t François \n",
"code" => "francois",
"password" => "some password")
result.success?
# true
# This is what I WANT
result[:code]
# "fran"我想创建一个新的类型,StrictString,它将使用谓词信息,比如max_size并截断它。
问题是:我无法访问Types::String.constructor中的谓词。如果我走相反的路,即通过自定义谓词,我不能只返回true或false,我看不出如何更改参数。
我想用猎枪杀死一只苍蝇吗?
发布于 2019-02-13 17:57:49
根据干类型创建者的提示,我创建了一个可以使用的新类型:
# frozen_string_literal: true
require 'dry-types'
module Types
include Dry::Types.module
# rubocop:disable Naming/MethodName
def self.TruncatedString(size)
Types::String.constructor { |s| s[0..size - 1] unless s.nil? }.constrained(max_size: size)
end
# rubocop:enable Naming/MethodName
end所以现在我可以用:
attribute :company_name, Types::TruncatedString(100)
而不是:
attribute :company_name, Types::String.constrained(max_size: 100)
https://stackoverflow.com/questions/53766096
复制相似问题