Sha256: bd5e1d3a6acb37847562018dec52b59fa203132a01266c8a5691fb7d7b6f12b0

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 :default
      discard_on ActiveJob::DeserializationError

      def perform(record)
        record.class.serialized_associations.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 serialize_association(association)
      serialized_associations << 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 serialized_associations
      @serialized_associations ||= []
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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