Автоматически обрезать строку
Возьмем пример из сухой проверки:
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, я не смогу увидеть, как я могу изменить аргумент.
Я пытаюсь убить муху из дробовика?
1 ответ
Следуя совету создателя сухих типов, мне удалось создать новый тип, который можно использовать:
# 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)