File: evaluator.rb

package info (click to toggle)
ruby-dry-logic 1.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 728 kB
  • sloc: ruby: 4,929; makefile: 6
file content (50 lines) | stat: -rw-r--r-- 987 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# frozen_string_literal: true

require "dry/core/equalizer"

module Dry
  module Logic
    class Evaluator
      include Dry::Equalizer(:path)

      attr_reader :path

      class Set
        include Dry::Equalizer(:evaluators)

        attr_reader :evaluators

        def self.new(paths)
          super(paths.map { |path| Evaluator::Key.new(path) })
        end

        def initialize(evaluators)
          @evaluators = evaluators
        end

        def call(input)
          evaluators.map { |evaluator| evaluator[input] }
        end
        alias_method :[], :call
      end

      class Key < Evaluator
        def call(input)
          path.reduce(input) { |a, e| a[e] }
        end
        alias_method :[], :call
      end

      class Attr < Evaluator
        def call(input)
          path.reduce(input) { |a, e| a.public_send(e) }
        end
        alias_method :[], :call
      end

      def initialize(path)
        @path = Array(path)
      end
    end
  end
end