Sha256: a4fcf238efe0855a64eb0b6e543eccd0b1f24da9f90d0c0d9f66608d6b180888

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

module AdequateSerialization
  module CacheRefresh
    class CacheRefreshJob < ActiveJob::Base
      using(
        Module.new do
          # The association will return a relation if it's a `has_many` or a
          # `has_many_through` regardless of how many associated records exist.
          refine ActiveRecord::Relation do
            def refresh
              return unless any?

              update_all(updated_at: Time.now)
              find_each(&:as_json)
            end
          end

          # The association will return a record if it's a `has_one` and it was
          # previously created.
          refine ActiveRecord::Base do
            def refresh
              touch
              as_json
            end
          end

          # The association will return a `nil` if it's a `has_one` and it was
          # not yet created.
          refine NilClass do
            def refresh; end
          end
        end
      )

      queue_as AdequateSerialization.active_job_queue
      discard_on ActiveJob::DeserializationError

      def perform(record)
        record.class.associated_caches.each do |association|
          record.public_send(association).refresh
        end
      end
    end

    def self.extended(base)
      base.after_update_commit { CacheRefreshJob.perform_later(self) }
    end

    def associate_cache(association)
      associated_caches << association
    end

    # The associations that serialize this object in their responses, so that we
    # know to bust their cache when this object is updated.
    def associated_caches
      @associated_caches ||= []
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
adequate_serialization-2.0.1 lib/adequate_serialization/rails/cache_refresh.rb