首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自动截断字符串

自动截断字符串
EN

Stack Overflow用户
提问于 2018-12-13 16:22:15
回答 1查看 240关注 0票数 3

以干验证为例:

代码语言:javascript
复制
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,我看不出如何更改参数。

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

EN

回答 1

Stack Overflow用户

发布于 2019-02-13 17:57:49

根据干类型创建者的提示,我创建了一个可以使用的新类型:

代码语言:javascript
复制
# 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)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53766096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档