Sha256: b007c66f41b9d96256debcb78d946565068eb3b6606ff6fb4fa19786185791e8

Contents?: true

Size: 1.91 KB

Versions: 14

Compression:

Stored size: 1.91 KB

Contents

# frozen_string_literal: true

require "dry/core/equalizer"
require "dry/logic/operators"

module Dry
  module Schema
    # Predicate objects used within the DSL
    #
    # @api public
    class Predicate
      # A negated predicate
      #
      # @api private
      class Negation
        include Dry::Logic::Operators

        # @api private
        attr_reader :predicate

        # @api private
        def initialize(predicate)
          @predicate = predicate
        end

        # Dump negated predicate to an AST
        #
        # @return [Array]
        #
        # @api private
        def to_ast(...)
          [:not, predicate.to_ast(...)]
        end
        alias_method :ast, :to_ast
      end

      include Dry::Logic::Operators
      include Dry::Equalizer(:name, :args, :block)

      # @api private
      attr_reader :compiler

      # @api private
      attr_reader :name

      # @api private
      attr_reader :args

      # @api private
      attr_reader :block

      # @api private
      def initialize(compiler, name, args, block)
        @compiler = compiler
        @name = name
        @args = args
        @block = block
      end

      # Negate a predicate
      #
      # @example
      #   required(:name).value(:string) { !empty? }
      #
      # @return [Negation]
      #
      # @api public
      def !
        Negation.new(self)
      end

      # @api private
      def ensure_valid
        if compiler.predicates[name].arity - 1 != args.size
          raise ArgumentError, "#{name} predicate arity is invalid"
        end
      end

      # Compile predicate to a rule object
      #
      # @api private
      def to_rule
        compiler.visit(to_ast)
      end

      # Dump predicate to an AST
      #
      # @return [Array]
      #
      # @api private
      def to_ast(*)
        [:predicate, [name, compiler.predicates.arg_list(name, *args)]]
      end
      alias_method :ast, :to_ast
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
dry-schema-1.12.0 lib/dry/schema/predicate.rb
dry-schema-1.11.3 lib/dry/schema/predicate.rb
dry-schema-1.11.2 lib/dry/schema/predicate.rb
dry-schema-1.11.1 lib/dry/schema/predicate.rb
dry-schema-1.11.0 lib/dry/schema/predicate.rb
dry-schema-1.10.6 lib/dry/schema/predicate.rb
dry-schema-1.10.5 lib/dry/schema/predicate.rb
dry-schema-1.10.4 lib/dry/schema/predicate.rb
dry-schema-1.10.2 lib/dry/schema/predicate.rb
dry-schema-1.10.1 lib/dry/schema/predicate.rb
dry-schema-1.9.3 lib/dry/schema/predicate.rb
dry-schema-1.9.2 lib/dry/schema/predicate.rb
dry-schema-1.9.1 lib/dry/schema/predicate.rb
dry-schema-1.9.0 lib/dry/schema/predicate.rb