dry-schema

v1.14
  1. Introduction
  2. Basics
    1. Built-in predicates
    2. Macros
    3. Type specs
    4. Working with schemas
  3. Optional keys and values
  4. Nested data
  5. Reusing schemas
  6. Params
  7. JSON
  8. Error messages
  9. Advanced
    1. Composing schemas
    2. Custom predicates
    3. Custom types
    4. Filtering
    5. Key maps
    6. Predicate logic
    7. Processor steps
    8. Rule AST
    9. Unexpected keys
  10. Extensions
    1. Hints
    2. Info
    3. JSON Schema
    4. Monads

TOC

  1. Accessing key map
  2. KeyMap is an enumerable
  3. Learn more

Key maps

When you define a schema, you get access to the key map which holds information about specified keys. Internally, dry-schema uses key maps to:

Accessing key map

To access schema's key map use Schema#key_map method:

schema = Dry::Schema.Params do
  required(:email).filled(:string)
  optional(:age).filled(:integer, gt?: 18)
end

schema.key_map
# => #<Dry::Schema::KeyMap["email", "age"]>

schema.key_map.write("email" => "jane@doe.org", "age" => 21, "something_unexpected" => "oops")
# => {:email=>"jane@doe.org", :age=>21}

KeyMap is an enumerable

You can use Enumerable API when working with key maps:

schema.key_map.each { |key| puts key.inspect }
# #<Dry::Schema::Key name="email" coercer=#<Proc:0x00007feb288ff848(&:to_sym)>>
# #<Dry::Schema::Key name="age" coercer=#<Proc:0x00007feb288ff848(&:to_sym)>>

schema.key_map.detect { |key| key.name.eql?("email") }
# => #<Dry::Schema::Key name="email" coercer=#<Proc:0x00007feb288ff848(&:to_sym)>>

Learn more