Sha256: 6a15fe5581e030071f1bd3c66c7a2008f1b20285c53c4f3f5c4d0196d46a3867

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

require 'pry'

module QueryDam
  module Trackable
    extend ActiveSupport::Concern

    included do
      before_save :get_prior_results
      before_destroy :get_prior_results
      after_commit :update_queries
    end

    def get_prior_results
      @_prior_results = {}

      queries.each do |key, query_hash|
        query = query_hash[:query]

        @_prior_results[key] =
          self.class.connection.select_values(query).map(&:to_i)
      end
    end

    def update_queries
      queries.each do |key, query_hash|
        query = query_hash[:query]
        result = self.class.connection.select_values(query).map(&:to_i)
        added = result - @_prior_results[key]
        removed = @_prior_results[key] - result

        if result.include?(id)
          QueryDam.updates_set(key) << id
        end

        additions_set = QueryDam.additions_set(key)
        updates_set = QueryDam.updates_set(key)
        removals_set = QueryDam.removals_set(key)

        if result.include?(id)
          updates_set.add(id)
        end

        added.each do |record_id|
          if removals_set.member?(record_id)
            removals_set.delete(record_id)
          else
            additions_set.add(record_id)
          end
        end

        removed.each do |record_id|
          updates_set.delete(record_id)

          if additions_set.member?(record_id)
            additions_set.delete(record_id)
          else
            removals_set.add(record_id)
          end
        end
      end
    end

    def queries
      queries_set = Redis::Set.new(self.class.name)
      queries_set.members.reduce({}) do |acc, key|
        query_hash = Redis::HashKey.new(key)
        if query_hash.exists?
          acc.merge(key => query_hash)
        else
          queries_set.delete(key)
          acc
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
query_dam-0.1.1 lib/query_dam/concerns/trackable.rb