Sha256: c30848c832fae466ac015ee1436214d75f79e7898436b0af86d99113a0463c09

Contents?: true

Size: 1.27 KB

Versions: 12

Compression:

Stored size: 1.27 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
      self
    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

12 entries across 12 versions & 1 rubygems

Version Path
iron_bank-3.3.4 lib/iron_bank/cacheable.rb
iron_bank-3.3.3 lib/iron_bank/cacheable.rb
iron_bank-3.3.2 lib/iron_bank/cacheable.rb
iron_bank-3.3.1 lib/iron_bank/cacheable.rb
iron_bank-3.3.0 lib/iron_bank/cacheable.rb
iron_bank-3.2.0 lib/iron_bank/cacheable.rb
iron_bank-3.1.1 lib/iron_bank/cacheable.rb
iron_bank-3.1.0 lib/iron_bank/cacheable.rb
iron_bank-3.0.3 lib/iron_bank/cacheable.rb
iron_bank-3.0.2 lib/iron_bank/cacheable.rb
iron_bank-3.0.1 lib/iron_bank/cacheable.rb
iron_bank-3.0.0 lib/iron_bank/cacheable.rb