Sha256: 5accc328c4694f37e998b87627d52d374c39ba5e1351e0969e1b4ae8776e0d37

Contents?: true

Size: 1.44 KB

Versions: 2

Compression:

Stored size: 1.44 KB

Contents

module SearchyJson
  class Extracter
    attr_reader :data, :query, :negative_keywords, :positive_keywords, :exact_matches

    def initialize(data, query)
      @data = data
      @query = query
      @negative_keywords = query.negative_keywords
      @positive_keywords = query.positive_keywords
    end

    def call
      query.exact_matches? ? exact_extract : match_extract
    end

    private

    def match_extract
      result = {}

      data.each do |primary_field, keywords|
        negative_diff_size = keywords_diff_size(keywords, :negative)
        next if contain_negative?(negative_diff_size)

        positive_diff_size = keywords_diff_size(keywords, :positive)
        next unless contain_positive?(positive_diff_size)

        result[primary_field] = positive_diff_size
      end

      result.sort_by { |_key, index| index }.map(&:first)
    end

    def exact_extract
      result = []

      data.each do |primary_field, keywords|
        result << primary_field if full_positive_match?(keywords)
      end

      result
    end

    def contain_negative?(negative_diff)
      negative_diff != negative_keywords.count
    end

    def contain_positive?(positive_diff)
      positive_diff != positive_keywords.count
    end

    def full_positive_match?(keywords)
      (keywords & positive_keywords).count == positive_keywords.count
    end

    def keywords_diff_size(keywords, type)
      (send("#{type}_keywords") - keywords).count
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
searchy-json-0.3.1 lib/searchy/extracter.rb
searchy-json-0.3.0 lib/searchy/extracter.rb