Skip to content

Commit

Permalink
Use local cache Rack middleware with BulkData::Cache
Browse files Browse the repository at this point in the history
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
```
  • Loading branch information
kevindew committed Dec 12, 2019
1 parent 6845130 commit b89f071
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
14 changes: 14 additions & 0 deletions config/initializers/bulk_data_rack_middleware.rb
Original file line number Diff line number Diff line change
@@ -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,
)
3 changes: 3 additions & 0 deletions lib/bulk_data/cache.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require "bulk_data"

module BulkData
class Cache
include Singleton
Expand All @@ -8,6 +10,7 @@ class NoEntryError < RuntimeError; end

class << self
delegate :cache, to: :instance
delegate :clear, :middleware, to: :cache
end

attr_reader :cache
Expand Down

0 comments on commit b89f071

Please sign in to comment.