@ahacop/

CheapQuarrelsomeApplicationserver

Ruby

No description

fork
loading
Files
  • main.rb
  • Gemfile
  • Gemfile.lock
main.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require "dry-types"
require "dry-schema"
require "dry-validation"
require "test/unit/assertions"

include Test::Unit::Assertions

module Types
  include Dry::Types()

  HashType = Hash.schema({c: Params::Float})

  SumHashParam = Params::Float | HashType
  SumScalarParam = Params::Float | Params::Bool
end

ASchema = Dry::Schema.Params do
  required(:a).filled(Types::SumScalarParam)
end

assert_equal({ a: 1.0 }, ASchema.(a: "1.0").to_h)
assert_equal({ a: true }, ASchema.(a: "true").to_h)

class BValidation < Dry::Validation::Contract
  params do
    required(:b) do
      float? | hash do
        required(:c).filled(:float)
      end
    end
  end
end

assert_equal({ b: 1.0 }, BValidation.new.({ b: 1.0 }).to_h)
assert_equal(
  { b: ["must be a float or must be a hash"] }, 
  BValidation.new.({ b: "1.0" }).errors.to_h # no coercion on scalar
)
assert_equal({ b: { c: 1.0 } }, BValidation.new.({ b: { c: "1.0" } }).to_h)

# the following code raises on evaluation; change conditional to see 
if true
  BSchema = Dry::Schema.Params do
    required(:b).filled(Types::SumHashParam)
  end

  assert_equal({ b: 1.0 }, BSchema.(b: "1.0").to_h)
  assert_equal({ b: { c: 1.0 } }, BSchema.(b: { c: "1.0"}).to_h)
end
ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]