简体   繁体   中英

Coercion of comma separated values string into array using dry-types

I wish to coerce the form input

"1,3,5"

into:

[1,3,5]

I am using dry-types gem for other coercions and constraints. I need to know:

  • Is this possible via any built-in mechanism in rails or dry-types ?

  • If not, how do I define a custom coercion for it using dry-types ?

I'd consider two ways of solving this:

  • converting a string with comma-separated values into an array of numbers and then feed it to dry-types (what as far as I understand you're currently doing)
  • Define a custom construction type for such a string which is convertable to an array here's an article about it

You can patch 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

I was using dry-validation, which uses dry-types under the hood. You can pre-process the input using a custom type that transforms it as you'd like:

NumberArrayAsString =
  Dry::Types::Definition
  .new(Array)
  .constructor { |input| input.split(',').map { |v| Integer(v) } }

In complete context, using dry-validation:

# 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={}>

This works with dry-validation 0.13, but similar code should work for 1.0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM