dry-rb/dry-logic

View on GitHub
lib/dry/logic/operations/each.rb

Summary

Maintainability
A
0 mins
Test Coverage
# frozen_string_literal: true

require "dry/logic/operations/unary"
require "dry/logic/result"

module Dry
  module Logic
    module Operations
      class Each < Unary
        def type
          :each
        end

        def call(input)
          results = input.map { |element| rule.(element) }
          success = results.all?(&:success?)

          Result.new(success, id) do
            failures = results
              .map
              .with_index { |result, idx| [:key, [idx, result.ast(input[idx])]] if result.failure? }
              .compact

            [:set, failures]
          end
        end

        def [](arr)
          arr.map { |input| rule[input] }.all?
        end
      end
    end
  end
end