Sha256: 5404bbeece38274c39b38fde0752c91e38b8f6c419d80ac3f666ae87535dd22b

Contents?: true

Size: 1.32 KB

Versions: 2

Compression:

Stored size: 1.32 KB

Contents

require 'rack'
require 'active_support/core_ext/string/inflections'

module ActiveRecordMultipleQueryCache
  class Rails4QueryCache
    def initialize(active_record_base_class)
      active_record_base_class = active_record_base_class.constantize if active_record_base_class.is_a?(String)
      @active_record_base_class = active_record_base_class
    end

    def new(app)
      @app = app
      self
    end

    def call(env)
      connection = @active_record_base_class.connection
      enabled = connection.query_cache_enabled
      connection_id = @active_record_base_class.connection_id
      connection.enable_query_cache!

      response = @app.call(env)
      response[2] = Rack::BodyProxy.new(response[2]) do
        restore_query_cache_settings(connection_id, enabled)
      end

      response
    rescue Exception
      restore_query_cache_settings(connection_id, enabled)
      raise
    end

    def name
      self.class.name
    end

    def to_s
      %{#<#{self.class} @active_record_class: "#{@active_record_base_class}">}
    end

    private

    def restore_query_cache_settings(connection_id, enabled)
      @active_record_base_class.connection_id = connection_id
      @active_record_base_class.connection.clear_query_cache
      @active_record_base_class.connection.disable_query_cache! unless enabled
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
active_record_multiple_query_cache-0.1.1 lib/active_record_multiple_query_cache/rails4_query_cache.rb
active_record_multiple_query_cache-0.1.0 lib/active_record_multiple_query_cache/rails4_query_cache.rb