From b89f071881832704a41b67cc796e8f80d585f4dd Mon Sep 17 00:00:00 2001 From: Kevin Dew Date: Thu, 12 Dec 2019 23:50:48 +0000 Subject: [PATCH] Use local cache Rack middleware with BulkData::Cache This sets up a local cache that wraps around the Redis cache layer of BulkData::Cache during the duration of a request. In order for this to work in a development environment we need the BulkData::Cache class not to be reloaded automatically. I achieved this by doing direct require calls. I first tried using the Rails autoload_once_paths option but didn't have much luck. As an example, before fixed require calls: ``` irb(main):002:0> BulkData::Cache.object_id => 70342543814920 irb(main):003:0> reload! Reloading... => true irb(main):004:0> BulkData::Cache.object_id => 70342595490220 ``` and after: ``` irb(main):002:0> BulkData::Cache.object_id => 70249028613320 irb(main):004:0> reload! Reloading... => true irb(main):005:0> BulkData::Cache.object_id => 70249028613320 ``` --- config/initializers/bulk_data_rack_middleware.rb | 14 ++++++++++++++ lib/bulk_data/cache.rb | 3 +++ 2 files changed, 17 insertions(+) create mode 100644 config/initializers/bulk_data_rack_middleware.rb diff --git a/config/initializers/bulk_data_rack_middleware.rb b/config/initializers/bulk_data_rack_middleware.rb new file mode 100644 index 0000000000..10397735df --- /dev/null +++ b/config/initializers/bulk_data_rack_middleware.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +require "bulk_data/cache" + +# This is used to set a local cache that runs on BulkData for the duration of +# a request. This means if we look up the same item in the cache multiple +# times during a single request it will only hit Redis once and then look up +# the item in memory. +# +# For more details see: https://github.com/rails/rails/blob/fa292703e1b733a7a55a8d6f0d749ddf590c61fd/activesupport/lib/active_support/cache/strategy/local_cache.rb +Rails.application.config.middleware.insert_before( + ::Rack::Runtime, + BulkData::Cache.middleware, +) diff --git a/lib/bulk_data/cache.rb b/lib/bulk_data/cache.rb index f57fdc2b4a..40330b405d 100644 --- a/lib/bulk_data/cache.rb +++ b/lib/bulk_data/cache.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "bulk_data" + module BulkData class Cache include Singleton @@ -8,6 +10,7 @@ class NoEntryError < RuntimeError; end class << self delegate :cache, to: :instance + delegate :clear, :middleware, to: :cache end attr_reader :cache