Sha256: e288d1e95416e1022fe99a2233de58a45ce13d73bee6de7631653555b17cb943

Contents?: true

Size: 843 Bytes

Versions: 4

Compression:

Stored size: 843 Bytes

Contents

# frozen_string_literal: true

module AdequateSerialization
  module Rails
    module CacheKey
      def self.cacheable?(object)
        if object.class < ActiveRecord::Base
          object.has_attribute?(:updated_at)
        else
          object.respond_to?(:cache_key)
        end
      end

      def self.for(object, includes = [])
        includes.empty? ? object : [object, *includes]
      end
    end

    class CacheStep < Steps::Step
      def apply(response)
        object = response.object
        opts = response.opts

        if opts.options[:multi_caching] || !CacheKey.cacheable?(object)
          return apply_next(response)
        end

        ::Rails.cache.fetch(CacheKey.for(object, opts.includes)) do
          apply_next(response)
        end
      end
    end

    AdequateSerialization.prepend(CacheStep)
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
adequate_serialization-2.0.1 lib/adequate_serialization/rails/cache_step.rb
adequate_serialization-2.0.0 lib/adequate_serialization/rails/cache_step.rb
adequate_serialization-1.0.1 lib/adequate_serialization/rails/cache_step.rb
adequate_serialization-1.0.0 lib/adequate_serialization/rails/cache_step.rb