dry-types

v1.8 v1.7
  1. Introduction
  2. Getting Started
  3. Built-in Types
  4. Type Attributes
  5. Default Values
  6. Fallbacks
  7. Constraints
  8. Hash Schemas
  9. Array With Member
  10. Enum
  11. Map
  12. Combining Types
    1. Intersection
    2. Sum
  13. Custom Types
  14. Custom Type Builders
  15. Extensions
    1. Maybe
    2. Monads

TOC


Fallbacks

Fallback value will be returned when invalid input is provided:

type = Dry::Types['integer'].fallback(100)

type.(99) # => 99
type.('99') # => 100
type.(:invalid) # => 100

Block syntax:

cnt = 0
type = Dry::Types['integer'].fallback { cnt += 1 }

type.(99) # => 99
type.('99') # => 1
type.(:invalid) # => 2

Fallbacks are different from default values because the latter are triggered on missing input rather than invalid. They can be combined:

schema = Dry::Types['hash'].schema(
  size: Dry::Types['integer'].fallback(50).default(100)
)
schema.({}) # => { size: 100 }
schema.({ size: 'invalid' }) # => { size: 50 }