Class: Dry::Schema::Macros::Key

Inherits:
DSL
  • Object
show all
Defined in:
lib/dry/schema/macros/key.rb

Overview

Base macro for specifying rules applied to a value found under a key

Direct Known Subclasses

Optional, Required

Instance Attribute Summary collapse

Attributes inherited from DSL

#chain, #predicate_inferrer, #primitive_inferrer

Instance Method Summary collapse

Methods inherited from DSL

#array, #custom_type?, #each, #filled, #hash, #schema, #type, #value

Methods inherited from Core

#new, #operation, #path

Instance Attribute Details

#filter_schema_dslSchema::DSL (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:



17
# File 'lib/dry/schema/macros/key.rb', line 17

option :filter_schema_dsl, default: proc { schema_dsl&.filter_schema_dsl }

Instance Method Details

#filterMacros::Key

Specify predicates that should be applied before coercion

Examples:

check format before coercing to a date

required(:publish_date).filter(format?: /\d{4}-\d{2}-\d{2}).value(:date)

Returns:

See Also:

  • Macros::Key#value


29
30
31
32
# File 'lib/dry/schema/macros/key.rb', line 29

def filter(...)
  (filter_schema_dsl[name] || filter_schema_dsl.optional(name)).value(...)
  self
end

#maybe(*args, **opts, &block) ⇒ Macros::Key

Set type specification and predicates for a maybe value

Examples:

required(:name).maybe(:string)

Returns:

See Also:

  • Macros::Key#value


45
46
47
48
49
50
51
# File 'lib/dry/schema/macros/key.rb', line 45

def maybe(*args, **opts, &block)
  extract_type_spec(args, nullable: true) do |*predicates, type_spec:, type_rule:|
    append_macro(Macros::Maybe) do |macro|
      macro.call(*predicates, type_spec: type_spec, type_rule: type_rule, **opts, &block)
    end
  end
end

#to_astObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



67
68
69
# File 'lib/dry/schema/macros/key.rb', line 67

def to_ast
  [:predicate, [:key?, [[:name, name], [:input, Undefined]]]]
end

#to_ruleDry::Logic::Rule

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Coerce macro to a rule

Returns:

  • (Dry::Logic::Rule)


58
59
60
61
62
63
64
# File 'lib/dry/schema/macros/key.rb', line 58

def to_rule
  if trace.captures.empty?
    super
  else
    [super, trace.to_rule(name)].reduce(operation)
  end
end