These are chat archives for dry-rb/chat

5th
Dec 2016
Ralf Schmitz Bongiolo
@mrbongiolo
Dec 05 2016 21:41
Is there a way to coerce array values with dry-validation?
Tim Riley
@timriley
Dec 05 2016 21:41
@mrbongiolo what sort of thing would you like to achieve?
Ralf Schmitz Bongiolo
@mrbongiolo
Dec 05 2016 21:43
@timriley Actually I have a form that sends IDs, but as string, I would like to coerce them to Integer, something like:
optional(:my_ids, [:nil, :array]).each([:nil, :int], :int?)
Tim Riley
@timriley
Dec 05 2016 21:44
OK cool. And is this a Dry::Validation.Form schema?
Fran Worley
@fran-worley
Dec 05 2016 21:45
@mrbongiolo I use Types::Form::Array.member(Types::Form::Int) works perfectly in my Reform form to do exactly as you describe
Ralf Schmitz Bongiolo
@mrbongiolo
Dec 05 2016 21:46
Thanks @fran-worley I'll try this out :)
It worked like a charm!!! Thanks for the help, I had forgotten about the member key on Dry::Types
Tim Riley
@timriley
Dec 05 2016 21:49
Can we see your final result, @mrbongiolo? :)
Thanks @fran-worley :)
Ralf Schmitz Bongiolo
@mrbongiolo
Dec 05 2016 21:50
Sure @timriley, here it is:
# first I defined my custom Dry Type
module MyApp
  module Types
    include Dry::Types.module
    ArrayOfInts = Types::Form::Array.member(Types::Form::Int)
  end
end

# Then I use it on my Schema
optional(:my_ids, [:nil, MyApp::Types::ArrayOfInts]).each(:int?)
Tim Riley
@timriley
Dec 05 2016 21:51
right, very nice :)
Ralf Schmitz Bongiolo
@mrbongiolo
Dec 05 2016 21:56
Is there an easy way to say that the schema should be valid only if one specific key is given and none of the others, or only some of the others? Or I would need to list all the other keys on a custom rule?
Tim Riley
@timriley
Dec 05 2016 21:57
just on the schema still, another way could be like this:
optional(:my_ids, [:nil, :array]).each([:nil, Types::Form::Int], :int?)
or something like that, using dry-types’ coercing form types
if you wanted to avoid creating an “ArrayOfInts” type just for this purpose
That’s why I was asking whether it was .Form schema, I was wondering if/how that worked with the new type specs
Ralf Schmitz Bongiolo
@mrbongiolo
Dec 05 2016 22:27
@timriley so each accept a type as first argument?
I'm using Dry::Validation.Form with type_spec = true on the configs
I've tried your suggestions, but then I get this error: +nil+ is not a valid predicate name
Tim Riley
@timriley
Dec 05 2016 22:50
ah, I probably got it wrong, sorry
Tim Riley
@timriley
Dec 05 2016 22:58
It’s an interesting question though, the intersection of type specs and each