Sha256: 95a0c81c9bec05c43a0f6878718ac004d2913ecc1f31a7b677a2c806192327b0

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

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 |tracking_key, query|
        @_prior_results[tracking_key] =
          self.class.connection.select_values(query).map(&:to_i)
      end
    end

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

        additions_set, updates_set, removals_set =
          QueryDam.query_sets(tracking_key)

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

        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

        [additions_set, updates_set, removals_set]
          .each { |set| set.expire(QueryDam.expiration) }
      end
    end

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

Version data entries

1 entries across 1 versions & 1 rubygems

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