Skip to content

Commit

Permalink
Extract local cache middleware
Browse files Browse the repository at this point in the history
Extract LocalCache Middleware, so it can requires rack dependencies,
without adding rack dependencies to `AS::Cache::Strategy::LocalCache`.
  • Loading branch information
arthurnn committed Feb 24, 2014
1 parent 876e893 commit b2d19a5
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 32 deletions.
34 changes: 2 additions & 32 deletions activesupport/lib/active_support/cache/strategy/local_cache.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
require 'active_support/core_ext/object/duplicable'
require 'active_support/core_ext/string/inflections'
require 'rack/body_proxy'

module ActiveSupport
module Cache
Expand All @@ -9,6 +8,8 @@ module Strategy
# duration of a block. Repeated calls to the cache for the same key will hit the
# in-memory cache for faster access.
module LocalCache
autoload :Middleware, 'active_support/cache/strategy/local_cache_middleware'

# Class for storing and registering the local caches.
class LocalCacheRegistry # :nodoc:
extend ActiveSupport::PerThreadRegistry
Expand Down Expand Up @@ -64,37 +65,6 @@ def delete_entry(key, options)
def with_local_cache
use_temporary_local_cache(LocalStore.new) { yield }
end

#--
# This class wraps up local storage for middlewares. Only the middleware method should
# construct them.
class Middleware # :nodoc:
attr_reader :name, :local_cache_key

def initialize(name, local_cache_key)
@name = name
@local_cache_key = local_cache_key
@app = nil
end

def new(app)
@app = app
self
end

def call(env)
LocalCacheRegistry.set_cache_for(local_cache_key, LocalStore.new)
response = @app.call(env)
response[2] = ::Rack::BodyProxy.new(response[2]) do
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
end
response
rescue Exception
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
raise
end
end

# Middleware class can be inserted as a Rack handler to be local cache for the
# duration of request.
def middleware
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
require 'rack/body_proxy'
module ActiveSupport
module Cache
module Strategy
module LocalCache

#--
# This class wraps up local storage for middlewares. Only the middleware method should
# construct them.
class Middleware # :nodoc:
attr_reader :name, :local_cache_key

def initialize(name, local_cache_key)
@name = name
@local_cache_key = local_cache_key
@app = nil
end

def new(app)
@app = app
self
end

def call(env)
LocalCacheRegistry.set_cache_for(local_cache_key, LocalStore.new)
response = @app.call(env)
response[2] = ::Rack::BodyProxy.new(response[2]) do
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
end
response
rescue Exception
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
raise
end
end
end
end
end
end

0 comments on commit b2d19a5

Please sign in to comment.