Sha256: 56df1b0fb447a17a7a4a67f8f51914c24944fb2c2b718391012ab966045e9706

Contents?: true

Size: 1.43 KB

Versions: 4

Compression:

Stored size: 1.43 KB

Contents

# frozen_string_literal: true

require "dry/schema/processor"
require "dry/schema/macros/dsl"
require "dry/schema/constants"

module Dry
  module Schema
    module Macros
      # Base macro for specifying rules applied to a value found under a key
      #
      # @api public
      class Key < DSL
        # @!attribute [r] filter_schema_dsl
        #   @return [Schema::DSL]
        #   @api private
        option :filter_schema_dsl, default: proc { schema_dsl&.filter_schema_dsl }

        # Specify predicates that should be applied before coercion
        #
        # @example check format before coercing to a date
        #   required(:publish_date).filter(format?: /\d{4}-\d{2}-\d{2}).value(:date)
        #
        # @see Macros::Key#value
        #
        # @return [Macros::Key]
        #
        # @api public
        def filter(...)
          (filter_schema_dsl[name] || filter_schema_dsl.optional(name)).value(...)
          self
        end
        ruby2_keywords(:filter) if respond_to?(:ruby2_keywords, true)

        # Coerce macro to a rule
        #
        # @return [Dry::Logic::Rule]
        #
        # @api private
        def to_rule
          if trace.captures.empty?
            super
          else
            [super, trace.to_rule(name)].reduce(operation)
          end
        end

        # @api private
        def to_ast
          [:predicate, [:key?, [[:name, name], [:input, Undefined]]]]
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
dry-schema-1.10.6 lib/dry/schema/macros/key.rb
dry-schema-1.10.5 lib/dry/schema/macros/key.rb
dry-schema-1.10.4 lib/dry/schema/macros/key.rb
dry-schema-1.10.3 lib/dry/schema/macros/key.rb