Sha256: 33a3a0c30f096c79c02eb329c0ae566d4c0895c5cba00e427c0b7d3edef86789

Contents?: true

Size: 1.06 KB

Versions: 2

Compression:

Stored size: 1.06 KB

Contents

module BloodContracts
  module Contracts
    class Validator
      extend Dry::Initializer

      param :contract_hash, ->(v) { Hashie::Mash.new(v) }

      def valid?(statistics)
        return if statistics.found_unexpected_behavior?

        last_run_stats = statistics.to_h
        expectations.all? do |rule, check|
          percent = last_run_stats[rule.name]&.percent || 0.0
          check.call(percent, rule)
        end
      end

      private

      def expectations
        Hash[
          contract_hash.map do |name, rule|
            if rule.threshold
              [rule.merge(name: name), method(:threshold_check)]
            elsif rule.limit
              [rule.merge(name: name), method(:limit_check)]
            else
              [rule.merge(name: name), method(:anyway)]
            end
          end.compact
        ]
      end

      def threshold_check(value, rule)
        value > rule.threshold
      end

      def limit_check(value, rule)
        value <= rule.limit
      end

      def anyway(_value, _rule)
        true
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
blood_contracts-0.2.1 lib/blood_contracts/contracts/validator.rb
blood_contracts-0.2.0 lib/blood_contracts/contracts/validator.rb