3

以干验证为例:

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. 如果我反过来,即通过自定义谓词,我不能只返回真或假,我看不到如何更改参数

我想用霰弹枪杀死一只苍蝇吗?

4

1 回答 1

2

按照干类型创建者的提示,我设法创建了一个可以使用的新类型:

# 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)

于 2019-02-13T17:57:49.770 回答