Sha256: e1a9562341e8810be5aa981ef2c7c49c0dafa67f266164bfd5763ee9bb3dae4c

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

require 'set'
require_relative 'value_rule'
require_relative 'name_rule'

module Leftovers
  class HashRule
    def initialize(patterns) # rubocop:disable Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
      keys = []
      pairs = []
      Array.each_or_self(patterns) do |pat|
        if pat.is_a?(Hash) && pat[:value]
          pairs << [
            (NameRule.new(pat[:keyword]) if pat[:keyword]),
            (ValueRule.new(pat[:value]) if pat[:value])
          ]
        else
          keys << NameRule.new(pat)
        end
      end

      @keys = (NameRule.new(keys) if keys)

      @pairs = (pairs unless pairs.empty?)

      freeze
    end

    def match_pair?(key_node, value_node)
      return true if @keys&.match?(key_node.to_sym, key_node.to_s)

      @pairs&.any? do |(key_rule, value_rule)|
        next unless !key_rule || key_rule.match?(key_node.to_sym, key_node.to_s)

        (!value_rule || value_rule.match?(value_node))
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
leftovers-0.1.0 lib/leftovers/hash_rule.rb