Add docs for fallbacks and custom builders

This commit is contained in:
Nikita Shilnikov 2021-01-21 21:32:55 +03:00
parent aa9a2e1d11
commit d628ec2f8b
No known key found for this signature in database
GPG Key ID: E569D1D64C40E241
3 changed files with 62 additions and 0 deletions

View File

@ -0,0 +1,24 @@
---
title: Custom Type Builders
layout: gem-single
name: dry-types
---
It is idiomatic to construct new types based on existing.
```ruby
source_type = Dry::Types['integer']
constructor_type = source_type.constructor(Kernel.method(:Integer))
consrained_type = constructor_type.constrained(gteq: 18)
```
This API can be extended with `Dry::Types.define_builder`
```ruby
Dry::Types.define_builder(:or) { |type, value| type.fallback(value) }
source_type = Dry::Types['integer']
type = source_type.or(0)
type.(10) # => 10
type.(:invalid) # => 0
```

View File

@ -0,0 +1,36 @@
---
title: Fallbacks
layout: gem-single
name: dry-types
---
Fallback value will be returned when invalid input is provided:
```ruby
type = Dry::Types['integer'].fallback(100)
type.(99) # => 99
type.('99') # => 100
type.(:invalid) # => 100
```
Block syntax:
```ruby
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:
```ruby
schema = Dry::Types['hash'].schema(
size: Dry::Types['integer'].fallback(50).default(100)
)
schema.({}) # => { size: 100 }
schema.({ size: 'invalid' }) # => { size: 50 }
```

View File

@ -8,6 +8,7 @@ sections:
- built-in-types
- optional-values
- default-values
- fallbacks
- sum
- constraints
- hash-schemas
@ -15,6 +16,7 @@ sections:
- enum
- map
- custom-types
- custom-type-builders
- extensions
---