Sha256: 3d1074905f58235990f5db862d3847537034d41d3d429cc664def5b71dde369d

Contents?: true

Size: 1.44 KB

Versions: 6

Compression:

Stored size: 1.44 KB

Contents

# frozen_string_literal: true

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

module Dry
  module Logic
    module Operations
      class Key < Unary
        attr_reader :evaluator

        attr_reader :path

        def self.new(rules, **options)
          if options[:evaluator]
            super
          else
            name = options.fetch(:name)
            eval = options.fetch(:evaluator, evaluator(name))
            super(rules, **options, evaluator: eval, path: name)
          end
        end

        def self.evaluator(name)
          Evaluator::Key.new(name)
        end

        def initialize(*rules, **options)
          super
          @evaluator = options[:evaluator]
          @path = options[:path]
        end

        def type
          :key
        end

        def call(hash)
          input = evaluator[hash]
          result = rule.(input)

          if result.success?
            Result::SUCCESS
          else
            Result.new(false, path) { [type, [path, result.to_ast]] }
          end
        end

        def [](hash)
          rule[evaluator[hash]]
        end

        def ast(input = Undefined)
          if input.equal?(Undefined) || !input.is_a?(Hash)
            [type, [path, rule.ast]]
          else
            [type, [path, rule.ast(evaluator[input])]]
          end
        end

        def to_s
          "#{type}[#{path}](#{rule})"
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 2 rubygems

Version Path
dry-logic-1.2.0 lib/dry/logic/operations/key.rb
dry-logic-1.1.1 lib/dry/logic/operations/key.rb
dry-logic-1.1.0 lib/dry/logic/operations/key.rb
dry-logic-1.0.8 lib/dry/logic/operations/key.rb
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/dry-logic-1.0.7/lib/dry/logic/operations/key.rb
dry-logic-1.0.7 lib/dry/logic/operations/key.rb