From e143710d8af2f53d3b0702e6e20d7958810bfd76 Mon Sep 17 00:00:00 2001 From: Nikita Shilnikov Date: Mon, 6 Jan 2025 20:46:26 +0100 Subject: [PATCH] Add more examples for `maybe(:array)` (close #480) Co-Authored-By: Kenneth Teh <31978393+kennethteh90@users.noreply.github.com> --- docsite/source/nested-data.html.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docsite/source/nested-data.html.md b/docsite/source/nested-data.html.md index 9c0cf1b9..26dbe4ed 100644 --- a/docsite/source/nested-data.html.md +++ b/docsite/source/nested-data.html.md @@ -133,3 +133,33 @@ puts errors.to_h.inspect # } ``` + +Use `maybe(array[?])` to validate an array that could be `nil`: + +```ruby +nested_schema = Dry::Schema.Params do + required(:name).filled(:string) +end + +schema = Dry::Schema.Params do + required(:tags).maybe(array[nested_schema]) +end + +schema.call(tags: nil).success? # true +schema.call(tags: [{ name: 'Alice' }, { name: 'Bob' }]).success? # true +``` + +Or use `maybe(:array)` with a block: + +```ruby +schema = Dry::Schema.Params do + required(:tags).maybe(:array) do + nil? | each(:hash) do + required(:name).filled(:string) + end + end +end + +schema.call(tags: nil).success? # true +schema.call(tags: [{ name: 'Alice' }, { name: 'Bob' }]).success? # true +```