Sha256: 93ce8e6f85aee63219c6314ff4d55f62b871634e99a028bc36b48018568add90

Contents?: true

Size: 1.37 KB

Versions: 3

Compression:

Stored size: 1.37 KB

Contents

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.merge(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 = nil)
          if input
            [type, [path, rule.ast(evaluator[input])]]
          else
            [type, [path, rule.ast]]
          end
        end

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
dry-logic-0.4.2 lib/dry/logic/operations/key.rb
dry-logic-0.4.1 lib/dry/logic/operations/key.rb
dry-logic-0.4.0 lib/dry/logic/operations/key.rb