Sha256: 89fb236e339e08392da4c5ceca90cb5ebed1463a93996237e84aa4a6e4914ca7

Contents?: true

Size: 1.43 KB

Versions: 1

Compression:

Stored size: 1.43 KB

Contents

module Dry
  module Validation
    class Result
      include Dry::Equalizer(:output, :messages)
      include Enumerable

      attr_reader :output
      attr_reader :errors
      attr_reader :error_compiler
      attr_reader :hint_compiler

      alias_method :to_hash, :output
      alias_method :to_h, :output # for MRI 2.0, remove it when drop support

      EMPTY_MESSAGES = {}.freeze

      def initialize(output, errors, error_compiler, hint_compiler)
        @output = output
        @errors = errors
        @error_compiler = error_compiler
        @hint_compiler = hint_compiler
      end

      def each(&block)
        output.each(&block)
      end

      def [](name)
        output.fetch(name)
      end

      def success?
        errors.empty?
      end

      def failure?
        !success?
      end

      def messages(options = {})
        @messages ||=
          begin
            return EMPTY_MESSAGES if success?

            hints = hint_compiler.with(options).call
            comp = error_compiler.with(options.merge(hints: hints))

            messages = comp.(error_ast)
            msg_hash = comp.dump_messages(messages)

            if msg_hash.key?(nil)
              msg_hash.values.flatten
            else
              msg_hash
            end
          end
      end

      def to_ast
        [:set, error_ast]
      end

      private

      def error_ast
        errors.map { |error| error.to_ast }
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dry-validation-0.8.0 lib/dry/validation/result.rb