Sha256: c76743ae51a060caea0e1a02d52db2dee7bd6bffdbd2d2bb0c1cd7711cb4af98

Contents?: true

Size: 1.25 KB

Versions: 11

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module IronBank
  # Use the provided cache if present.
  #
  module Cacheable
    def reload
      remove_instance_vars
      @remote = self.class.find(id, force: true).remote
    end

    private

    def remove_instance_vars
      # Substract predefined variables from the instance variables
      (instance_variables - [:@remote]).each do |var|
        remove_instance_variable(:"#{var}")
      end
    end

    def cache
      self.class.cache
    end

    # Override queryable class methods to use cache if present.
    #
    module ClassMethods
      def find(id, force: false)
        return super(id) unless cache

        cache.fetch(id, force: force) { super(id) }
      end

      def where(conditions)
        # Conditions can be empty when called from #all, it does not make sense
        # to try to cache all records returned then.
        return super if conditions.empty?

        return super unless cache

        # Ensure we are not colliding when the conditions are similar for two
        # different resources, like Account and Subscription.
        cache_key = conditions.merge(object_name: name)
        cache.fetch(cache_key) { super }
      end

      def cache
        IronBank.configuration.cache
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
iron_bank-2.2.0 lib/iron_bank/cacheable.rb
iron_bank-2.1.0 lib/iron_bank/cacheable.rb
iron_bank-2.0.2 lib/iron_bank/cacheable.rb
iron_bank-2.0.1 lib/iron_bank/cacheable.rb
iron_bank-2.0.0 lib/iron_bank/cacheable.rb
iron_bank-1.0.4 lib/iron_bank/cacheable.rb
iron_bank-1.0.3 lib/iron_bank/cacheable.rb
iron_bank-1.0.2 lib/iron_bank/cacheable.rb
iron_bank-1.0.1 lib/iron_bank/cacheable.rb
iron_bank-1.0.0 lib/iron_bank/cacheable.rb
iron_bank-0.7.1 lib/iron_bank/cacheable.rb